Sanket17 commited on
Commit
5fbd25d
·
1 Parent(s): 55bae0c

added all files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +53 -0
  2. .github/workflows/docker-image.yml +32 -0
  3. .gitignore +50 -0
  4. CreativeMLOpenRAIL-M +82 -0
  5. Dockerfile +15 -0
  6. LICENSE +674 -0
  7. README copy.md +286 -0
  8. README_zh.md +288 -0
  9. cog.yaml +48 -0
  10. docs/api_doc_en.md +983 -0
  11. docs/api_doc_zh.md +987 -0
  12. docs/assets/tasks.png +0 -0
  13. docs/change_logs.md +178 -0
  14. docs/change_logs_zh.md +178 -0
  15. docs/migrate.md +377 -0
  16. docs/migrate_zh.md +377 -0
  17. docs/openapi.json +0 -0
  18. environment.yaml +7 -0
  19. examples/Note.txt +3 -0
  20. examples/examples.ipynb +521 -0
  21. examples/examples_v1.py +266 -0
  22. examples/examples_v2.py +288 -0
  23. extras/BLIP/configs/bert_config.json +21 -0
  24. extras/BLIP/configs/caption_coco.yaml +33 -0
  25. extras/BLIP/configs/med_config.json +21 -0
  26. extras/BLIP/configs/nlvr.yaml +21 -0
  27. extras/BLIP/configs/nocaps.yaml +15 -0
  28. extras/BLIP/configs/pretrain.yaml +27 -0
  29. extras/BLIP/configs/retrieval_coco.yaml +34 -0
  30. extras/BLIP/configs/retrieval_flickr.yaml +34 -0
  31. extras/BLIP/configs/retrieval_msrvtt.yaml +12 -0
  32. extras/BLIP/configs/vqa.yaml +25 -0
  33. extras/BLIP/models/bert_tokenizer/config.json +23 -0
  34. extras/BLIP/models/bert_tokenizer/tokenizer.json +0 -0
  35. extras/BLIP/models/bert_tokenizer/tokenizer_config.json +3 -0
  36. extras/BLIP/models/bert_tokenizer/vocab.txt +0 -0
  37. extras/BLIP/models/blip.py +239 -0
  38. extras/BLIP/models/blip_itm.py +76 -0
  39. extras/BLIP/models/blip_nlvr.py +105 -0
  40. extras/BLIP/models/blip_pretrain.py +339 -0
  41. extras/BLIP/models/blip_retrieval.py +319 -0
  42. extras/BLIP/models/blip_vqa.py +186 -0
  43. extras/BLIP/models/med.py +955 -0
  44. extras/BLIP/models/nlvr_encoder.py +843 -0
  45. extras/BLIP/models/vit.py +308 -0
  46. extras/GroundingDINO/config/GroundingDINO_SwinT_OGC.py +43 -0
  47. extras/GroundingDINO/util/inference.py +100 -0
  48. extras/censor.py +60 -0
  49. extras/expansion.py +129 -0
  50. extras/face_crop.py +50 -0
.dockerignore ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ .DS_Store
3
+ *.ckpt
4
+ *.safetensors
5
+ *.pth
6
+ *.pt
7
+ *.bin
8
+ *.patch
9
+ *.backup
10
+ *.corrupted
11
+ sorted_styles.json
12
+ /language/default.json
13
+ lena.png
14
+ lena_result.png
15
+ lena_test.py
16
+ config.txt
17
+ config_modification_tutorial.txt
18
+ user_path_config.txt
19
+ user_path_config-deprecated.txt
20
+ build_chb.py
21
+ experiment.py
22
+ /modules/*.png
23
+ /venv
24
+ /tmp
25
+ /ui-config.json
26
+ /outputs
27
+ /config.json
28
+ /log
29
+ /webui.settings.bat
30
+ /embeddings
31
+ /styles.csv
32
+ /params.txt
33
+ /styles.csv.bak
34
+ /webui-user.bat
35
+ /webui-user.sh
36
+ /interrogate
37
+ /user.css
38
+ /.idea
39
+ /notification.ogg
40
+ /notification.mp3
41
+ /SwinIR
42
+ /textual_inversion
43
+ .vscode
44
+ /extensions
45
+ /test/stdout.txt
46
+ /test/stderr.txt
47
+ /cache.json*
48
+ /config_states/
49
+ /node_modules
50
+ /package-lock.json
51
+ /.coverage*
52
+ /auth.json
53
+ *.db
.github/workflows/docker-image.yml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Docker Image CI
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - v*
7
+
8
+ jobs:
9
+
10
+ build:
11
+
12
+ runs-on: ubuntu-latest
13
+
14
+ steps:
15
+ -
16
+ name: Set up QEMU
17
+ uses: docker/setup-qemu-action@v3
18
+ -
19
+ name: Set up Docker Buildx
20
+ uses: docker/setup-buildx-action@v3
21
+ -
22
+ name: Login to Docker Hub
23
+ uses: docker/login-action@v3
24
+ with:
25
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
26
+ password: ${{ secrets.DOCKERHUB_TOKEN }}
27
+ -
28
+ name: Build and push
29
+ uses: docker/build-push-action@v5
30
+ with:
31
+ push: true
32
+ tags: konieshadow/fooocus-api:latest,konieshadow/fooocus-api:${{ github.ref_name }}
.gitignore ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ide config
2
+ .idea
3
+ .vscode
4
+
5
+ #runtime
6
+ __pycache__
7
+ .DS_Store
8
+
9
+ # models
10
+ *.ckpt
11
+ *.safetensors
12
+ *.pth
13
+ *.pt
14
+ *.bin
15
+ *.patch
16
+ *.backup
17
+ *.corrupted
18
+
19
+ # environment
20
+ venv
21
+ .venv
22
+ .env
23
+ .conda
24
+ conda
25
+
26
+ # log files
27
+ *.log
28
+ logs
29
+ log
30
+
31
+ # config files
32
+ .cog
33
+ config.txt
34
+ config_modification_tutorial.txt
35
+ user_path_config.txt
36
+ user_path_config-deprecated.txt
37
+ hash_cache.txt
38
+
39
+ sorted_styles.json
40
+ /presets
41
+
42
+ # db
43
+ *.db
44
+
45
+ # cache
46
+ outputs
47
+
48
+ #other
49
+ *.http
50
+ hash_cache.txt
CreativeMLOpenRAIL-M ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2022 Robin Rombach and Patrick Esser and contributors
2
+
3
+ CreativeML Open RAIL-M
4
+ dated August 22, 2022
5
+
6
+ Section I: PREAMBLE
7
+
8
+ Multimodal generative models are being widely adopted and used, and have the potential to transform the way artists, among other individuals, conceive and benefit from AI or ML technologies as a tool for content creation.
9
+
10
+ Notwithstanding the current and potential benefits that these artifacts can bring to society at large, there are also concerns about potential misuses of them, either due to their technical limitations or ethical considerations.
11
+
12
+ In short, this license strives for both the open and responsible downstream use of the accompanying model. When it comes to the open character, we took inspiration from open source permissive licenses regarding the grant of IP rights. Referring to the downstream responsible use, we added use-based restrictions not permitting the use of the Model in very specific scenarios, in order for the licensor to be able to enforce the license in case potential misuses of the Model may occur. At the same time, we strive to promote open and responsible research on generative models for art and content generation.
13
+
14
+ Even though downstream derivative versions of the model could be released under different licensing terms, the latter will always have to include - at minimum - the same use-based restrictions as the ones in the original license (this license). We believe in the intersection between open and responsible AI development; thus, this License aims to strike a balance between both in order to enable responsible open-science in the field of AI.
15
+
16
+ This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model.
17
+
18
+ NOW THEREFORE, You and Licensor agree as follows:
19
+
20
+ 1. Definitions
21
+
22
+ - "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document.
23
+ - "Data" means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License.
24
+ - "Output" means the results of operating a Model as embodied in informational content resulting therefrom.
25
+ - "Model" means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material.
26
+ - "Derivatives of the Model" means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model.
27
+ - "Complementary Material" means the accompanying source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, etc, if any.
28
+ - "Distribution" means any transmission, reproduction, publication or other sharing of the Model or Derivatives of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means - e.g. API-based or web access.
29
+ - "Licensor" means the copyright owner or entity authorized by the copyright owner that is granting the License, including the persons or entities that may have rights in the Model and/or distributing the Model.
30
+ - "You" (or "Your") means an individual or Legal Entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application - e.g. chatbot, translator, image generator.
31
+ - "Third Parties" means individuals or legal entities that are not under common control with Licensor or You.
32
+ - "Contribution" means any work of authorship, including the original version of the Model and any modifications or additions to that Model or Derivatives of the Model thereof, that is intentionally submitted to Licensor for inclusion in the Model by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Model, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
33
+ - "Contributor" means Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Model.
34
+
35
+ Section II: INTELLECTUAL PROPERTY RIGHTS
36
+
37
+ Both copyright and patent grants apply to the Model, Derivatives of the Model and Complementary Material. The Model and Derivatives of the Model are subject to additional terms as described in Section III.
38
+
39
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publicly display, publicly perform, sublicense, and distribute the Complementary Material, the Model, and Derivatives of the Model.
40
+ 3. Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and the Complementary Material, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Model to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model and/or Complementary Material or a Contribution incorporated within the Model and/or Complementary Material constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or Work shall terminate as of the date such litigation is asserted or filed.
41
+
42
+ Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION
43
+
44
+ 4. Distribution and Redistribution. You may host for Third Party remote access purposes (e.g. software-as-a-service), reproduce and distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the following conditions:
45
+ Use-based restrictions as referenced in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (e.g. a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model or Derivatives of the Model are subject to paragraph 5. This provision does not apply to the use of Complementary Material.
46
+ You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License;
47
+ You must cause any modified files to carry prominent notices stating that You changed the files;
48
+ You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model, Derivatives of the Model.
49
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions - respecting paragraph 4.a. - for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License.
50
+ 5. Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Therefore You cannot use the Model and the Derivatives of the Model for the specified restricted uses. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, finetuning, updating, running, training, evaluating and/or reparametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph (paragraph 5).
51
+ 6. The Output You Generate. Except as set forth herein, Licensor claims no rights in the Output You generate using the Model. You are accountable for the Output you generate and its subsequent uses. No use of the output can contravene any provision as stated in the License.
52
+
53
+ Section IV: OTHER PROVISIONS
54
+
55
+ 7. Updates and Runtime Restrictions. To the maximum extent permitted by law, Licensor reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License, update the Model through electronic means, or modify the Output of the Model based on updates. You shall undertake reasonable efforts to use the latest version of the Model.
56
+ 8. Trademarks and related. Nothing in this License permits You to make use of Licensors’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by the Licensors.
57
+ 9. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Model and the Complementary Material (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Model, Derivatives of the Model, and the Complementary Material and assume any risks associated with Your exercise of permissions under this License.
58
+ 10. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Model and the Complementary Material (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
59
+ 11. Accepting Warranty or Additional Liability. While redistributing the Model, Derivatives of the Model and the Complementary Material thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
60
+ 12. If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
61
+
62
+ END OF TERMS AND CONDITIONS
63
+
64
+
65
+
66
+
67
+ Attachment A
68
+
69
+ Use Restrictions
70
+
71
+ You agree not to use the Model or Derivatives of the Model:
72
+ - In any way that violates any applicable national, federal, state, local or international law or regulation;
73
+ - For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
74
+ - To generate or disseminate verifiably false information and/or content with the purpose of harming others;
75
+ - To generate or disseminate personal identifiable information that can be used to harm an individual;
76
+ - To defame, disparage or otherwise harass others;
77
+ - For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;
78
+ - For any use intended to or which has the effect of discriminating against or harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics;
79
+ - To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
80
+ - For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories;
81
+ - To provide medical advice and medical results interpretation;
82
+ - To generate or disseminate information for the purpose to be used for administration of justice, law enforcement, immigration or asylum processes, such as predicting an individual will commit fraud/crime commitment (e.g. by text profiling, drawing causal relationships between assertions made in documents, indiscriminate and arbitrarily-targeted use).
Dockerfile ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM pytorch/pytorch:2.1.0-cuda12.1-cudnn8-runtime
2
+
3
+ ENV TZ=Asia/Shanghai
4
+
5
+ WORKDIR /app
6
+
7
+ COPY . /app
8
+
9
+ RUN pip install --no-cache-dir -r requirements.txt
10
+
11
+ RUN pip install --no-cache-dir opencv-python-headless -i https://pypi.org/simple
12
+
13
+ EXPOSE 8888
14
+
15
+ CMD ["python", "main.py", "--host", "0.0.0.0", "--port", "8888", "--skip-pip"]
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
README copy.md ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [![Docker Image CI](https://github.com/konieshadow/Fooocus-API/actions/workflows/docker-image.yml/badge.svg?branch=main)](https://github.com/konieshadow/Fooocus-API/actions/workflows/docker-image.yml)
2
+
3
+ [ English | [中文](/README_zh.md) ]
4
+
5
+ - [Introduction](#introduction)
6
+ - [Fooocus](#fooocus)
7
+ - [Fooocus-API](#fooocus-api)
8
+ - [Get-Start](#get-start)
9
+ - [Run with Replicate](#run-with-replicate)
10
+ - [Self-hosted](#self-hosted)
11
+ - [conda](#conda)
12
+ - [venv](#venv)
13
+ - [predownload and install](#predownload-and-install)
14
+ - [already exist Fooocus](#already-exist-fooocus)
15
+ - [Start with docker](#start-with-docker)
16
+ - [cmd flags](#cmd-flags)
17
+ - [Change log](#change-log)
18
+ - [Apis](#apis)
19
+ - [License](#license)
20
+ - [Thanks :purple\_heart:](#thanks-purple_heart)
21
+
22
+ > Note:
23
+ >
24
+ > Although I tested it, I still suggest you test it again before the official update
25
+ >
26
+ > Fooocus 2.5 includes a significant update, with most dependencies upgraded. Therefore, after updating, do not use `--skip-pip` unless you have already performed a manual update.
27
+ >
28
+ > Additionally, `groundingdino-py` may encounter installation errors, especially in Chinese Windows environments. The solution can be found in the following [issue](https://github.com/IDEA-Research/GroundingDINO/issues/206).
29
+
30
+
31
+ > GenerateMask is same as DescribeImage, It is not process as a task, result will directly return
32
+
33
+ # Instructions for Using the ImageEnhance Interface
34
+ Below are examples of parameters that include the main parameters required for ImageEnhance. The V1 interface adopts a form-like approach similar to ImagePrompt to break down the enhance controller.
35
+
36
+
37
+ ```python
38
+ {
39
+ "enhance_input_image": "",
40
+ "enhance_checkbox": true,
41
+ "enhance_uov_method": "Vary (Strong)",
42
+ "enhance_uov_processing_order": "Before First Enhancement",
43
+ "enhance_uov_prompt_type": "Original Prompts",
44
+ "save_final_enhanced_image_only": true,
45
+ "enhance_ctrlnets": [
46
+ {
47
+ "enhance_enabled": false,
48
+ "enhance_mask_dino_prompt": "face",
49
+ "enhance_prompt": "",
50
+ "enhance_negative_prompt": "",
51
+ "enhance_mask_model": "sam",
52
+ "enhance_mask_cloth_category": "full",
53
+ "enhance_mask_sam_model": "vit_b",
54
+ "enhance_mask_text_threshold": 0.25,
55
+ "enhance_mask_box_threshold": 0.3,
56
+ "enhance_mask_sam_max_detections": 0,
57
+ "enhance_inpaint_disable_initial_latent": false,
58
+ "enhance_inpaint_engine": "v2.6",
59
+ "enhance_inpaint_strength": 1,
60
+ "enhance_inpaint_respective_field": 0.618,
61
+ "enhance_inpaint_erode_or_dilate": 0,
62
+ "enhance_mask_invert": false
63
+ }
64
+ ]
65
+ }
66
+ ```
67
+
68
+ - enhance_input_image: The image to be enhanced, which is required and can be provided as an image URL for the V2 interface.
69
+ - enhance_checkbox: A toggle switch that must be set to true if you want to use the enhance image feature.
70
+ - save_final_enhanced_image_only: Since image enhancement is a pipeline operation, it can produce multiple result images. This parameter allows you to only return the final enhanced image.
71
+
72
+ There are three parameters related to UpscaleVary, which are used to perform Upscale or Vary before or after enhancement.
73
+
74
+ - enhance_uov_method: Similar to the UpscaleOrVary interface, Disabled turns it off.
75
+ - enhance_uov_processing_order: Determines whether to process the image before or after enhancement.
76
+ - enhance_uov_prompt_type: I'm not sure about the specific function; you might want to research it based on the WebUI.
77
+
78
+ The `enhance_ctrlnets` element is a list of ImageEnhance controller objects, with a maximum of three elements in the list, any additional elements will be discarded. The parameters correspond roughly to the WebUI, and the notable parameters are:
79
+
80
+ - enhance_enabled: This parameter controls whether the enhance controller is active. If there are no enabled enhance controllers, the task will be skipped.
81
+ - enhance_mask_dino_prompt: This parameter is required and indicates the area to be enhanced. If it is empty, even if the enhance controller is enabled, the task will be skipped.
82
+
83
+
84
+ # Introduction
85
+
86
+ FastAPI powered API for [Fooocus](https://github.com/lllyasviel/Fooocus).
87
+
88
+ Currently loaded Fooocus version: [2.3.0](https://github.com/lllyasviel/Fooocus/blob/main/update_log.md).
89
+
90
+ ## Fooocus
91
+
92
+ This part from [Fooocus](https://github.com/lllyasviel/Fooocus) project.
93
+
94
+ Fooocus is an image generating software (based on [Gradio](https://www.gradio.app/)).
95
+
96
+ Fooocus is a rethinking of Stable Diffusion and Midjourney’s designs:
97
+
98
+ - Learned from Stable Diffusion, the software is offline, open source, and free.
99
+
100
+ - Learned from Midjourney, the manual tweaking is not needed, and users only need to focus on the prompts and images.
101
+
102
+ Fooocus has included and automated lots of inner optimizations and quality improvements. Users can forget all those difficult technical parameters, and just enjoy the interaction between human and computer to "explore new mediums of thought and expanding the imaginative powers of the human species"
103
+
104
+ ## Fooocus-API
105
+
106
+ I think you must have tried to use [Gradio client](https://www.gradio.app/docs/client) to call Fooocus, which was a terrible experience for me.
107
+
108
+ Fooocus API uses [FastAPI](https://fastapi.tiangolo.com/) provides the `REST` API for using Fooocus. Now, you can use Fooocus's powerful ability in any language you like.
109
+
110
+ In addition, we also provide detailed [documentation](/docs/api_doc_en.md) and [sample code](/examples)
111
+
112
+ # Get-Start
113
+
114
+ ## Run with Replicate
115
+
116
+ Now you can use Fooocus-API by Replicate, the model is on [konieshadow/fooocus-api](https://replicate.com/konieshadow/fooocus-api).
117
+
118
+ With preset:
119
+
120
+ - [konieshadow/fooocus-api-anime](https://replicate.com/konieshadow/fooocus-api-anime)
121
+ - [konieshadow/fooocus-api-realistic](https://replicate.com/konieshadow/fooocus-api-realistic)
122
+
123
+ I believe this is the easiest way to generate image with Fooocus's power.
124
+
125
+ ## Self-hosted
126
+
127
+ You need python version >= 3.10, or use conda to create a new env.
128
+
129
+ The hardware requirements are what Fooocus needs. You can find detail [here](https://github.com/lllyasviel/Fooocus#minimal-requirement)
130
+
131
+ ### conda
132
+
133
+ You can easily start app follow this step use conda:
134
+
135
+ ```shell
136
+ conda env create -f environment.yaml
137
+ conda activate fooocus-api
138
+ ```
139
+
140
+ and then, run `python main.py` to start app, default, server is listening on `http://127.0.0.1:8888`
141
+
142
+ > If you are running the project for the first time, you may have to wait for a while, during which time the program will complete the rest of the installation and download the necessary models. You can also do these steps manually, which I'll mention later.
143
+
144
+ ### venv
145
+
146
+ Similar to using conda, create a virtual environment, and then start and wait for a while
147
+
148
+ ```powershell
149
+ # windows
150
+ python -m venv venv
151
+ .\venv\Scripts\Activate
152
+ ```
153
+
154
+ ```shell
155
+ # linux
156
+ python -m venv venv
157
+ source venv/bin/activate
158
+ ```
159
+ and then, run `python main.py`
160
+
161
+ ### predownload and install
162
+
163
+ If you want to deal with environmental problems manually and download the model in advance, you can refer to the following steps
164
+
165
+ After creating a complete environment using conda or venv, you can manually complete the installation of the subsequent environment, just follow
166
+
167
+ first, install requirements: `pip install -r requirements.txt`
168
+
169
+ then, pytorch with cuda: `pip install torch==2.1.0 torchvision==0.16.0 torchaudio==2.1.0 --index-url https://download.pytorch.org/whl/cu121` , you can find more info about this [here](https://pytorch.org/get-started/previous-versions/),
170
+
171
+ > It is important to note that for pytorch and cuda versions, the recommended version of Fooocus is used, which is currently pytorch2.1.0+cuda12.1. If you insist, you can also use other versions, but you need to add `--skip-pip` when you start app, otherwise the recommended version will be installed automatically
172
+
173
+ Go to the `repositories` directories, download models and put it into `repositories\Fooocus\models`
174
+
175
+ If you have Fooocus installed, see [already-exist-fooocus](#already-exist-fooocus)
176
+
177
+ here is a list need to download for startup (for different [startup params](#cmd-flags) maybe difference):
178
+
179
+ - checkpoint: path to `repositories\Fooocus\models\checkpoints`
180
+ + [juggernautXL_version6Rundiffusion.safetensors](https://huggingface.co/lllyasviel/fav_models/resolve/main/fav/juggernautXL_version6Rundiffusion.safetensors)
181
+
182
+ - vae_approx: path to `repositories\Fooocus\models\vae_approx`
183
+ + [xlvaeapp.pth](https://huggingface.co/lllyasviel/misc/resolve/main/xlvaeapp.pth)
184
+ + [vaeapp_sd15.pth](https://huggingface.co/lllyasviel/misc/resolve/main/vaeapp_sd15.pt)
185
+ + [xl-to-v1_interposer-v3.1.safetensors](https://huggingface.co/lllyasviel/misc/resolve/main/xl-to-v1_interposer-v3.1.safetensors)
186
+
187
+ - lora: path to `repositories\Fooocus\models\loras`
188
+ + [sd_xl_offset_example-lora_1.0.safetensors](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_offset_example-lora_1.0.safetensors?download=true)
189
+
190
+ > I've uploaded the model I'm using, which contains almost all the base models that Fooocus will use! I put it [here](https://www.123pan.com/s/dF5A-SIQsh.html) 提取码: `D4Mk`
191
+
192
+ ### already exist Fooocus
193
+
194
+ If you already have Fooocus installed, and it is work well, The recommended way is to reuse models, you just simple copy `config.txt` file from your local Fooocus folder to Fooocus-API root folder. See [Customization](https://github.com/lllyasviel/Fooocus#customization) for details.
195
+
196
+ Use this method you will have both Fooocus and Fooocus-API running at the same time. And they operate independently and do not interfere with each other.
197
+
198
+ > Do not copy Fooocus to repositories directory
199
+
200
+ ## Start with docker
201
+
202
+ Before use docker with GPU, you should [install NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html) first.
203
+
204
+ Run
205
+
206
+ ```shell
207
+ docker run -d --gpus=all \
208
+ -e NVIDIA_DRIVER_CAPABILITIES=compute,utility \
209
+ -e NVIDIA_VISIBLE_DEVICES=all \
210
+ -p 8888:8888 konieshadow/fooocus-api
211
+ ```
212
+
213
+ For a more complex usage:
214
+
215
+ ```shell
216
+ mkdir ~/repositories
217
+ mkdir -p ~/.cache/pip
218
+
219
+ docker run -d --gpus=all \
220
+ -e NVIDIA_DRIVER_CAPABILITIES=compute,utility \
221
+ -e NVIDIA_VISIBLE_DEVICES=all \
222
+ -v ~/repositories:/app/repositories \
223
+ -v ~/.cache/pip:/root/.cache/pip \
224
+ -p 8888:8888 konieshadow/fooocus-api
225
+ ```
226
+
227
+ It will be persistent the dependent repositories and pip cache.
228
+
229
+ You can add `-e PIP_INDEX_URL={pypi-mirror-url}` to docker run command to change pip index url.
230
+
231
+ > From version 0.4.0.0, Full environment include in docker image, mapping `models` or project root if you needed
232
+ > For example:
233
+ > ```
234
+ > docker run -d --gpus all \
235
+ > -v /Fooocus-API:/app \
236
+ > -p 8888:8888 konieshadow/fooocus-api
237
+ >```
238
+
239
+ # cmd flags
240
+
241
+ - `-h, --help` show this help message and exit
242
+ - `--port PORT` Set the listen port, default: 8888
243
+ - `--host HOST` Set the listen host, default: 127.0.0.1
244
+ - `--base-url BASE_URL` Set base url for outside visit, default is http://host:port
245
+ - `--log-level LOG_LEVEL` Log info for Uvicorn, default: info
246
+ - `--skip-pip` Skip automatic pip install when setup
247
+ - `--preload-pipeline` Preload pipeline before start http server
248
+ - `--queue-size QUEUE_SIZE` Working queue size, default: 100, generation requests exceeding working queue size will return failure
249
+ - `--queue-history QUEUE_HISTORY` Finished jobs reserve size, tasks exceeding the limit will be deleted, including output image files, default: 0, means no limit
250
+ - `--webhook-url WEBHOOK_URL` Webhook url for notify generation result, default: None
251
+ - `--persistent` Store history to db
252
+ - `--apikey APIKEY` Set apikey to enable secure api, default: None
253
+
254
+ Since v0.3.25, added CMD flags support of Fooocus. You can pass any argument which Fooocus supported.
255
+
256
+ For example, to startup image generation (need more vRAM):
257
+
258
+ ```
259
+ python main.py --all-in-fp16 --always-gpu
260
+ ```
261
+
262
+ For Fooocus CMD flags, see [here](https://github.com/lllyasviel/Fooocus?tab=readme-ov-file#all-cmd-flags).
263
+
264
+
265
+ # Change log
266
+
267
+ [CHANGELOG](./docs/change_logs.md)
268
+
269
+ older change history you can find in [release page](https://github.com/konieshadow/Fooocus-API/releases)
270
+
271
+
272
+ # Apis
273
+
274
+ you can find all api detail [here](/docs/api_doc_en.md)
275
+
276
+ # License
277
+
278
+ This repository is licensed under the [GUN General Public License v3.0](https://github.com/mrhan1993/Fooocus-API/blob/main/LICENSE)
279
+
280
+ The default checkpoint is published by [RunDiffusion](https://huggingface.co/RunDiffusion), is licensed under the [CreativeML Open RAIL-M](https://github.com/mrhan1993/Fooocus-API/blob/main/CreativeMLOpenRAIL-M).
281
+
282
+ or, you can find it [here](https://huggingface.co/spaces/CompVis/stable-diffusion-license)
283
+
284
+ # Thanks :purple_heart:
285
+
286
+ Thanks for all your contributions and efforts towards improving the Fooocus API. We thank you for being part of our :sparkles: community :sparkles:!
README_zh.md ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [![Docker Image CI](https://github.com/konieshadow/Fooocus-API/actions/workflows/docker-image.yml/badge.svg?branch=main)](https://github.com/konieshadow/Fooocus-API/actions/workflows/docker-image.yml)
2
+
3
+ [ [English](/README.md) | 中文 ]
4
+
5
+ - [简介](#简介)
6
+ - [Fooocus](#fooocus)
7
+ - [Fooocus-API](#fooocus-api)
8
+ - [开始](#开始)
9
+ - [在 Replicate 上运行](#在-replicate-上运行)
10
+ - [自托管](#自托管)
11
+ - [conda](#conda)
12
+ - [venv](#venv)
13
+ - [预下载及安装](#预下载及安装)
14
+ - [已经有安装好的 Fooocus](#已经有安装好的-fooocus)
15
+ - [使用Docker启动](#使用docker启动)
16
+ - [命令行参数](#命令行参数)
17
+ - [更新日志](#更新日志)
18
+ - [Apis](#apis)
19
+ - [License](#license)
20
+ - [感谢 :purple\_heart:](#感谢-purple_heart)
21
+
22
+
23
+ > 注意:
24
+ >
25
+ > 尽管我进行了测试,但我仍建议你在正式更新前再测一遍
26
+ >
27
+ > Fooocus 2.5 包含大量更新,其中多数依赖进行了升级,因此,更新后请不要使用 `--skip-pip`. 除非你已经进行过手动更新
28
+ >
29
+ > 此外, `groundingdino-py` 可能会遇到安装错误, 特别是在中文 windows 环境中, 解决办法参考: [issues](https://github.com/IDEA-Research/GroundingDINO/issues/206)
30
+
31
+ > 和 DescribeImage 一样,GenerateMask 不会作为 task 处理而是直接返回结果
32
+
33
+ # ImageEnhance 接口的使用说明
34
+
35
+ 以下面的参数为例,它包含了 ImageEnhance 所需要的主要参数,V1 接口采用和 ImagePrompt 类似的方式将 enhance 控制器拆分成表单形式:
36
+
37
+ ```python
38
+ {
39
+ "enhance_input_image": "",
40
+ "enhance_checkbox": true,
41
+ "enhance_uov_method": "Vary (Strong)",
42
+ "enhance_uov_processing_order": "Before First Enhancement",
43
+ "enhance_uov_prompt_type": "Original Prompts",
44
+ "save_final_enhanced_image_only": true,
45
+ "enhance_ctrlnets": [
46
+ {
47
+ "enhance_enabled": false,
48
+ "enhance_mask_dino_prompt": "face",
49
+ "enhance_prompt": "",
50
+ "enhance_negative_prompt": "",
51
+ "enhance_mask_model": "sam",
52
+ "enhance_mask_cloth_category": "full",
53
+ "enhance_mask_sam_model": "vit_b",
54
+ "enhance_mask_text_threshold": 0.25,
55
+ "enhance_mask_box_threshold": 0.3,
56
+ "enhance_mask_sam_max_detections": 0,
57
+ "enhance_inpaint_disable_initial_latent": false,
58
+ "enhance_inpaint_engine": "v2.6",
59
+ "enhance_inpaint_strength": 1,
60
+ "enhance_inpaint_respective_field": 0.618,
61
+ "enhance_inpaint_erode_or_dilate": 0,
62
+ "enhance_mask_invert": false
63
+ }
64
+ ]
65
+ }
66
+ ```
67
+
68
+ - enhance_input_image:需要增强的图像,如果是 v2 接口,可以提供一个图像 url,必选
69
+ - enhance_checkbox:总开关,使用 enhance image 必须设置为 true
70
+ - save_final_enhanced_image_only:图像增强是一个管道作业,因此会产生多个结果图像,使用该参数仅返回最终图像
71
+
72
+ 有三个和 UpscaleVary 相关的参数,其作用是执行增强之前或完成增强之后执行 Upscale 或 Vary
73
+
74
+ - enhance_uov_method:和 UpscaleOrVary 接口一样,Disabled 是关闭
75
+ - enhance_uov_processing_order:在增强之前处理还是处理增强后的图像
76
+ - enhance_uov_prompt_type:我也不知道具体作用,对着 WebUI 研究研究🧐
77
+
78
+ `enhance_ctrlnets` 元素为 ImageEnhance 控制器对象列表,该列表最多包含 3 个元素,多余会被丢弃。参数和 WebUI 基本一一对应,需要注意的参数是:
79
+
80
+ - enhance_enabled:参数控制该 enhance 控制器是否工作,如果没有开启的 enhance 控制器,任务会被跳过
81
+ - enhance_mask_dino_prompt:该参数必选,表示需要增强的部位,如果该参数为空,即便 enhance 控制器处于开启状态,也会跳过
82
+
83
+ # 简介
84
+
85
+ 使用 FastAPI 构建的 [Fooocus](https://github.com/lllyasviel/Fooocus) 的 API。
86
+
87
+ 当前支持的 Fooocus 版本: [2.5.3](https://github.com/lllyasviel/Fooocus/blob/main/update_log.md)。
88
+
89
+ ## Fooocus
90
+
91
+ **该章节来自 [Fooocus](https://github.com/lllyasviel/Fooocus) 项目。**
92
+
93
+ Fooocus 是一个图像生成软件 (基于 [Gradio](https://www.gradio.app/))。
94
+
95
+ Fooocus 是对于 Stable Diffusion 和 Midjourney 的重新思考以及设计:
96
+
97
+ - 我们学习了 Stable Diffusion 的开源、免费、离线运行。
98
+
99
+ - 我们学习了 Midjourney 的专注,不需要手动调整,专注于描述词以及图像。
100
+
101
+ Fooocus 包含了许多内部优化以及质量改进。 忘记那些复杂困难的技术参数,享受人机交互带来的想象力的突破以及探索新的思维
102
+
103
+ ## Fooocus-API
104
+
105
+ 可能您已经尝试过通过 [Gradio 客户端](https://www.gradio.app/docs/client) 来接入 Fooocus,但您可能发现体验并不理想。
106
+
107
+ Fooocus API 是基于 [FastAPI](https://fastapi.tiangolo.com/) 构建的一系列 `REST` 接口,它们使得利用 Fooocus 的强大功能变得简单易行。现在,您可以使用任何您喜欢的编程语言来轻松地与 Fooocus 进行交互。
108
+
109
+ 此外,我们还提供了详尽的 [API 文档](/docs/api_doc_zh.md) 和丰富的 [示例代码](/examples),以���助您快速上手和深入了解如何有效地利用 Fooocus。
110
+
111
+ # 开始
112
+
113
+ ## 在 Replicate 上运行
114
+
115
+ 现在你可以在 Replicate 上使用 Fooocus-API,在这儿: [konieshadow/fooocus-api](https://replicate.com/konieshadow/fooocus-api).
116
+
117
+ 使用预先调整参数的:
118
+
119
+ - [konieshadow/fooocus-api-anime](https://replicate.com/konieshadow/fooocus-api-anime)
120
+ - [konieshadow/fooocus-api-realistic](https://replicate.com/konieshadow/fooocus-api-realistic)
121
+
122
+ 我认为这是更简单的方法来体验 Fooocus 的强大
123
+
124
+ > 出于某些原因,上述 replicate 上的实例版本无法更新,你可以参照 [push-a-model](https://replicate.com/docs/guides/push-a-model) 部署自己专用的实例。
125
+
126
+ ## 自托管
127
+
128
+ 需要 Python >= 3.10,或者使用 conda、venv 创建一个新的环境
129
+
130
+ 硬件需求来源于 Fooocus。 详细要求可以看[这里](https://github.com/lllyasviel/Fooocus#minimal-requirement)
131
+
132
+ ### conda
133
+
134
+ 按照下面的步骤启动一个 app:
135
+
136
+ ```shell
137
+ conda env create -f environment.yaml
138
+ conda activate fooocus-api
139
+ ```
140
+
141
+ 然后,执行 `python main.py` 启动 app ,默认情况下会监听在 `http://127.0.0.1:8888`
142
+
143
+ > 如果是第一次运行,程序会自动处理完成剩余的环境配置、模型下载等工作,因此会等待一段时间。也可以预先配置好环境、下载模型,后面会提到。
144
+
145
+ ### venv
146
+
147
+ 和使用 conda 类似,创建虚拟环境,启动 app ,等待程序完成环境安装、模型下载
148
+
149
+ ```powershell
150
+ # windows
151
+ python -m venv venv
152
+ .\venv\Scripts\Activate
153
+ ```
154
+
155
+ ```shell
156
+ # linux
157
+ python -m venv venv
158
+ source venv/bin/activate
159
+ ```
160
+ 然后执行 `python main.py`
161
+
162
+ ### 预下载及安装
163
+
164
+ 如果想要手动配置环境以及放置模型,可以参考下面的步骤
165
+
166
+ 在创建完 conda 或者 venv 环境之后,按照下面的步骤手动配置环境、下载模型
167
+
168
+ 首先,安装 requirements: `pip install -r requirements.txt`
169
+
170
+ 然后安装 pytorch+cuda: `pip install torch==2.1.0 torchvision==0.16.0 torchaudio==2.1.0 --index-url https://download.pytorch.org/whl/cu121`
171
+
172
+ 更多安装信息在 pytorch 官方的 [previous-versions](https://pytorch.org/get-started/previous-versions/) 页面找到。
173
+
174
+ > 关于 pytorch 和 cuda 的版本,Fooocus API 使用的是 Fooocus 推荐的版本,目前是 pytorch2.1.0+cuda12.1。如果你是个 "犟种" 非要用其他版本,我测试过也是可以的,不过启动的时候记得加上 `--skip-pip`,否则程序会自动替换为推荐版本。
175
+
176
+ 进入 `repositories` 的目录,下载的模型放到这个目录 `repositories\Fooocus\models`。如果你有一个已经安装完成的 Fooocus,在[这里](#已经有安装好的-fooocus)查看如何复用模型
177
+
178
+ 这里是一个启动必须下载的模型列表 (也可能不一样如果 [启动参数](#命令行参数) 不同的话):
179
+
180
+ - checkpoint: 放到 `repositories\Fooocus\models\checkpoints`
181
+ + [juggernautXL_v8Rundiffusion.safetensors](https://huggingface.co/lllyasviel/fav_models/resolve/main/fav/juggernautXL_v8Rundiffusion.safetensors)
182
+
183
+ - vae_approx: 放到 `repositories\Fooocus\models\vae_approx`
184
+ + [xlvaeapp.pth](https://huggingface.co/lllyasviel/misc/resolve/main/xlvaeapp.pth)
185
+ + [vaeapp_sd15.pth](https://huggingface.co/lllyasviel/misc/resolve/main/vaeapp_sd15.pt)
186
+ + [xl-to-v1_interposer-v3.1.safetensors](https://huggingface.co/lllyasviel/misc/resolve/main/xl-to-v1_interposer-v3.1.safetensors)
187
+
188
+ - lora: 放到 `repositories\Fooocus\models\loras`
189
+ + [sd_xl_offset_example-lora_1.0.safetensors](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_offset_example-lora_1.0.safetensors?download=true)
190
+
191
+ > 国内不好下的到 [这儿](https://www.123pan.com/s/dF5A-SIQsh.html)下载, 提取码: `D4Mk`
192
+
193
+ ### 已经有安装好的 Fooocus
194
+
195
+ 如果你已经有一个安装好的且运行正常的 Fooocus, 推荐的方式是复用模型, 只需要将 Fooocus 根目录下的 `config.txt` 文件复制到 Fooocus API 的根目录即可。 查看 [Customization](https://github.com/lllyasviel/Fooocus#customization) 获取更多细节.
196
+
197
+ 使用这种方法 Fooocus 和 Fooocus API 会同时存在,独立运行互不干扰。
198
+
199
+ > 不要将已安装的 Fooocus 目录复制到 repositories 目录。
200
+
201
+ ## 使用Docker启动
202
+
203
+ 开始之前,先安装 [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html),这是 Docker 可以使用 GPU 的前提。
204
+
205
+ 运行
206
+
207
+ ```shell
208
+ docker run -d --gpus=all \
209
+ -e NVIDIA_DRIVER_CAPABILITIES=compute,utility \
210
+ -e NVIDIA_VISIBLE_DEVICES=all \
211
+ -p 8888:8888 konieshadow/fooocus-api
212
+ ```
213
+
214
+ 一个更实用的例子:
215
+
216
+ ```shell
217
+ mkdir ~/repositories
218
+ mkdir -p ~/.cache/pip
219
+
220
+ docker run -d --gpus=all \
221
+ -e NVIDIA_DRIVER_CAPABILITIES=compute,utility \
222
+ -e NVIDIA_VISIBLE_DEVICES=all \
223
+ -v ~/repositories:/app/repositories \
224
+ -v ~/.cache/pip:/root/.cache/pip \
225
+ -p 8888:8888 konieshadow/fooocus-api
226
+ ```
227
+
228
+ 这里把 `repositories` 和 `pip cache` 映射到了本地
229
+
230
+ 你还可以添加 `-e PIP_INDEX_URL={pypi-mirror-url}` 选项来更换 pip 源
231
+
232
+ > 0.4.0.0 版本开始,镜像包含完整运行环境,因此只需要根据需要将 `models` 或者项目根目录进行映射即可
233
+ > 比如:
234
+ > ```
235
+ > docker run -d --gpus all \
236
+ > -v /Fooocus-API:/app \
237
+ > -p 8888:8888 konieshadow/fooocus-api
238
+ >```
239
+
240
+ # 命令行参数
241
+
242
+ - `-h, --help` 显示本帮助并退出
243
+ - `--port PORT` 设置监听端口,默认:8888
244
+ - `--host HOST` 设置监听地址,默认:127.0.0.1
245
+ - `--base-url BASE_URL` 设置返回结果中的地址,默认是: http://host:port
246
+ - `--log-level LOG_LEVEL` Uvicorn 中的日志等级,默认:info
247
+ - `--skip-pip` 跳过启动时的 pip 安装
248
+ - `--preload-pipeline` 启动 http server 之前加载 pipeline
249
+ - `--queue-size QUEUE_SIZE` 工作队列大小,默认是 100 ,超过队列的请求会返回失败
250
+ - `--queue-history QUEUE_HISTORY` 保留的作业历史,默认 0 即无限制,超过会被删除,包括生成的图像
251
+ - `--webhook-url WEBHOOK_URL` 通知生成结果的 webhook 地址,默认为 None
252
+ - `--persistent` 持久化历史记录到SQLite数据库,默认关闭
253
+ - `--apikey APIKEY` 设置 apikey 以启用安全api,默认值:无
254
+
255
+ 从 v0.3.25 开始, Fooocus 的命令行选项也被支持,你可以在启动时加上 Fooocus 支持的选项
256
+
257
+ 比如(需要更大的显存):
258
+
259
+ ```
260
+ python main.py --all-in-fp16 --always-gpu
261
+ ```
262
+
263
+ 完成的 Fooocus 命令行选项可以在[这儿](https://github.com/lllyasviel/Fooocus?tab=readme-ov-file#all-cmd-flags)找到。
264
+
265
+
266
+ # 更新日志
267
+
268
+ [CHANGELOG](./docs/change_logs_zh.md)
269
+
270
+ 更早的日志可以在 [release page](https://github.com/konieshadow/Fooocus-API/releases) 找到
271
+
272
+
273
+ # Apis
274
+
275
+ 你可以在[这里](/docs/api_doc_zh.md)找到所有的 API 细节
276
+
277
+ # License
278
+
279
+ This repository is licensed under the [GUN General Public License v3.0](https://github.com/mrhan1993/Fooocus-API/blob/main/LICENSE)
280
+
281
+ The default checkpoint is published by [RunDiffusion](https://huggingface.co/RunDiffusion), is licensed under the [CreativeML Open RAIL-M](https://github.com/mrhan1993/Fooocus-API/blob/main/CreativeMLOpenRAIL-M).
282
+
283
+ or, you can find it [here](https://huggingface.co/spaces/CompVis/stable-diffusion-license)
284
+
285
+
286
+ # 感谢 :purple_heart:
287
+
288
+ 感谢所有为改进 Fooocus API 做出贡献和努力的人。再次感谢 :sparkles: 社区万岁 :sparkles:!
cog.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Configuration for Cog ⚙️
2
+ # Reference: https://github.com/replicate/cog/blob/main/docs/yaml.md
3
+
4
+ build:
5
+ # set to true if your model requires a GPU
6
+ gpu: true
7
+ cuda: "12.1"
8
+
9
+ # a list of ubuntu apt packages to install
10
+ system_packages:
11
+ - "libgl1-mesa-glx"
12
+ - "libglib2.0-0"
13
+
14
+ # python version in the form '3.11' or '3.11.4'
15
+ python_version: "3.11"
16
+
17
+ # a list of packages in the format <package-name>==<version>
18
+ python_packages:
19
+ - "torchsde==0.2.5"
20
+ - "einops==0.4.1"
21
+ - "transformers==4.30.2"
22
+ - "safetensors==0.3.1"
23
+ - "accelerate==0.21.0"
24
+ - "pyyaml==6.0"
25
+ - "Pillow==9.2.0"
26
+ - "scipy==1.9.3"
27
+ - "tqdm==4.64.1"
28
+ - "psutil==5.9.5"
29
+ - "pytorch_lightning==1.9.4"
30
+ - "omegaconf==2.2.3"
31
+ - "pygit2==1.12.2"
32
+ - "opencv-contrib-python==4.8.0.74"
33
+ - "onnxruntime==1.16.3"
34
+ - "timm==0.9.2"
35
+ - "torch==2.1.0"
36
+ - "torchvision==0.16.0"
37
+ - "colorlog==6.8.2"
38
+ - "rich==13.7.1"
39
+
40
+ # commands run after the environment is set up
41
+ # run:
42
+ # - "echo env is ready!"
43
+ # - "echo another command if needed"
44
+
45
+ image: "r8.im/konieshadow/fooocus-api"
46
+
47
+ # predict.py defines how predictions are run on your model
48
+ predict: "predict.py:Predictor"
docs/api_doc_en.md ADDED
@@ -0,0 +1,983 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - [Introduction](#introduction)
2
+ - [Fooocus capability related interfaces](#fooocus-capability-related-interfaces)
3
+ - [text-to-image](#text-to-image)
4
+ - [image-upscale-vary](#image-upscale-vary)
5
+ - [image-inpaint-outpaint](#image-inpaint-outpaint)
6
+ - [image-prompt](#image-prompt)
7
+ - [text-to-image-with-image-prompt](#text-to-image-with-image-prompt)
8
+ - [describe](#describe)
9
+ - [all-models](#all-models)
10
+ - [refresh-models](#refresh-models)
11
+ - [styles](#styles)
12
+ - [Fooocus API task related interfaces](#fooocus-api-task-related-interfaces)
13
+ - [job-queue](#job-queue)
14
+ - [query-job](#query-job)
15
+ - [job-history](#job-history)
16
+ - [stop](#stop)
17
+ - [ping](#ping)
18
+ - [webhook](#webhook)
19
+ - [public requests body](#public-requests-params)
20
+ - [AdvanceParams](#advanceparams)
21
+ - [lora](#lora)
22
+ - [response](#response)
23
+
24
+
25
+
26
+ # Introduction
27
+
28
+ Fooocus API are provided more than a dozen REST interfaces now, I roughly divide it into two categories, the first is the ability to call Fooocus, such as generating images, refreshing models, and so on, and the second is related to Fooocus API itself, mainly related to task queries. I will try to illustrate their role and usage and provide examples in the following content.
29
+
30
+ > Almost all interface parameters have default values, which means you only need to send the parameters you are interested in. The complete parameters and default values can be viewed in the table.
31
+
32
+ # Fooocus capability related interfaces
33
+
34
+ ## text-to-image
35
+
36
+ Corresponding to the function of text to image in Fooocus
37
+
38
+ **base info:**
39
+
40
+ ```yaml
41
+ EndPoint: /v1/generation/text-to-image
42
+ Method: Post
43
+ DataType: json
44
+ ```
45
+ **requests params:**
46
+
47
+ | Name | Type | Description |
48
+ |-------------------------|----------------|-------------------------------------------------------------------------------------------------|
49
+ | prompt | string | prompt, default to empty string |
50
+ | negative_prompt | string | negative_prompt |
51
+ | style_selections | List[str] | list of style, must be supported style, you can get all supported [style](#styles) here |
52
+ | performance_selection | Enum | performance_selection, must be one of `Speed`, `Quality`, `Extreme Speed` default to `Speed` |
53
+ | aspect_ratios_selection | str | resolution, default to `1152*896` |
54
+ | image_number | int | the num of image to generate, default to 1 , max num is 32, note: Not a parallel interface |
55
+ | image_seed | int | seed, default to -1, meant random |
56
+ | sharpness | float | sharpness, default to 2.0 , 0-30 |
57
+ | guidance_scale | float | guidance scale, default to 4.0 , 1-30 |
58
+ | base_model_name | str | base model, default to `juggernautXL_version6Rundiffusion.safetensors` |
59
+ | refiner_model_name | str | refiner model, default to `None` |
60
+ | refiner_switch | float | refiner switch, default to 0.5 |
61
+ | loras | List[Lora] | lora list, include conf, lora: [Lora](#lora) |
62
+ | advanced_params | AdvancedParams | Advanced params, [AdvancedParams](#advanceparams) |
63
+ | require_base64 | bool | require base64, default to False |
64
+ | save_meta | bool | save metadata to image, default True |
65
+ | meta_scheme | str | metadata scheme, default 'fooocus', only support 'fooocus' now |
66
+ | save_extension | str | extension for saved image, default 'png' |
67
+ | save_name | str | image name saved, default job_id + seq |
68
+ | read_wildcards_in_order | bool | read wildcards in order, default False |
69
+ | async_process | bool | is async, default to False |
70
+ | webhook_url | str | after async task completed, address for callback, default to None, refer to [webhook](#webhook) |
71
+
72
+ **response params:**
73
+
74
+ Most response have the same structure, but different parts will be specifically explained
75
+
76
+ This interface returns a universal response structure, refer to [response](#response)
77
+
78
+ **request example:**
79
+
80
+ ```python
81
+ host = "http://127.0.0.1:8888"
82
+
83
+ def text2img(params: dict) -> dict:
84
+ """
85
+ text to image
86
+ """
87
+ result = requests.post(url=f"{host}/v1/generation/text-to-image",
88
+ data=json.dumps(params),
89
+ headers={"Content-Type": "application/json"})
90
+ return result.json()
91
+
92
+ result =text2img({
93
+ "prompt": "1girl sitting on the ground",
94
+ "async_process": True})
95
+ print(result)
96
+ ```
97
+
98
+ ## image-upscale-vary
99
+
100
+ Corresponding to the function of Upscale or Variation in Fooocus
101
+
102
+ the requests body for this interface based on [text-to-image](#text-to-image), so I will only list the difference with [text-to-image](#text-to-image)
103
+
104
+ In addition, the interface provides two versions, and there is no functional difference between the two versions, mainly due to slight differences in request methods
105
+
106
+ **base info:**
107
+
108
+ ```yaml
109
+ EndPoint_V1: /v1/generation/image-upscale-vary
110
+ EndPoint_V2: /v2/generation/image-upscale-vary
111
+ Method: Post
112
+ DataType: form|json
113
+ ```
114
+
115
+ ### V1
116
+
117
+ **requests params**
118
+
119
+ | Name | Type | Description |
120
+ |------------------|---------------------|-------------------------------------------------------------------------------------------------------------------------------------------|
121
+ | input_image | string($binary) | binary image |
122
+ | uov_method | Enum | 'Vary (Subtle)','Vary (Strong)','Upscale (1.5x)','Upscale (2x)','Upscale (Fast 2x)','Upscale (Custom)' |
123
+ | upscale_value | float | default to None , 1.0-5.0, magnification, only for uov_method is 'Upscale (Custom)' |
124
+ | style_selections | List[str] | list Fooocus style seg with comma |
125
+ | loras | str(List[Lora]) | list for lora, with configure, lora: [Lora](#lora), example: [{"model_name": "sd_xl_offset_example-lora_1.0.safetensors", "weight": 0.5}] |
126
+ | advanced_params | str(AdvancedParams) | AdvancedParams, AdvancedParams: [AdvancedParams](#advanceparams), send with str, None is available |
127
+
128
+ **response params:**
129
+
130
+ This interface returns a universal response structure, refer to [response](#response)
131
+
132
+ **requests example:**
133
+
134
+ ```python
135
+ # headers should not contain {"Content-Type": "application/json"}
136
+
137
+ host = "http://127.0.0.1:8888"
138
+ image = open("./examples/imgs/bear.jpg", "rb").read()
139
+
140
+ def upscale_vary(image, params: dict) -> dict:
141
+ """
142
+ Upscale or Vary
143
+ """
144
+ response = requests.post(url=f"{host}/v1/generation/image-upscale-vary",
145
+ data=params,
146
+ files={"input_image": image})
147
+ return response.json()
148
+
149
+ result =upscale_vary(image=image,
150
+ params={
151
+ "uov_method": "Upscale (2x)",
152
+ "async_process": True
153
+ })
154
+ print(json.dumps(result, indent=4, ensure_ascii=False))
155
+ ```
156
+
157
+ ### V2
158
+
159
+ **requests params**
160
+
161
+ | Name | Type | Description |
162
+ |---------------|---------------------|---------------------------------------------------------------------------------------------------------------------------------------|
163
+ | uov_method | UpscaleOrVaryMethod | Enum type, value should one of 'Vary (Subtle)','Vary (Strong)','Upscale (1.5x)','Upscale (2x)','Upscale (Fast 2x)','Upscale (Custom)' |
164
+ | upscale_value | float | default to None , 1.0-5.0, magnification, only for uov_method is 'Upscale (Custom)' |
165
+ | input_image | str | input image, base64 str, or a URL |
166
+
167
+ **response params:**
168
+
169
+ This interface returns a universal response structure, refer to [response](#response)
170
+
171
+ **requests params:**
172
+
173
+ ```python
174
+ host = "http://127.0.0.1:8888"
175
+ image = open("./examples/imgs/bear.jpg", "rb").read()
176
+
177
+ def upscale_vary(image, params: dict) -> dict:
178
+ """
179
+ Upscale or Vary
180
+ """
181
+ params["input_image"] = base64.b64encode(image).decode('utf-8')
182
+ response = requests.post(url=f"{host}/v2/generation/image-upscale-vary",
183
+ data=json.dumps(params),
184
+ headers={"Content-Type": "application/json"},
185
+ timeout=300)
186
+ return response.json()
187
+
188
+ result =upscale_vary(image=image,
189
+ params={
190
+ "uov_method": "Upscale (2x)",
191
+ "async_process": True
192
+ })
193
+ print(json.dumps(result, indent=4, ensure_ascii=False))
194
+ ```
195
+
196
+ ## image-inpaint-outpaint
197
+
198
+ **base info:**
199
+
200
+ ```yaml
201
+ EndPoint_V1: /v1/generation/image-inpaint-outpaint
202
+ EndPoint_V2: /v2/generation/image-inpaint-outpaint
203
+ Method: Post
204
+ DataType: form|json
205
+ ```
206
+
207
+ ### V1
208
+
209
+ **requests params**
210
+
211
+ | Name | Type | Description |
212
+ |---------------------------|---------------------|----------------------------------------------------------------------------------------------------------------------------------|
213
+ | input_image | string($binary) | binary image |
214
+ | input_mask | string($binary) | binary image |
215
+ | inpaint_additional_prompt | string | additional_prompt |
216
+ | outpaint_selections | str | Image extension direction , 'Left', 'Right', 'Top', 'Bottom' seg with comma |
217
+ | outpaint_distance_left | int | Image extension distance, default to 0 |
218
+ | outpaint_distance_right | int | Image extension distance, default to 0 |
219
+ | outpaint_distance_top | int | Image extension distance, default to 0 |
220
+ | outpaint_distance_bottom | int | Image extension distance, default to 0 |
221
+ | style_selections | List[str] | list Fooocus style seg with comma |
222
+ | loras | str(List[Lora]) | list for lora, with configure, lora: Lora, example: [{"model_name": "sd_xl_offset_example-lora_1.0.safetensors", "weight": 0.5}] |
223
+ | advanced_params | str(AdvancedParams) | AdvancedParams, AdvancedParams: AdvancedParams, send with str, None is available |
224
+
225
+ **response params:**
226
+
227
+ This interface returns a universal response structure, refer to [response](#response)
228
+
229
+ **requests example:**
230
+
231
+ ```python
232
+ # example for inpaint outpaint v1
233
+ host = "http://127.0.0.1:8888"
234
+ image = open("./examples/imgs/bear.jpg", "rb").read()
235
+
236
+ def inpaint_outpaint(params: dict, input_image: bytes, input_mask: bytes = None) -> dict:
237
+ """
238
+ example for inpaint outpaint v1
239
+ """
240
+ response = requests.post(url=f"{host}/v1/generation/image-inpaint-outpaint",
241
+ data=params,
242
+ files={"input_image": input_image,
243
+ "input_mask": input_mask})
244
+ return response.json()
245
+
246
+ # image extension example
247
+ result = inpaint_outpaint(params={
248
+ "outpaint_selections": "Left,Right",
249
+ "async_process": True},
250
+ input_image=image,
251
+ input_mask=None)
252
+ print(json.dumps(result, indent=4, ensure_ascii=False))
253
+
254
+ # image inpaint example
255
+ source = open("./examples/imgs/s.jpg", "rb").read()
256
+ mask = open("./examples/imgs/m.png", "rb").read()
257
+ result = inpaint_outpaint(params={
258
+ "prompt": "a cat",
259
+ "async_process": True},
260
+ input_image=source,
261
+ input_mask=mask)
262
+ print(json.dumps(result, indent=4, ensure_ascii=False))
263
+ ```
264
+
265
+ ### V2
266
+
267
+ **requests params**
268
+
269
+ | Name | Type | Description |
270
+ |---------------------------|-------------------------|---------------------------------------------------------------------------------|
271
+ | input_image | str | input image, base64 str, or a URL |
272
+ | input_mask | str | input mask, base64 str, or a URL |
273
+ | inpaint_additional_prompt | str | additional prompt |
274
+ | outpaint_selections | List[OutpaintExpansion] | OutpaintExpansion is Enum, value should one of "Left", "Right", "Top", "Bottom" |
275
+ | outpaint_distance_left | int | Image extension distance, default to 0 |
276
+ | outpaint_distance_right | int | Image extension distance, default to 0 |
277
+ | outpaint_distance_top | int | Image extension distance, default to 0 |
278
+ | outpaint_distance_bottom | int | Image extension distance, default to 0 |
279
+
280
+ **response params:**
281
+
282
+ This interface returns a universal response structure, refer to [response](#response)[response params](#response)
283
+
284
+ **requests example:**
285
+
286
+ ```python
287
+ # example for inpaint outpaint v2
288
+ host = "http://127.0.0.1:8888"
289
+ image = open("./examples/imgs/bear.jpg", "rb").read()
290
+
291
+ def inpaint_outpaint(params: dict) -> dict:
292
+ """
293
+ example for inpaint outpaint v2
294
+ """
295
+ response = requests.post(url=f"{host}/v2/generation/image-inpaint-outpaint",
296
+ data=json.dumps(params),
297
+ headers={"Content-Type": "application/json"})
298
+ return response.json()
299
+
300
+ # image extension example
301
+ result = inpaint_outpaint(params={
302
+ "input_image": base64.b64encode(image).decode('utf-8'),
303
+ "input_mask": None,
304
+ "outpaint_selections": ["Left", "Right"],
305
+ "async_process": True})
306
+ print(json.dumps(result, indent=4, ensure_ascii=False))
307
+
308
+ # image inpaint example
309
+ source = open("./examples/imgs/s.jpg", "rb").read()
310
+ mask = open("./examples/imgs/m.png", "rb").read()
311
+ result = inpaint_outpaint(params={
312
+ "prompt": "a cat",
313
+ "input_image": base64.b64encode(source).decode('utf-8'),
314
+ "input_mask": base64.b64encode(mask).decode('utf-8'),
315
+ "async_process": True})
316
+ print(json.dumps(result, indent=4, ensure_ascii=False))
317
+ ```
318
+
319
+ ## image-prompt
320
+
321
+ `v0.3.27` has a break change. Interface based on change to [inpaint-outpaint](#image-inpaint-outpaint)
322
+
323
+ after v0.3.27, this interface implements the functions of `inpaint_outpaint` and `image-prompt`.
324
+
325
+ > Multi-function interface, which does not implement the functions of `inpaint_outpaint` and `image-prompt` at the same time in the same request
326
+
327
+ **base info:**
328
+
329
+ ```yaml
330
+ EndPoint_V1: /v1/generation/image-prompt
331
+ EndPoint_V2: /v2/generation/image-prompt
332
+ Method: Post
333
+ DataType: form|json
334
+ ```
335
+
336
+ ### V1
337
+
338
+ **requests params**
339
+
340
+ | Name | Type | Description |
341
+ |---------------------------|---------------------|----------------------------------------------------------------------------------------------------------------------------------|
342
+ | input_image | Bytes | binary image, use for inpaint |
343
+ | input_mask | Bytes | binary image mask, use for inpaint |
344
+ | inpaint_additional_prompt | str | inpaint additional prompt |
345
+ | outpaint_selections | str | Image extension direction , 'Left', 'Right', 'Top', 'Bottom' seg with comma |
346
+ | outpaint_distance_left | int | Image extension distance, default to 0 |
347
+ | outpaint_distance_right | int | Image extension distance, default to 0 |
348
+ | outpaint_distance_top | int | Image extension distance, default to 0 |
349
+ | outpaint_distance_bottom | int | Image extension distance, default to 0 |
350
+ | cn_img1 | string($binary) | binary image |
351
+ | cn_stop1 | float | default to 0.6 |
352
+ | cn_weight1 | float | default to 0.6 |
353
+ | cn_type1 | Enum | should one of "ImagePrompt", "FaceSwap", "PyraCanny", "CPDS" |
354
+ | cn_img2 | string($binary) | binary image |
355
+ | cn_stop2 | float | default to 0.6 |
356
+ | cn_weight2 | float | default to 0.6 |
357
+ | cn_type2 | Enum | should one of "ImagePrompt", "FaceSwap", "PyraCanny", "CPDS" |
358
+ | cn_img3 | string($binary) | binary image |
359
+ | cn_stop3 | float | default to 0.6 |
360
+ | cn_weight3 | float | default to 0.6 |
361
+ | cn_type3 | Enum | should one of "ImagePrompt", "FaceSwap", "PyraCanny", "CPDS" |
362
+ | cn_img4 | string($binary) | binary image |
363
+ | cn_stop4 | float | default to 0.6 |
364
+ | cn_weight4 | float | default to 0.6 |
365
+ | cn_type4 | Enum | should one of "ImagePrompt", "FaceSwap", "PyraCanny", "CPDS" |
366
+ | style_selections | List[str] | list Fooocus style seg with comma |
367
+ | loras | str(List[Lora]) | list for lora, with configure, lora: Lora, example: [{"model_name": "sd_xl_offset_example-lora_1.0.safetensors", "weight": 0.5}] |
368
+ | advanced_params | str(AdvancedParams) | AdvancedParams, AdvancedParams: AdvancedParams, send with str, None is available |
369
+
370
+ **response params:**
371
+
372
+ This interface returns a universal response structure, refer to [response](#response)[response params](#response)
373
+
374
+ **requests example:**
375
+
376
+ ```python
377
+ # image_prompt v1 example
378
+ host = "http://127.0.0.1:8888"
379
+ image = open("./examples/imgs/bear.jpg", "rb").read()
380
+ source = open("./examples/imgs/s.jpg", "rb").read()
381
+ mask = open("./examples/imgs/m.png", "rb").read()
382
+
383
+ def image_prompt(params: dict,
384
+ input_image: bytes=None,
385
+ input_mask: bytes=None,
386
+ cn_img1: bytes=None,
387
+ cn_img2: bytes=None,
388
+ cn_img3: bytes=None,
389
+ cn_img4: bytes=None,) -> dict:
390
+ """
391
+ image prompt
392
+ """
393
+ response = requests.post(url=f"{host}/v1/generation/image-prompt",
394
+ data=params,
395
+ files={
396
+ "input_image": input_image,
397
+ "input_mask": input_mask,
398
+ "cn_img1": cn_img1,
399
+ "cn_img2": cn_img2,
400
+ "cn_img3": cn_img3,
401
+ "cn_img4": cn_img4,
402
+ })
403
+ return response.json()
404
+
405
+ # image extend
406
+ params = {
407
+ "outpaint_selections": ["Left", "Right"],
408
+ "image_prompts": [] # required, can be empty list
409
+ }
410
+ result = image_prompt(params=params, input_image=image)
411
+ print(json.dumps(result, indent=4, ensure_ascii=False))
412
+
413
+ # inpaint
414
+
415
+ params = {
416
+ "prompt": "1girl sitting on the chair",
417
+ "image_prompts": [], # required, can be empty list
418
+ "async_process": True
419
+ }
420
+ result = image_prompt(params=params, input_image=source, input_mask=mask)
421
+ print(json.dumps(result, indent=4, ensure_ascii=False))
422
+
423
+ # image prompt
424
+
425
+ params = {
426
+ "prompt": "1girl sitting on the chair",
427
+ "image_prompts": [
428
+ {
429
+ "cn_stop": 0.6,
430
+ "cn_weight": 0.6,
431
+ "cn_type": "ImagePrompt"
432
+ },{
433
+ "cn_stop": 0.6,
434
+ "cn_weight": 0.6,
435
+ "cn_type": "ImagePrompt"
436
+ }]
437
+ }
438
+ result = image_prompt(params=params, cn_img1=image, cn_img2=source)
439
+ print(json.dumps(result, indent=4, ensure_ascii=False))
440
+ ```
441
+
442
+ ### V2
443
+
444
+ **requests params**
445
+
446
+ | Name | Type | Description |
447
+ |---------------------------|-------------------|-----------------------------------------------------------------------------|
448
+ | input_image | str | base64 image, or a URL, use for inpaint |
449
+ | input_mask | str | base64 image mask, or a URL, use for inpaint |
450
+ | inpaint_additional_prompt | str | inpaint additional prompt |
451
+ | outpaint_selections | List[] | Image extension direction , 'Left', 'Right', 'Top', 'Bottom' seg with comma |
452
+ | outpaint_distance_left | int | Image extension distance, default to 0 |
453
+ | outpaint_distance_right | int | Image extension distance, default to 0 |
454
+ | outpaint_distance_top | int | Image extension distance, default to 0 |
455
+ | outpaint_distance_bottom | int | Image extension distance, default to 0 |
456
+ | image_prompts | List[ImagePrompt] | image list, include config, ImagePrompt struct: |
457
+
458
+ **ImagePrompt**
459
+
460
+ | Name | Type | Description |
461
+ |-----------|----------------|-----------------------------------------------------------------------------------|
462
+ | cn_img | str | input image, base64 str, or a URL |
463
+ | cn_stop | float | 0-1, default to 0.5 |
464
+ | cn_weight | float | weight, 0-2, default to 1.0 |
465
+ | cn_type | ControlNetType | ControlNetType Enum, should one of "ImagePrompt", "FaceSwap", "PyraCanny", "CPDS" |
466
+
467
+ **response params:**
468
+
469
+ This interface returns a universal response structure, refer to [response](#response)[response params](#response)
470
+
471
+ **requests example:**
472
+
473
+ ```python
474
+ # image_prompt v2 example
475
+ host = "http://127.0.0.1:8888"
476
+ image = open("./examples/imgs/bear.jpg", "rb").read()
477
+ source = open("./examples/imgs/s.jpg", "rb").read()
478
+ mask = open("./examples/imgs/m.png", "rb").read()
479
+
480
+ def image_prompt(params: dict) -> dict:
481
+ """
482
+ image prompt
483
+ """
484
+ response = requests.post(url=f"{host}/v2/generation/image-prompt",
485
+ data=json.dumps(params),
486
+ headers={"Content-Type": "application/json"})
487
+ return response.json()
488
+
489
+ # image extend
490
+ params = {
491
+ "input_image": base64.b64encode(image).decode('utf-8'),
492
+ "outpaint_selections": ["Left", "Right"],
493
+ "image_prompts": [] # required, can be empty list
494
+ }
495
+ result = image_prompt(params)
496
+ print(json.dumps(result, indent=4, ensure_ascii=False))
497
+
498
+ # inpaint
499
+
500
+ params = {
501
+ "prompt": "1girl sitting on the chair",
502
+ "input_image": base64.b64encode(source).decode('utf-8'),
503
+ "input_mask": base64.b64encode(mask).decode('utf-8'),
504
+ "image_prompts": [], # required, can be empty list
505
+ "async_process": True
506
+ }
507
+ result = image_prompt(params)
508
+ print(json.dumps(result, indent=4, ensure_ascii=False))
509
+
510
+ # image prompt
511
+
512
+ params = {
513
+ "prompt": "1girl sitting on the chair",
514
+ "image_prompts": [
515
+ {
516
+ "cn_img": base64.b64encode(source).decode('utf-8'),
517
+ "cn_stop": 0.6,
518
+ "cn_weight": 0.6,
519
+ "cn_type": "ImagePrompt"
520
+ },{
521
+ "cn_img": base64.b64encode(image).decode('utf-8'),
522
+ "cn_stop": 0.6,
523
+ "cn_weight": 0.6,
524
+ "cn_type": "ImagePrompt"
525
+ }]
526
+ }
527
+ result = image_prompt(params)
528
+ print(json.dumps(result, indent=4, ensure_ascii=False))
529
+ ```
530
+
531
+ ## text to image with image prompt
532
+
533
+ this interface only provides v2 version
534
+
535
+ **base info:**
536
+
537
+ ```yaml
538
+ EndPoint: /v2/generation/text-to-image-with-ip
539
+ Method: Post
540
+ DataType: json
541
+ ```
542
+
543
+ **requests params**
544
+
545
+ | Name | Type | Description |
546
+ |---------------|-------------------|-------------|
547
+ | image_prompts | List[ImagePrompt] | Image list |
548
+
549
+ **requests example**:
550
+
551
+ ```python
552
+ # text to image with image prompt example
553
+ host = "http://127.0.0.1:8888"
554
+ image = open("./examples/imgs/bear.jpg", "rb").read()
555
+ source = open("./examples/imgs/s.jpg", "rb").read()
556
+ def image_prompt(params: dict) -> dict:
557
+ """
558
+ image prompt
559
+ """
560
+ response = requests.post(url=f"{host}/v2/generation/text-to-image-with-ip",
561
+ data=json.dumps(params),
562
+ headers={"Content-Type": "application/json"})
563
+ return response.json()
564
+
565
+ params = {
566
+ "prompt": "A bear",
567
+ "image_prompts": [
568
+ {
569
+ "cn_img": base64.b64encode(source).decode('utf-8'),
570
+ "cn_stop": 0.6,
571
+ "cn_weight": 0.6,
572
+ "cn_type": "ImagePrompt"
573
+ },{
574
+ "cn_img": base64.b64encode(image).decode('utf-8'),
575
+ "cn_stop": 0.6,
576
+ "cn_weight": 0.6,
577
+ "cn_type": "ImagePrompt"
578
+ }
579
+ ]
580
+ }
581
+ result = image_prompt(params)
582
+ print(json.dumps(result, indent=4, ensure_ascii=False))
583
+ ```
584
+
585
+ ## describe
586
+
587
+ **base info:**
588
+
589
+ ```yaml
590
+ EndPoint: /v1/tools/describe-image
591
+ Method: Post
592
+ DataType: form
593
+ ```
594
+
595
+ **requests params**
596
+
597
+ | Name | Type | Description |
598
+ |------|------|------------------------------------------|
599
+ | type | Enum | type, should be one of "Photo", "Anime" |
600
+
601
+ **requests example**:
602
+
603
+ ```python
604
+ def describe_image(image: bytes,
605
+ params: dict = {"type": "Photo"}) -> dict:
606
+ """
607
+ describe-image
608
+ """
609
+ response = requests.post(url="http://127.0.0.1:8888/v1/tools/describe-image",
610
+ params=params,
611
+ files={
612
+ "image": image
613
+ },
614
+ timeout=30)
615
+ return response.json()
616
+ ```
617
+
618
+ **response example**:
619
+
620
+ ```python
621
+ {
622
+ "describe": "a young woman posing with her hands behind her head"
623
+ }
624
+ ```
625
+
626
+ --------------------------------------------
627
+
628
+ ## all-models
629
+
630
+ **base info:**
631
+
632
+ ```yaml
633
+ EndPoint: /v1/engines/all-models
634
+ Method: Get
635
+ ```
636
+
637
+ **requests example**:
638
+
639
+ ```python
640
+ def all_models() -> dict:
641
+ """
642
+ all-models
643
+ """
644
+ response = requests.get(url="http://127.0.0.1:8888/v1/engines/all-models",
645
+ timeout=30)
646
+ return response.json()
647
+ ```
648
+
649
+ **response params**:
650
+
651
+ ```python
652
+ {
653
+ "model_filenames": [
654
+ "juggernautXL_version6Rundiffusion.safetensors",
655
+ "sd_xl_base_1.0_0.9vae.safetensors",
656
+ "sd_xl_refiner_1.0_0.9vae.safetensors"
657
+ ],
658
+ "lora_filenames": [
659
+ "sd_xl_offset_example-lora_1.0.safetensors"
660
+ ]
661
+ }
662
+ ```
663
+
664
+ ## refresh-models
665
+
666
+ **base info:**
667
+
668
+ ```yaml
669
+ EndPoint: /v1/engines/refresh-models
670
+ Method: Post
671
+ ```
672
+
673
+ > Removed, use [all-models](#all-models) instead
674
+
675
+ **requests example**
676
+ ```python
677
+ def refresh() -> dict:
678
+ """
679
+ refresh-models
680
+ """
681
+ response = requests.post(url="http://127.0.0.1:8888/v1/engines/refresh-models",
682
+ timeout=30)
683
+ return response.json()
684
+ ```
685
+
686
+ **response params**
687
+ ```python
688
+ {
689
+ "model_filenames": [
690
+ "juggernautXL_version6Rundiffusion.safetensors",
691
+ "sd_xl_base_1.0_0.9vae.safetensors",
692
+ "sd_xl_refiner_1.0_0.9vae.safetensors"
693
+ ],
694
+ "lora_filenames": [
695
+ "sd_xl_offset_example-lora_1.0.safetensors"
696
+ ]
697
+ }
698
+ ```
699
+
700
+ ## styles
701
+
702
+ **base info:**
703
+
704
+ ```yaml
705
+ EndPoint: /v1/engines/styles
706
+ Method: Get
707
+ ```
708
+
709
+ **requests example**:
710
+
711
+ ```python
712
+ def styles() -> dict:
713
+ """
714
+ styles
715
+ """
716
+ response = requests.get(url="http://127.0.0.1:8888/v1/engines/styles",
717
+ timeout=30)
718
+ return response.json()
719
+ ```
720
+
721
+ **response params**:
722
+
723
+ ```python
724
+ [
725
+ "Fooocus V2",
726
+ "Fooocus Enhance",
727
+ ...
728
+ "Watercolor 2",
729
+ "Whimsical And Playful"
730
+ ]
731
+ ```
732
+
733
+ # Fooocus API task related interfaces
734
+
735
+ ## job-queue
736
+
737
+ **base info:**
738
+
739
+ ```yaml
740
+ EndPoint: /v1/engines/job-queue
741
+ Method: Get
742
+ ```
743
+
744
+ **requests example**:
745
+
746
+ ```python
747
+ def job_queue() -> dict:
748
+ """
749
+ job-queue
750
+ """
751
+ response = requests.get(url="http://127.0.0.1:8888/v1/generation/job-queue",
752
+ timeout=30)
753
+ return response.json()
754
+ ```
755
+
756
+ **response params**:
757
+
758
+ ```python
759
+ {
760
+ "running_size": 0,
761
+ "finished_size": 1,
762
+ "last_job_id": "cac3914a-926d-4b6f-a46a-83794a0ce1d4"
763
+ }
764
+ ```
765
+
766
+ ## query-job
767
+
768
+ **base info:**
769
+
770
+ ```yaml
771
+ EndPoint: /v1/generation/query-job
772
+ Method: Get
773
+ ```
774
+
775
+ **requests example**:
776
+ ```python
777
+ def taskResult(task_id: str) -> dict:
778
+ # get task status
779
+ task_status = requests.get(url="http://127.0.0.1:8888/v1/generation/query-job",
780
+ params={"job_id": task_id,
781
+ "require_step_preview": False},
782
+ timeout=30)
783
+
784
+ return task_status.json()
785
+ ```
786
+
787
+ **response params**:
788
+ ```python
789
+ {
790
+ "job_id": "cac3914a-926d-4b6f-a46a-83794a0ce1d4",
791
+ "job_type": "Text to Image",
792
+ "job_stage": "SUCCESS",
793
+ "job_progress": 100,
794
+ "job_status": "Finished",
795
+ "job_step_preview": null,
796
+ "job_result": [
797
+ {
798
+ "base64": null,
799
+ "url": "http://127.0.0.1:8888/files/2023-11-27/b928e50e-3c09-4187-a3f9-1c12280bfd95.png",
800
+ "seed": 8228839561385006000,
801
+ "finish_reason": "SUCCESS"
802
+ }
803
+ ]
804
+ }
805
+ ```
806
+
807
+ ## job-history
808
+
809
+ **base info:**
810
+
811
+ ```yaml
812
+ EndPoint: /v1/generation/job-history
813
+ Method: get
814
+ ```
815
+
816
+ **requests example**:
817
+
818
+ ```python
819
+ def job-history() -> dict:
820
+ """
821
+ job-history
822
+ """
823
+ response = requests.get(url="http://127.0.0.1:8888/v1/generation/job-history",
824
+ timeout=30)
825
+ return response.json()
826
+ ```
827
+
828
+ **response params**:
829
+
830
+ ```python
831
+ {
832
+ "queue": [],
833
+ "history": [
834
+ "job_id": "cac3914a-926d-4b6f-a46a-83794a0ce1d4",
835
+ "is_finished": True
836
+ ]
837
+ }
838
+ ```
839
+
840
+ ## stop
841
+
842
+ **base info:**
843
+
844
+ ```yaml
845
+ EndPoint: /v1/generation/stop
846
+ Method: post
847
+ ```
848
+
849
+ **requests example**:
850
+
851
+ ```python
852
+ def stop() -> dict:
853
+ """
854
+ stop
855
+ """
856
+ response = requests.post(url="http://127.0.0.1:8888/v1/generation/stop",
857
+ timeout=30)
858
+ return response.json()
859
+ ```
860
+
861
+ **response params**:
862
+
863
+ ```python
864
+ {
865
+ "msg": "success"
866
+ }
867
+ ```
868
+
869
+ ## ping
870
+
871
+ **base info:**
872
+
873
+ ```yaml
874
+ EndPoint: /ping
875
+ Method: get
876
+ ```
877
+
878
+ pong
879
+
880
+ # webhook
881
+
882
+ You can specify an address through '--webhook_url' on the command line so that you can receive notifications after asynchronous tasks are completed
883
+
884
+ Here is a simple example to demonstrate how 'webhook' works
885
+
886
+ First,start a simple server using the following code:
887
+
888
+ ```python
889
+ from fastapi import FastAPI
890
+ import uvicorn
891
+
892
+ app = FastAPI()
893
+
894
+ @app.post("/status")
895
+ async def status(requests: dict):
896
+ print(requests)
897
+
898
+ uvicorn.run(app, host="0.0.0.0", port=8000)
899
+ ```
900
+
901
+ Then, start Fooocus API with `--webhook-url http://host:8000/status`
902
+
903
+ Submit a task in any way, and after completion, you will see the task completion information in the background of this simple server:
904
+
905
+ ```python
906
+ {'job_id': '717ec0b5-85df-4174-80d6-bddf93cd8248', 'job_result': [{'url': 'http://127.0.0.1:8888/files/2023-12-29/f1eca704-718e-4781-9d5f-82d41aa799d7.png', 'seed': '3283449865282320931'}]}
907
+ ```
908
+
909
+ # public requests params
910
+
911
+ ## AdvanceParams
912
+
913
+ | Name | Type | Description |
914
+ |--------------------------------------|-------|----------------------------------------------------------------------------------|
915
+ | disable_preview | bool | disable preview, default to False |
916
+ | adm_scaler_positive | float | ADM Guidance Scaler, default to 1.5, range 0.1-3.0 |
917
+ | adm_scaler_negative | float | negative ADM Guidance Scaler, default to 0.8, range 0.1-3.0 |
918
+ | adm_scaler_end | float | ADM Guidance Scaler end value, default to 0.5, range 0.0-1.0 |
919
+ | refiner_swap_method | str | refiner model swap method, default to `joint` |
920
+ | adaptive_cfg | float | CFG Mimicking from TSNR, default to 7.0, range 1.0-30.0 |
921
+ | sampler_name | str | sampler, default to `default_sampler` |
922
+ | scheduler_name | str | scheduler, default to `default_scheduler` |
923
+ | overwrite_step | int | Forced Overwrite of Sampling Step, default to -1, range -1-200 |
924
+ | overwrite_switch | int | Forced Overwrite of Refiner Switch Step, default to -1, range -1-200 |
925
+ | overwrite_width | int | Forced Overwrite of Generating Width, default to -1, range -1-2048 |
926
+ | overwrite_height | int | Forced Overwrite of Generating Height, default to -1, range -1-2048 |
927
+ | overwrite_vary_strength | float | Forced Overwrite of Denoising Strength of "Vary", default to -1, range -1-1.0 |
928
+ | overwrite_upscale_strength | float | Forced Overwrite of Denoising Strength of "Upscale", default to -1, range -1-1.0 |
929
+ | mixing_image_prompt_and_vary_upscale | bool | Mixing Image Prompt and Vary/Upscale, default to False |
930
+ | mixing_image_prompt_and_inpaint | bool | Mixing Image Prompt and Inpaint, default to False |
931
+ | debugging_cn_preprocessor | bool | Debug Preprocessors, default to False |
932
+ | skipping_cn_preprocessor | bool | Skip Preprocessors, default to False |
933
+ | controlnet_softness | float | Softness of ControlNet, default to 0.25, range 0.0-1.0 |
934
+ | canny_low_threshold | int | Canny Low Threshold, default to 64, range 1-255 |
935
+ | canny_high_threshold | int | Canny High Threshold, default to 128, range 1-255 |
936
+ | freeu_enabled | bool | FreeU enabled, default to False |
937
+ | freeu_b1 | float | FreeU B1, default to 1.01 |
938
+ | freeu_b2 | float | FreeU B2, default to 1.02 |
939
+ | freeu_s1 | float | FreeU B3, default to 0.99 |
940
+ | freeu_s2 | float | FreeU B4, default to 0.95 |
941
+ | debugging_inpaint_preprocessor | bool | Debug Inpaint Preprocessing, default to False |
942
+ | inpaint_disable_initial_latent | bool | Disable initial latent in inpaint, default to False |
943
+ | inpaint_engine | str | Inpaint Engine, default to `v2.6` |
944
+ | inpaint_strength | float | Inpaint Denoising Strength, default to 1.0, range 0.0-1.0 |
945
+ | inpaint_respective_field | float | Inpaint Respective Field, default to 1.0, range 0.0-1.0 |
946
+ | inpaint_mask_upload_checkbox | bool | upload mask, default False |
947
+ | invert_mask_checkbox | bool | revert mask, default False |
948
+ | inpaint_erode_or_dilate | int | Mask Erode or Dilate, default 0, -64-64 |
949
+
950
+ ## lora
951
+
952
+ | Name | Type | Description |
953
+ |------------|-------|------------------------|
954
+ | enabled | bool | enable lora |
955
+ | model_name | str | model name |
956
+ | weight | float | weight, default to 0.5 |
957
+
958
+ ## response
959
+
960
+ success response:
961
+
962
+ **async_process: True**
963
+
964
+ | Name | Type | Description |
965
+ |------------------|-------|--------------|
966
+ | job_id | int | job ID |
967
+ | job_type | str | job type |
968
+ | job_stage | str | job stage |
969
+ | job_progress | float | job progress |
970
+ | job_status | str | job status |
971
+ | job_step_preview | str | job preview |
972
+ | job_result | str | job result |
973
+
974
+ **async_process: False**
975
+
976
+ | Name | Type | Description |
977
+ |---------------|------|----------------------------------------------------------------------------------|
978
+ | base64 | str | base64 image, according to `require_base64` params determines whether it is null |
979
+ | url | str | result image url |
980
+ | seed | int | image seed |
981
+ | finish_reason | str | finish reason |
982
+
983
+ fail response:
docs/api_doc_zh.md ADDED
@@ -0,0 +1,987 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - [简介](#简介)
2
+ - [Fooocus 能力相关接口](#fooocus-能力相关接口)
3
+ - [文生图 | text-to-image](#文生图--text-to-image)
4
+ - [图像放大 | image-upscale-vary](#图像放大--image-upscale-vary)
5
+ - [局部重绘 | image-inpaint-outpaint](#局部重绘--image-inpaint-outpaint)
6
+ - [图生图 | image-prompt](#图生图--image-prompt)
7
+ - [text-to-image-with-image prompt](#text-to-image-with-image-prompt)
8
+ - [图像反推 | describe](#图像反推--describe)
9
+ - [列出模型 | all-models](#列出模型--all-models)
10
+ - [刷新模型 | refresh-models](#刷新模型--refresh-models)
11
+ - [样式 | styles](#样式--styles)
12
+ - [Fooocus API 任务相关接口](#fooocus-api-任务相关接口)
13
+ - [任务队列 | job-queue](#任务队列--job-queue)
14
+ - [查询任务 | query-job](#查询任务--query-job)
15
+ - [查询任务历史 | job-history](#查询任务历史--job-history)
16
+ - [停止任务 | stop](#停止任务--stop)
17
+ - [ping](#ping)
18
+ - [webhook](#webhook)
19
+ - [公共请求体](#公共请求体)
20
+ - [高级参数 | AdvanceParams](#高级参数--advanceparams)
21
+ - [lora](#lora)
22
+ - [响应参数 | response](#响应参数--response)
23
+
24
+
25
+
26
+ # 简介
27
+
28
+ Fooocus API 目前提供了十多个 REST 接口, 我大致将其分为两类, 第一类用来调用 Fooocus 的能力, 比如生成图像、刷新模型之类的, 第二类为 Fooocus API 自身相关的, 主要是任务查询相关。我会在接下来的内容中尝试说明它们的作用以及用法并提供示例。
29
+
30
+ > 几乎所有的接口参数都有默认值,这意味着你只需要发送你感兴趣的参数即可。完整的参数以及默认值可以通过表格查看
31
+
32
+ # Fooocus 能力相关接口
33
+
34
+ ## 文生图 | text-to-image
35
+
36
+ 对应 Fooocus 中的文生图功能
37
+
38
+ **基础信息:**
39
+
40
+ ```yaml
41
+ EndPoint: /v1/generation/text-to-image
42
+ Method: Post
43
+ DataType: json
44
+ ```
45
+ **请求参数:**
46
+
47
+ | Name | Type | Description |
48
+ |-------------------------|----------------|-------------------------------------------------------------------------|
49
+ | prompt | string | 描述词, 默认为空字符串 |
50
+ | negative_prompt | string | 描述词, 反向描述词 |
51
+ | style_selections | List[str] | 风格列表, 需要是受支持的风格, 可以通过 [样式接口](#样式--styles) 获取所有支持的样式 |
52
+ | performance_selection | Enum | 性能选择, `Speed`, `Quality`, `Extreme Speed`, `Lightning` 中的一个, 默认 `Speed` |
53
+ | aspect_ratios_selection | str | 分辨率, 默认 '1152*896' |
54
+ | image_number | int | 生成图片数量, 默认 1 , 最大32, 注: 非并行接口 |
55
+ | image_seed | int | 图片种子, 默认 -1, 即随机生成 |
56
+ | sharpness | float | 锐度, 默认 2.0 , 0-30 |
57
+ | guidance_scale | float | 引导比例, 默认 4.0 , 1-30 |
58
+ | base_model_name | str | 基础模型, 默认 `juggernautXL_version6Rundiffusion.safetensors` |
59
+ | refiner_model_name | str | 优化模型, 默认 `None` |
60
+ | refiner_switch | float | 优化模型切换时机, 默认 0.5 |
61
+ | loras | List[Lora] | lora 模型列表, 包含配置, lora 结构: [Lora](#lora) |
62
+ | advanced_params | AdvancedParams | 高级参数, AdvancedParams 结构 [AdvancedParams](#高级参数--advanceparams) |
63
+ | save_meta | bool | 是否保存元数据, 默认 True |
64
+ | meta_scheme | str | 元数据方案, 默认 'fooocus', 目前只支持 'fooocus' |
65
+ | save_extension | str | 保存文件扩展名, 默认 'png' |
66
+ | save_name | str | 保存文件名, 默认 job_id + 序号 |
67
+ | read_wildcards_in_order | bool | 是否按照顺序读取通配符, 默认 False |
68
+ | require_base64 | bool | 是否返回base64编码, 默认 False |
69
+ | async_process | bool | 是否异步处理, 默认 False |
70
+ | webhook_url | str | 异步处理完成后, 触发的 webhook 地址, 参考[webhook](#webhook) |
71
+
72
+ **响应参数:**
73
+
74
+ 多数响应结构式相同的, 不同的部分会进行特别说明.
75
+
76
+ 该接口返回通用响应结构, 参考[响应参数](#响应参数--response)
77
+
78
+ **请求示例:**
79
+
80
+ ```python
81
+ host = "http://127.0.0.1:8888"
82
+
83
+ def text2img(params: dict) -> dict:
84
+ """
85
+ 文生图
86
+ """
87
+ result = requests.post(url=f"{host}/v1/generation/text-to-image",
88
+ data=json.dumps(params),
89
+ headers={"Content-Type": "application/json"})
90
+ return result.json()
91
+
92
+ result =text2img({
93
+ "prompt": "1girl sitting on the ground",
94
+ "async_process": True})
95
+ print(result)
96
+ ```
97
+
98
+ ## 图像放大 | image-upscale-vary
99
+
100
+ 该接口对应 Fooocus 中的 Upscale or Variation 功能
101
+
102
+ 该接口参数继承自[文生图](#文生图--text-to-image), 因此后面只会列出和[文生图](#文生图--text-to-image)请求参数差异部分
103
+
104
+ 此外, 该接口提供了两个版本, 两个版本并无功能上的差异, 主要是请求方式略有区别
105
+
106
+ **基础信息:**
107
+
108
+ ```yaml
109
+ EndPoint_V1: /v1/generation/image-upscale-vary
110
+ EndPoint_V2: /v2/generation/image-upscale-vary
111
+ Method: Post
112
+ DataType: form|json
113
+ ```
114
+
115
+ ### V1
116
+
117
+ **请求参数**
118
+
119
+ | Name | Type | Description |
120
+ |------------------|---------------------|---------------------------------------------------------------------------------------------------------------------------|
121
+ | input_image | string($binary) | 二进制 str 图像 |
122
+ | uov_method | Enum | 'Vary (Subtle)','Vary (Strong)','Upscale (1.5x)','Upscale (2x)','Upscale (Fast 2x)','Upscale (Custom)' |
123
+ | upscale_value | float | 默认为 None , 1.0-5.0, 放大倍数, 仅在 'Upscale (Custom)' 中有效 |
124
+ | style_selections | List[str] | 以逗号分割的 Fooocus 风格列表 |
125
+ | loras | str(List[Lora]) | lora 模型列表, 包含配置, lora 结构: [Lora](#lora), 比如: [{"model_name": "sd_xl_offset_example-lora_1.0.safetensors", "weight": 0.5}] |
126
+ | advanced_params | str(AdvancedParams) | 高级参数, AdvancedParams 结构 [AdvancedParams](#高级参数--advanceparams), 以字符串形式发送, 可以为空 |
127
+
128
+ **响应参数:**
129
+
130
+ 该接口返回通用响应结构, 参考[响应参数](#响应参数--response)
131
+
132
+ **请求示例:**
133
+
134
+ ```python
135
+ # 不要加 {"Content-Type": "application/json"} 这个 header
136
+
137
+ host = "http://127.0.0.1:8888"
138
+ image = open("./examples/imgs/bear.jpg", "rb").read()
139
+
140
+ def upscale_vary(image, params: dict) -> dict:
141
+ """
142
+ Upscale or Vary
143
+ """
144
+ response = requests.post(url=f"{host}/v1/generation/image-upscale-vary",
145
+ data=params,
146
+ files={"input_image": image})
147
+ return response.json()
148
+
149
+ result =upscale_vary(image=image,
150
+ params={
151
+ "uov_method": "Upscale (2x)",
152
+ "async_process": True
153
+ })
154
+ print(json.dumps(result, indent=4, ensure_ascii=False))
155
+ ```
156
+
157
+ ### V2
158
+
159
+ **请求参数**
160
+
161
+ | Name | Type | Description |
162
+ |---------------|---------------------|-------------------------------------------------------------------------------------------------------------------|
163
+ | uov_method | UpscaleOrVaryMethod | 是个枚举类型, 包括 'Vary (Subtle)','Vary (Strong)','Upscale (1.5x)','Upscale (2x)','Upscale (Fast 2x)','Upscale (Custom)' |
164
+ | upscale_value | float | 默认为 None , 1.0-5.0, 放大倍数, 仅在 'Upscale (Custom)' 中有效 |
165
+ | input_image | str | 输入图像, base64 格式, 或者一个URL |
166
+
167
+ **响应参数:**
168
+
169
+ 该接口返回通用响应结构, 参考[响应参数](#响应参数--response)
170
+
171
+ **请求示例:**
172
+
173
+ ```python
174
+ host = "http://127.0.0.1:8888"
175
+ image = open("./examples/imgs/bear.jpg", "rb").read()
176
+
177
+ def upscale_vary(image, params: dict) -> dict:
178
+ """
179
+ Upscale or Vary
180
+ """
181
+ params["input_image"] = base64.b64encode(image).decode('utf-8')
182
+ response = requests.post(url=f"{host}/v2/generation/image-upscale-vary",
183
+ data=json.dumps(params),
184
+ headers={"Content-Type": "application/json"},
185
+ timeout=300)
186
+ return response.json()
187
+
188
+ result =upscale_vary(image=image,
189
+ params={
190
+ "uov_method": "Upscale (2x)",
191
+ "async_process": True
192
+ })
193
+ print(json.dumps(result, indent=4, ensure_ascii=False))
194
+ ```
195
+
196
+ ## 局部重绘 | image-inpaint-outpaint
197
+
198
+ **基础信息:**
199
+
200
+ ```yaml
201
+ EndPoint_V1: /v1/generation/image-inpaint-outpaint
202
+ EndPoint_V2: /v2/generation/image-inpaint-outpaint
203
+ Method: Post
204
+ DataType: form|json
205
+ ```
206
+
207
+ ### V1
208
+
209
+ **请求参数**
210
+
211
+ | Name | Type | Description |
212
+ |---------------------------|---------------------|---------------------------------------------------------------------------------------------------------------------------|
213
+ | input_image | string($binary) | 二进制 str 图像 |
214
+ | input_mask | string($binary) | 二进制 str 图像 |
215
+ | inpaint_additional_prompt | string | 附加描述 |
216
+ | outpaint_selections | str | 图像扩展方向, 逗号分割的 'Left', 'Right', 'Top', 'Bottom' |
217
+ | outpaint_distance_left | int | 图像扩展距离, 默认 0 |
218
+ | outpaint_distance_right | int | 图像扩展距离, 默认 0 |
219
+ | outpaint_distance_top | int | 图像扩展距离, 默认 0 |
220
+ | outpaint_distance_bottom | int | 图像扩展距离, 默认 0 |
221
+ | style_selections | List[str] | 以逗号分割的 Fooocus 风格列表 |
222
+ | loras | str(List[Lora]) | lora 模型列表, 包含配置, lora 结构: [Lora](#lora), 比如: [{"model_name": "sd_xl_offset_example-lora_1.0.safetensors", "weight": 0.5}] |
223
+ | advanced_params | str(AdvancedParams) | 高级参数, AdvancedParams 结构 [AdvancedParams](#高级参数--advanceparams), 以字符串形式发送 |
224
+
225
+ **响应参数:**
226
+
227
+ 该接口返回通用响应结构, 参考[响应参数](#响应参数--response)
228
+
229
+ **请求示例:**
230
+
231
+ ```python
232
+ # 局部重绘 v1 接口示例
233
+ host = "http://127.0.0.1:8888"
234
+ image = open("./examples/imgs/bear.jpg", "rb").read()
235
+
236
+ def inpaint_outpaint(params: dict, input_image: bytes, input_mask: bytes = None) -> dict:
237
+ """
238
+ 局部重绘 v1 接口示例
239
+ """
240
+ response = requests.post(url=f"{host}/v1/generation/image-inpaint-outpaint",
241
+ data=params,
242
+ files={"input_image": input_image,
243
+ "input_mask": input_mask})
244
+ return response.json()
245
+
246
+ # 图片扩展示例
247
+ result = inpaint_outpaint(params={
248
+ "outpaint_selections": "Left,Right",
249
+ "async_process": True},
250
+ input_image=image,
251
+ input_mask=None)
252
+ print(json.dumps(result, indent=4, ensure_ascii=False))
253
+
254
+ # 局部重绘示例
255
+ source = open("./examples/imgs/s.jpg", "rb").read()
256
+ mask = open("./examples/imgs/m.png", "rb").read()
257
+ result = inpaint_outpaint(params={
258
+ "prompt": "a cat",
259
+ "async_process": True},
260
+ input_image=source,
261
+ input_mask=mask)
262
+ print(json.dumps(result, indent=4, ensure_ascii=False))
263
+ ```
264
+
265
+ ### V2
266
+
267
+ **请求参数**
268
+
269
+ | Name | Type | Description |
270
+ |---------------------------|-------------------------|-----------------------------------------------------------------|
271
+ | input_image | str | 输入图像, base64 格式, 或者一个URL |
272
+ | input_mask | str | 输入遮罩, base64 格式, 或者一个URL |
273
+ | inpaint_additional_prompt | str | 附加描述词 |
274
+ | outpaint_selections | List[OutpaintExpansion] | OutpaintExpansion 是一个枚举类型, 值包括 "Left", "Right", "Top", "Bottom" |
275
+ | outpaint_distance_left | int | 图像扩展距离, 默认 0 |
276
+ | outpaint_distance_right | int | 图像扩展距离, 默认 0 |
277
+ | outpaint_distance_top | int | 图像扩展距离, 默认 0 |
278
+ | outpaint_distance_bottom | int | 图像扩展距离, 默认 0 |
279
+
280
+ **响应参数:**
281
+
282
+ 该接口返回通用响应结构, 参考[响应参数](#响应参数--response)
283
+
284
+ **请求示例:**
285
+
286
+ ```python
287
+ # 局部重绘 v2 接口示例
288
+ host = "http://127.0.0.1:8888"
289
+ image = open("./examples/imgs/bear.jpg", "rb").read()
290
+
291
+ def inpaint_outpaint(params: dict) -> dict:
292
+ """
293
+ 局部重绘 v1 接口示例
294
+ """
295
+ response = requests.post(url=f"{host}/v2/generation/image-inpaint-outpaint",
296
+ data=json.dumps(params),
297
+ headers={"Content-Type": "application/json"})
298
+ return response.json()
299
+
300
+ # 图像扩展示例
301
+ result = inpaint_outpaint(params={
302
+ "input_image": base64.b64encode(image).decode('utf-8'),
303
+ "input_mask": None,
304
+ "outpaint_selections": ["Left", "Right"],
305
+ "async_process": True})
306
+ print(json.dumps(result, indent=4, ensure_ascii=False))
307
+
308
+ # 局部重绘示例
309
+ source = open("./examples/imgs/s.jpg", "rb").read()
310
+ mask = open("./examples/imgs/m.png", "rb").read()
311
+ result = inpaint_outpaint(params={
312
+ "prompt": "a cat",
313
+ "input_image": base64.b64encode(source).decode('utf-8'),
314
+ "input_mask": base64.b64encode(mask).decode('utf-8'),
315
+ "async_process": True})
316
+ print(json.dumps(result, indent=4, ensure_ascii=False))
317
+ ```
318
+
319
+ ## 图生图 | image-prompt
320
+
321
+ 该接口更新自 `v0.3.27` 后有重大更新。从继承自 [文生图](#文生图--text-to-image) 更改为继承自 [局部重绘](#局部重绘--image-inpaint-outpaint)
322
+
323
+ 该版本之后可以通过该接口实现 `inpaint_outpaint` 以及 `image-prompt` 接口的功能
324
+
325
+ > 多功能接口,并非可以同时实现 `inpaint_outpaint` 以及 `image-prompt` 接口的功能
326
+
327
+ **基础信息:**
328
+
329
+ ```yaml
330
+ EndPoint_V1: /v1/generation/image-prompt
331
+ EndPoint_V2: /v2/generation/image-prompt
332
+ Method: Post
333
+ DataType: form|json
334
+ ```
335
+
336
+ ### V1
337
+
338
+ **请求参数**
339
+
340
+ > 注意: 虽然接口更改为继承自[局部重绘](#局部重绘--image-inpaint-outpaint), 但下方表格展示的仍然继承自[文生图](#文生图--text-to-image), 但参数是完整的
341
+
342
+ | Name | Type | Description |
343
+ |---------------------------|---------------------|---------------------------------------------------------------------------------------------------------------------------|
344
+ | input_image | Bytes | 二进制图像, 用于局部重绘 |
345
+ | input_mask | Bytes | 二进制图像遮罩, 用于局部重绘 |
346
+ | inpaint_additional_prompt | str | inpaint 附加提示词 |
347
+ | outpaint_selections | str | 图像扩展选项, 逗号分割的 "Left", "Right", "Top", "Bottom" |
348
+ | outpaint_distance_left | int | 图像扩展距离, 默认 0 |
349
+ | outpaint_distance_right | int | 图像扩展距离, 默认 0 |
350
+ | outpaint_distance_top | int | 图像扩展距离, 默认 0 |
351
+ | outpaint_distance_bottom | int | 图像扩展距离, 默认 0 |
352
+ | cn_img1 | string($binary) | 二进制 str 图像 |
353
+ | cn_stop1 | float | 默认 0.6 |
354
+ | cn_weight1 | float | 默认 0.6 |
355
+ | cn_type1 | Enum | "ImagePrompt", "FaceSwap", "PyraCanny", "CPDS" 中的一个 |
356
+ | cn_img2 | string($binary) | 二进制 str 图像 |
357
+ | cn_stop2 | float | 默认 0.6 |
358
+ | cn_weight2 | float | 默认 0.6 |
359
+ | cn_type2 | Enum | "ImagePrompt", "FaceSwap", "PyraCanny", "CPDS" 中的一个 |
360
+ | cn_img3 | string($binary) | 二进制 str 图像 |
361
+ | cn_stop3 | float | 默认 0.6 |
362
+ | cn_weight3 | float | 默认 0.6 |
363
+ | cn_type3 | Enum | "ImagePrompt", "FaceSwap", "PyraCanny", "CPDS" 中的一个 |
364
+ | cn_img4 | string($binary) | 二进制 str 图像 |
365
+ | cn_stop4 | float | 默认 0.6 |
366
+ | cn_weight4 | float | 默认 0.6 |
367
+ | cn_type4 | Enum | "ImagePrompt", "FaceSwap", "PyraCanny", "CPDS" 中的一个 |
368
+ | style_selections | List[str] | 以逗号分割的 Fooocus 风格列表 |
369
+ | loras | str(List[Lora]) | lora 模型列表, 包含配置, lora 结构: [Lora](#lora), 比如: [{"model_name": "sd_xl_offset_example-lora_1.0.safetensors", "weight": 0.5}] |
370
+ | advanced_params | str(AdvancedParams) | 高级参数, AdvancedParams 结构 [AdvancedParams](#高级参数--advanceparams), 以字符串形式发送 |
371
+
372
+ **响应参数:**
373
+
374
+ 该接口返回通用响应结构, 参考[响应参数](#响应参数--response)
375
+
376
+ **请求示例:**
377
+
378
+ ```python
379
+ # image_prompt v1 接口示例
380
+ host = "http://127.0.0.1:8888"
381
+ image = open("./examples/imgs/bear.jpg", "rb").read()
382
+ source = open("./examples/imgs/s.jpg", "rb").read()
383
+ mask = open("./examples/imgs/m.png", "rb").read()
384
+
385
+ def image_prompt(params: dict,
386
+ input_image: bytes=None,
387
+ input_mask: bytes=None,
388
+ cn_img1: bytes=None,
389
+ cn_img2: bytes=None,
390
+ cn_img3: bytes=None,
391
+ cn_img4: bytes=None,) -> dict:
392
+ """
393
+ image prompt
394
+ """
395
+ response = requests.post(url=f"{host}/v1/generation/image-prompt",
396
+ data=params,
397
+ files={
398
+ "input_image": input_image,
399
+ "input_mask": input_mask,
400
+ "cn_img1": cn_img1,
401
+ "cn_img2": cn_img2,
402
+ "cn_img3": cn_img3,
403
+ "cn_img4": cn_img4,
404
+ })
405
+ return response.json()
406
+
407
+ # 图像扩展
408
+ params = {
409
+ "outpaint_selections": ["Left", "Right"],
410
+ "image_prompts": [] # 必传参数,可以为空列表
411
+ }
412
+ result = image_prompt(params=params, input_iamge=image)
413
+ print(json.dumps(result, indent=4, ensure_ascii=False))
414
+
415
+ # 局部重绘
416
+
417
+ params = {
418
+ "prompt": "1girl sitting on the chair",
419
+ "image_prompts": [], # 必传参数,可以为空列表
420
+ "async_process": True
421
+ }
422
+ result = image_prompt(params=params, input_iamge=source, input_mask=mask)
423
+ print(json.dumps(result, indent=4, ensure_ascii=False))
424
+
425
+ # image prompt
426
+
427
+ params = {
428
+ "prompt": "1girl sitting on the chair",
429
+ "image_prompts": [
430
+ {
431
+ "cn_stop": 0.6,
432
+ "cn_weight": 0.6,
433
+ "cn_type": "ImagePrompt"
434
+ },{
435
+ "cn_stop": 0.6,
436
+ "cn_weight": 0.6,
437
+ "cn_type": "ImagePrompt"
438
+ }]
439
+ }
440
+ result = image_prompt(params=params, cn_img1=image, cn_img2=source)
441
+ print(json.dumps(result, indent=4, ensure_ascii=False))
442
+ ```
443
+
444
+ ### V2
445
+
446
+ **请求参数**
447
+
448
+ | Name | Type | Description |
449
+ |---------------------------|-------------------------|------------------------------------------------|
450
+ | input_image | str | base64 图像, 或者一个URL, 用于局部重绘 |
451
+ | input_mask | str | base64 图像遮罩, 或者一个URL, 用于局部重绘 |
452
+ | inpaint_additional_prompt | str | inpaint 附加提示词 |
453
+ | outpaint_selections | List[OutpaintExpansion] | 图像扩展选项, 逗号分割的 "Left", "Right", "Top", "Bottom" |
454
+ | outpaint_distance_left | int | 图像扩展距离, 默认 0 |
455
+ | outpaint_distance_right | int | 图像扩展距离, 默认 0 |
456
+ | outpaint_distance_top | int | 图像扩展距离, 默认 0 |
457
+ | outpaint_distance_bottom | int | 图像扩展距离, 默认 0 |
458
+ | image_prompts | List[ImagePrompt] | 图像列表, 包含配置, ImagePrompt 结构如下: |
459
+
460
+ **ImagePrompt**
461
+
462
+ | Name | Type | Description |
463
+ |-----------|----------------|---------------------------------------------------------------------|
464
+ | cn_img | str | 输入图像, base64 编码, 或者一个URL |
465
+ | cn_stop | float | 停止位置, 范围 0-1, 默认 0.5 |
466
+ | cn_weight | float | 权重, 范围 0-2, 默认 1.0 |
467
+ | cn_type | ControlNetType | 控制网络类型, 是一个枚举类型, 包括: "ImagePrompt", "FaceSwap", "PyraCanny", "CPDS" |
468
+
469
+ **响应参数:**
470
+
471
+ 该接口返回通用响应结构, 参考[响应参数](#响应参数--response)
472
+
473
+ **请求示例:**
474
+
475
+ ```python
476
+ # image_prompt v2 接口示例
477
+ host = "http://127.0.0.1:8888"
478
+ image = open("./examples/imgs/bear.jpg", "rb").read()
479
+ source = open("./examples/imgs/s.jpg", "rb").read()
480
+ mask = open("./examples/imgs/m.png", "rb").read()
481
+
482
+ def image_prompt(params: dict) -> dict:
483
+ """
484
+ image prompt
485
+ """
486
+ response = requests.post(url=f"{host}/v2/generation/image-prompt",
487
+ data=json.dumps(params),
488
+ headers={"Content-Type": "application/json"})
489
+ return response.json()
490
+
491
+ # 图像扩展
492
+ params = {
493
+ "input_image": base64.b64encode(image).decode('utf-8'),
494
+ "outpaint_selections": ["Left", "Right"],
495
+ "image_prompts": [] # 必传参数,可以为空列表
496
+ }
497
+ result = image_prompt(params)
498
+ print(json.dumps(result, indent=4, ensure_ascii=False))
499
+
500
+ # 局部重绘
501
+
502
+ params = {
503
+ "prompt": "1girl sitting on the chair",
504
+ "input_image": base64.b64encode(source).decode('utf-8'),
505
+ "input_mask": base64.b64encode(mask).decode('utf-8'),
506
+ "image_prompts": [], # 必传参数,可以为空列表
507
+ "async_process": True
508
+ }
509
+ result = image_prompt(params)
510
+ print(json.dumps(result, indent=4, ensure_ascii=False))
511
+
512
+ # image prompt
513
+
514
+ params = {
515
+ "prompt": "1girl sitting on the chair",
516
+ "image_prompts": [
517
+ {
518
+ "cn_img": base64.b64encode(source).decode('utf-8'),
519
+ "cn_stop": 0.6,
520
+ "cn_weight": 0.6,
521
+ "cn_type": "ImagePrompt"
522
+ },{
523
+ "cn_img": base64.b64encode(image).decode('utf-8'),
524
+ "cn_stop": 0.6,
525
+ "cn_weight": 0.6,
526
+ "cn_type": "ImagePrompt"
527
+ }]
528
+ }
529
+ result = image_prompt(params)
530
+ print(json.dumps(result, indent=4, ensure_ascii=False))
531
+ ```
532
+
533
+ ## text to image with image prompt
534
+
535
+ 该接口暂无 v1 版本
536
+
537
+ **基础信息:**
538
+
539
+ ```yaml
540
+ EndPoint: /v2/generation/text-to-image-with-ip
541
+ Method: Post
542
+ DataType: json
543
+ ```
544
+
545
+ **请求参数**
546
+
547
+ | Name | Type | Description |
548
+ |---------------|-------------------|-------------|
549
+ | image_prompts | List[ImagePrompt] | 图像列表 |
550
+
551
+ **请求示例**:
552
+
553
+ ```python
554
+ # text to image with image prompt 示例
555
+ host = "http://127.0.0.1:8888"
556
+ image = open("./examples/imgs/bear.jpg", "rb").read()
557
+ source = open("./examples/imgs/s.jpg", "rb").read()
558
+ def image_prompt(params: dict) -> dict:
559
+ """
560
+ image prompt
561
+ """
562
+ response = requests.post(url=f"{host}/v2/generation/text-to-image-with-ip",
563
+ data=json.dumps(params),
564
+ headers={"Content-Type": "application/json"})
565
+ return response.json()
566
+
567
+ params = {
568
+ "prompt": "A bear",
569
+ "image_prompts": [
570
+ {
571
+ "cn_img": base64.b64encode(source).decode('utf-8'),
572
+ "cn_stop": 0.6,
573
+ "cn_weight": 0.6,
574
+ "cn_type": "ImagePrompt"
575
+ },{
576
+ "cn_img": base64.b64encode(image).decode('utf-8'),
577
+ "cn_stop": 0.6,
578
+ "cn_weight": 0.6,
579
+ "cn_type": "ImagePrompt"
580
+ }
581
+ ]
582
+ }
583
+ result = image_prompt(params)
584
+ print(json.dumps(result, indent=4, ensure_ascii=False))
585
+ ```
586
+
587
+ ## 图像反推 | describe
588
+
589
+ **基础信息:**
590
+
591
+ ```yaml
592
+ EndPoint: /v1/tools/describe-image
593
+ Method: Post
594
+ DataType: form
595
+ ```
596
+
597
+ **请求参数**
598
+
599
+ | Name | Type | Description |
600
+ |------|------|-----------------------------|
601
+ | type | Enum | 反推类型, "Photo", "Anime" 中的一个 |
602
+
603
+ **请求示例**:
604
+
605
+ ```python
606
+ def describe_image(image: bytes,
607
+ params: dict = {"type": "Photo"}) -> dict:
608
+ """
609
+ describe-image
610
+ """
611
+ response = requests.post(url="http://127.0.0.1:8888/v1/tools/describe-image",
612
+ params=params,
613
+ files={
614
+ "image": image
615
+ },
616
+ timeout=30)
617
+ return response.json()
618
+ ```
619
+
620
+ **响应示例**:
621
+
622
+ ```python
623
+ {
624
+ "describe": "a young woman posing with her hands behind her head"
625
+ }
626
+ ```
627
+
628
+ --------------------------------------------
629
+
630
+ ## 列出模型 | all-models
631
+
632
+ **基础信息:**
633
+
634
+ ```yaml
635
+ EndPoint: /v1/engines/all-models
636
+ Method: Get
637
+ ```
638
+
639
+ **请求示例**:
640
+
641
+ ```python
642
+ def all_models() -> dict:
643
+ """
644
+ all-models
645
+ """
646
+ response = requests.get(url="http://127.0.0.1:8888/v1/engines/all-models",
647
+ timeout=30)
648
+ return response.json()
649
+ ```
650
+
651
+ **响应示例**:
652
+
653
+ ```python
654
+ {
655
+ "model_filenames": [
656
+ "juggernautXL_version6Rundiffusion.safetensors",
657
+ "sd_xl_base_1.0_0.9vae.safetensors",
658
+ "sd_xl_refiner_1.0_0.9vae.safetensors"
659
+ ],
660
+ "lora_filenames": [
661
+ "sd_xl_offset_example-lora_1.0.safetensors"
662
+ ]
663
+ }
664
+ ```
665
+
666
+ ## 刷新模型 | refresh-models
667
+
668
+ **基础信息:**
669
+
670
+ > 该接口已移除,功能合并到 [列出模型](#列出模型--all-models)
671
+
672
+ ```yaml
673
+ EndPoint: /v1/engines/refresh-models
674
+ Method: Post
675
+ ```
676
+
677
+ **请求示例**
678
+ ```python
679
+ def refresh() -> dict:
680
+ """
681
+ refresh-models
682
+ """
683
+ response = requests.post(url="http://127.0.0.1:8888/v1/engines/refresh-models",
684
+ timeout=30)
685
+ return response.json()
686
+ ```
687
+
688
+ **响应示例**
689
+ ```python
690
+ {
691
+ "model_filenames": [
692
+ "juggernautXL_version6Rundiffusion.safetensors",
693
+ "sd_xl_base_1.0_0.9vae.safetensors",
694
+ "sd_xl_refiner_1.0_0.9vae.safetensors"
695
+ ],
696
+ "lora_filenames": [
697
+ "sd_xl_offset_example-lora_1.0.safetensors"
698
+ ]
699
+ }
700
+ ```
701
+
702
+ ## 样式 | styles
703
+
704
+ **基础信息:**
705
+
706
+ ```yaml
707
+ EndPoint: /v1/engines/styles
708
+ Method: Get
709
+ ```
710
+
711
+ **请求示例**:
712
+
713
+ ```python
714
+ def styles() -> dict:
715
+ """
716
+ styles
717
+ """
718
+ response = requests.get(url="http://127.0.0.1:8888/v1/engines/styles",
719
+ timeout=30)
720
+ return response.json()
721
+ ```
722
+
723
+ **响应示例**:
724
+
725
+ ```python
726
+ [
727
+ "Fooocus V2",
728
+ "Fooocus Enhance",
729
+ ...
730
+ "Watercolor 2",
731
+ "Whimsical And Playful"
732
+ ]
733
+ ```
734
+
735
+ # Fooocus API 任务相关接口
736
+
737
+ ## 任务队列 | job-queue
738
+
739
+ **基础信息:**
740
+
741
+ ```yaml
742
+ EndPoint: /v1/engines/job-queue
743
+ Method: Get
744
+ ```
745
+
746
+ **请求示例**:
747
+
748
+ ```python
749
+ def job_queue() -> dict:
750
+ """
751
+ job-queue
752
+ """
753
+ response = requests.get(url="http://127.0.0.1:8888/v1/generation/job-queue",
754
+ timeout=30)
755
+ return response.json()
756
+ ```
757
+
758
+ **响应示例**:
759
+
760
+ ```python
761
+ {
762
+ "running_size": 0,
763
+ "finished_size": 1,
764
+ "last_job_id": "cac3914a-926d-4b6f-a46a-83794a0ce1d4"
765
+ }
766
+ ```
767
+
768
+ ## 查询任务 | query-job
769
+
770
+ **基础信息:**
771
+
772
+ ```yaml
773
+ EndPoint: /v1/generation/query-job
774
+ Method: Get
775
+ ```
776
+
777
+ **请求示例**:
778
+ ```python
779
+ def taskResult(task_id: str) -> dict:
780
+ # 获取任务状态
781
+ task_status = requests.get(url="http://127.0.0.1:8888/v1/generation/query-job",
782
+ params={"job_id": task_id,
783
+ "require_step_preview": False},
784
+ timeout=30)
785
+
786
+ return task_status.json()
787
+ ```
788
+
789
+ **响应示例**:
790
+ ```python
791
+ {
792
+ "job_id": "cac3914a-926d-4b6f-a46a-83794a0ce1d4",
793
+ "job_type": "Text to Image",
794
+ "job_stage": "SUCCESS",
795
+ "job_progress": 100,
796
+ "job_status": "Finished",
797
+ "job_step_preview": null,
798
+ "job_result": [
799
+ {
800
+ "base64": null,
801
+ "url": "http://127.0.0.1:8888/files/2023-11-27/b928e50e-3c09-4187-a3f9-1c12280bfd95.png",
802
+ "seed": 8228839561385006000,
803
+ "finish_reason": "SUCCESS"
804
+ }
805
+ ]
806
+ }
807
+ ```
808
+
809
+ ## 查询任务历史 | job-history
810
+
811
+ **基础信息:**
812
+
813
+ ```yaml
814
+ EndPoint: /v1/generation/job-history
815
+ Method: get
816
+ ```
817
+
818
+ **请求示例**:
819
+
820
+ ```python
821
+ def job-history() -> dict:
822
+ """
823
+ job-history
824
+ """
825
+ response = requests.get(url="http://127.0.0.1:8888/v1/generation/job-history",
826
+ timeout=30)
827
+ return response.json()
828
+ ```
829
+
830
+ **响应示例**:
831
+
832
+ ```python
833
+ {
834
+ "queue": [],
835
+ "history": [
836
+ "job_id": "cac3914a-926d-4b6f-a46a-83794a0ce1d4",
837
+ "is_finished": True
838
+ ]
839
+ }
840
+ ```
841
+
842
+ ## 停止任务 | stop
843
+
844
+ **基础信息:**
845
+
846
+ ```yaml
847
+ EndPoint: /v1/generation/stop
848
+ Method: post
849
+ ```
850
+
851
+ **请求示例**:
852
+
853
+ ```python
854
+ def stop() -> dict:
855
+ """
856
+ stop
857
+ """
858
+ response = requests.post(url="http://127.0.0.1:8888/v1/generation/stop",
859
+ timeout=30)
860
+ return response.json()
861
+ ```
862
+
863
+ **响应示例**:
864
+
865
+ ```python
866
+ {
867
+ "msg": "success"
868
+ }
869
+ ```
870
+
871
+ ## ping
872
+
873
+ **基础信息:**
874
+
875
+ ```yaml
876
+ EndPoint: /ping
877
+ Method: get
878
+ ```
879
+
880
+ pong
881
+
882
+ # webhook
883
+
884
+ 你可以在命令行通过 `--webhook-url` 指定一个地址,以便异步任务完成之后可以收到通知
885
+
886
+ 下面是一个简单的示例来展示 `webhook` 是如何工作的
887
+
888
+ 首先,使用下面的代码启动一个简易服务器:
889
+
890
+ ```python
891
+ from fastapi import FastAPI
892
+ import uvicorn
893
+
894
+ app = FastAPI()
895
+
896
+ @app.post("/status")
897
+ async def status(requests: dict):
898
+ print(requests)
899
+
900
+ uvicorn.run(app, host="0.0.0.0", port=8000)
901
+ ```
902
+
903
+ 然后, 在启动 Fooocus API 时添加 `--webhook-url http://host:8000/status`
904
+
905
+ 通过任意方式提交一个任务, 等完成后你会在这个简易服务器的后台看到任务结束信息:
906
+
907
+ ```python
908
+ {'job_id': '717ec0b5-85df-4174-80d6-bddf93cd8248', 'job_result': [{'url': 'http://127.0.0.1:8888/files/2023-12-29/f1eca704-718e-4781-9d5f-82d41aa799d7.png', 'seed': '3283449865282320931'}]}
909
+ ```
910
+
911
+ # 公共请求体
912
+
913
+ ## 高级参数 | AdvanceParams
914
+
915
+ | Name | Type | Description |
916
+ |--------------------------------------|-------|-----------------------------------------------------------------------|
917
+ | disable_preview | bool | 是否禁用预览, 默认 False |
918
+ | disable_intermediate_results | bool | 是否禁用中间结果, 默认 False |
919
+ | disable_seed_increment | bool | 是否禁用种子递增, 默认 False |
920
+ | adm_scaler_positive | float | 正 ADM Guidance Scaler, 默认 1.5, 范围 0.1-3.0 |
921
+ | adm_scaler_negative | float | 负 ADM Guidance Scaler, 默认 0.8, 范围 0.1-3.0 |
922
+ | adm_scaler_end | float | ADM Guidance Scaler 结束值, 默认 0.5, 范围 0.0-1.0 |
923
+ | refiner_swap_method | str | 优化模型交换方法, 默认 `joint` |
924
+ | adaptive_cfg | float | CFG Mimicking from TSNR, 默认 7.0, 范围 1.0-30.0 |
925
+ | sampler_name | str | 采样器, 默认 `default_sampler` |
926
+ | scheduler_name | str | 调度器, 默认 `default_scheduler` |
927
+ | overwrite_step | int | Forced Overwrite of Sampling Step, 默认 -1, 范围 -1-200 |
928
+ | overwrite_switch | int | Forced Overwrite of Refiner Switch Step, 默认 -1, 范围 -1-200 |
929
+ | overwrite_width | int | Forced Overwrite of Generating Width, 默认 -1, 范围 -1-2048 |
930
+ | overwrite_height | int | Forced Overwrite of Generating Height, 默认 -1, 范围 -1-2048 |
931
+ | overwrite_vary_strength | float | Forced Overwrite of Denoising Strength of "Vary", 默认 -1, 范围 -1-1.0 |
932
+ | overwrite_upscale_strength | float | Forced Overwrite of Denoising Strength of "Upscale", 默认 -1, 范围 -1-1.0 |
933
+ | mixing_image_prompt_and_vary_upscale | bool | Mixing Image Prompt and Vary/Upscale, 默认 False |
934
+ | mixing_image_prompt_and_inpaint | bool | Mixing Image Prompt and Inpaint, 默认 False |
935
+ | debugging_cn_preprocessor | bool | Debug Preprocessors, 默认 False |
936
+ | skipping_cn_preprocessor | bool | Skip Preprocessors, 默认 False |
937
+ | controlnet_softness | float | Softness of ControlNet, 默认 0.25, 范围 0.0-1.0 |
938
+ | canny_low_threshold | int | Canny Low Threshold, 默认 64, 范围 1-255 |
939
+ | canny_high_threshold | int | Canny High Threshold, 默认 128, 范围 1-255 |
940
+ | freeu_enabled | bool | FreeU enabled, 默认 False |
941
+ | freeu_b1 | float | FreeU B1, 默认 1.01 |
942
+ | freeu_b2 | float | FreeU B2, 默认 1.02 |
943
+ | freeu_s1 | float | FreeU B3, 默认 0.99 |
944
+ | freeu_s2 | float | FreeU B4, 默认 0.95 |
945
+ | debugging_inpaint_preprocessor | bool | Debug Inpaint Preprocessing, 默认 False |
946
+ | inpaint_disable_initial_latent | bool | Disable initial latent in inpaint, 默认 False |
947
+ | inpaint_engine | str | Inpaint Engine, 默认 `v2.6` |
948
+ | inpaint_strength | float | Inpaint Denoising Strength, 默认 1.0, 范围 0.0-1.0 |
949
+ | inpaint_respective_field | float | Inpaint Respective Field, 默认 1.0, 范围 0.0-1.0 |
950
+ | inpaint_mask_upload_checkbox | bool | 是否上传掩码图片, 默认 False |
951
+ | invert_mask_checkbox | bool | 是否反转掩码, 默认 False |
952
+ | inpaint_erode_or_dilate | int | Mask Erode or Dilate, 默认 0, 范围 -64-64 |
953
+
954
+ ## lora
955
+
956
+ | Name | Type | Description |
957
+ |------------|-------|-------------|
958
+ | enabled | bool | 是否启用lora |
959
+ | model_name | str | 模型名称 |
960
+ | weight | float | 权重, 默认 0.5 |
961
+
962
+ ## 响应参数 | response
963
+
964
+ 成功响应:
965
+
966
+ **async_process: True**
967
+
968
+ | Name | Type | Description |
969
+ |------------------|-------|-------------|
970
+ | job_id | int | 任务ID |
971
+ | job_type | str | 任务类型 |
972
+ | job_stage | str | 任务阶段 |
973
+ | job_progress | float | 任务进度 |
974
+ | job_status | str | 任务状态 |
975
+ | job_step_preview | str | 任务预览 |
976
+ | job_result | str | 任务结果 |
977
+
978
+ **async_process: False**
979
+
980
+ | Name | Type | Description |
981
+ |---------------|------|----------------------------------------------|
982
+ | base64 | str | 图片base64编码, 根据 `require_base64` 参数决定是否为 null |
983
+ | url | str | 图片url |
984
+ | seed | int | 图片种子 |
985
+ | finish_reason | str | 任务结束原因 |
986
+
987
+ 失败响应:
docs/assets/tasks.png ADDED
docs/change_logs.md ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ChangeLog for Fooocus-API
2
+
3
+ ## [v0.5.0.1]
4
+ ### Changed
5
+ - Fooocus to v2.5.3
6
+ - Add enhance image endpoint
7
+ - Add generate mask endpoint
8
+ - Influenced by Fooocus, the worker.py was reconstructed
9
+ - Update docs
10
+ - Returned base64 str now include identifier like this `data:image/jpeg;base64,`
11
+
12
+ ### Fixed
13
+ - Issue #375
14
+ - Issue #378
15
+ - Save extension params now also takes effect for base64 str in the returned data
16
+
17
+ ## [v0.4.1.1] - 2024-05-2
18
+ ### Added
19
+ - LoraManager support tar file
20
+
21
+ ### Changed
22
+ - Update Fooocus to v2.4.3
23
+
24
+ ### Fixed
25
+ - Issue #363
26
+
27
+ ## [v0.4.1.0] - 2024-05-28
28
+ ### Added
29
+ - Add nsfw checker
30
+
31
+ ### Changed
32
+ - Fooocus to v2.4.1
33
+ - Increase support for config.txt
34
+
35
+ ### Fixed
36
+ - Issue #319
37
+ - Issue #327
38
+ - Issue #332
39
+ - Fix JPEG support
40
+
41
+ ## [v0.4.0.6] - 2024-04-24
42
+ ### Added
43
+ - UA in image request
44
+
45
+ ### Changed
46
+ - Fooocus to v2.3.1
47
+ - Code formatting.
48
+
49
+ ### Fixed
50
+ - Issue #302
51
+ - Issue #294
52
+
53
+ ## [v0.4.0.5] - 2024-04-16
54
+ ### Changed
55
+ - Sync v1 endpoints.
56
+
57
+ ### Fixed
58
+ - meta_scheme error
59
+
60
+ ## [v0.4.0.4] - 2024-04-15
61
+ ### Added
62
+ - Image meta save to image
63
+
64
+ ### Changed
65
+ - Code formatting.
66
+
67
+ ## [v0.4.0.3] - 2024-04-12
68
+ ### Fixed
69
+ - Fix opencv-python-headless failed in Docker
70
+ - Issue #270
71
+
72
+ ## [v0.4.0.2] - 2024-04-09
73
+ ### Fixed
74
+ - Issue #280
75
+ - Issue #222
76
+
77
+ ## [v0.4.0.1] - 2024-04-08
78
+ ### Added
79
+ - Url support for lora in replicate
80
+
81
+ ## [v0.4.0.0] - 2024-04-08
82
+ ### Changed
83
+ - Update docs
84
+ - Rewrite Dockerfile
85
+ - Rewirte examples
86
+ - Full code of Fooocus include
87
+ - Remove related code
88
+ - Optimize project structure.
89
+
90
+ ## [v0.3.33] - 2024-04-07
91
+ ### Added
92
+ - Support for Lightning model.
93
+ - Update default checkpoint for Replicate.
94
+
95
+ ### Fixed
96
+ - Issue #244
97
+ - Issue #259
98
+ - Issue #232
99
+
100
+ ## [v0.3.32] - 2024-03-21
101
+ ### Added
102
+ - Support for Fooocus 2.3.0.
103
+
104
+ ### Changed
105
+ - Project structure optimization.
106
+
107
+ ### Fixed
108
+ - Removed unnecessary dependencies and optimized code.
109
+
110
+ ## [v0.3.31] - 2024-03-20
111
+ ### Added
112
+ - Save extension
113
+ - Secure API future with the use of API keys.
114
+ - Add seeds for predict output
115
+
116
+ ### Changed
117
+ - Update Docs
118
+
119
+ ### Fixed
120
+ - OOM when running a long time
121
+ - Some spell error
122
+ - Issue with the Fooocus-API version in startup output.
123
+
124
+ ## [v0.3.30] - 2024-01-26
125
+ ### Added
126
+ - Support url for input_image in v2 API.
127
+ - Image Prompt Mixing requirements implemented
128
+ - Add SQLite database support for history.
129
+
130
+ ### Changed
131
+ - Update Docs
132
+ - Large queue size support
133
+ - Optimized async task response when the queue is full
134
+ - Update cog branch
135
+ - Optimized cli flages parser.
136
+ - Optimized some code formatting.
137
+ - Optimized the underlying logic of task execution.
138
+ - Default queue history size to 0 for no limit.
139
+
140
+ ### Fixed
141
+ - Fix condition. default params broke here and this fixes auto mixing feature.
142
+ - Fix error when use `Extreme Speed' with cog.
143
+ - Fix typo of 'presistent'
144
+ - Image Prompt Mixing requirements implemented
145
+ - Some spell error, some translations.
146
+ - Fix image prompt must require 'input_image'.
147
+ - Implemented support for storing history to the database.
148
+
149
+ ## [v0.3.29] - 2024-01-04
150
+ ### Added
151
+ - Add example using ipynb
152
+ - Add error logging
153
+ - Add check for aspect_ratios_selection
154
+ - Image Prompt Mixing requirements implemented.
155
+
156
+ ### Changed
157
+ - Update Docs
158
+ - Merge Fooocus to v2.1.860
159
+
160
+ ### Fixed
161
+ - Various bugs and issues reported by the community.
162
+
163
+ ## [v0.3.28] - 2024-01-03
164
+ ### Added
165
+ - Add ping endpoint
166
+ - Describe interface to get prompts from images.
167
+ - Add image_prompt to text2img endpoint
168
+ - Add mirror for fooocus
169
+
170
+ ### Changed
171
+ - Update Docs
172
+ - Added query job history API and webhook_url support for each generation request.
173
+ - Change to exit when Fooocus check failed
174
+
175
+ ### Fixed
176
+ - Fix #122 query job not found error.
177
+
178
+ Please note that this ChangeLog is a summary and may not include all changes. For a complete list of changes, please refer to the commit history on the [Fooocus-API GitHub repository](https://github.com/mrhan1993/Fooocus-API).
docs/change_logs_zh.md ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ChangeLog for Fooocus-API
2
+
3
+ ## [v0.5.0.1]
4
+ ### Changed
5
+ - 合并到 Fooocus 2.5.3
6
+ - 增加图像增强接口
7
+ - 增加遮罩生成接口
8
+ - 受 Fooocus 影响,重构了 worker.py
9
+ - 更新文档
10
+ - 返回数据中的 base64 字符串现在包含图像标识符,比如 `data:image/jpeg;base64,`
11
+
12
+ ### Fixed
13
+ - Issue #375
14
+ - Issue #378
15
+ - 保存扩展名参数现在可以对返回的 base64 生效了
16
+
17
+ ## [v0.4.1.1] - 2024-05-2
18
+ ### Added
19
+ - LoraManager 支持 tar 格式压缩文件
20
+
21
+ ### Changed
22
+ - Update Fooocus to v2.4.3
23
+
24
+ ### Fixed
25
+ - Issue #363
26
+
27
+ ## [v0.4.1.0] - 2024-05-28
28
+ ### Added
29
+ - 黄图检测
30
+
31
+ ### Changed
32
+ - Fooocus to v2.4.1
33
+ - 增强对 config.txt 文件的支持
34
+
35
+ ### Fixed
36
+ - Issue #319
37
+ - Issue #327
38
+ - Issue #332
39
+ - Fix JPEG support
40
+
41
+ ## [v0.4.0.6] - 2024-04-24
42
+ ### Added
43
+ - UA in image request
44
+
45
+ ### Changed
46
+ - Fooocus to v2.3.1
47
+ - Code formatting.
48
+
49
+ ### Fixed
50
+ - Issue #302
51
+ - Issue #294
52
+
53
+ ## [v0.4.0.5] - 2024-04-16
54
+ ### Changed
55
+ - Sync v1 endpoints.
56
+
57
+ ### Fixed
58
+ - meta_scheme error
59
+
60
+ ## [v0.4.0.4] - 2024-04-15
61
+ ### Added
62
+ - Image meta save to image
63
+
64
+ ### Changed
65
+ - Code formatting.
66
+
67
+ ## [v0.4.0.3] - 2024-04-12
68
+ ### Fixed
69
+ - Fix opencv-python-headless failed in Docker
70
+ - Issue #270
71
+
72
+ ## [v0.4.0.2] - 2024-04-09
73
+ ### Fixed
74
+ - Issue #280
75
+ - Issue #222
76
+
77
+ ## [v0.4.0.1] - 2024-04-08
78
+ ### Added
79
+ - Url support for lora in replicate
80
+
81
+ ## [v0.4.0.0] - 2024-04-08
82
+ ### Changed
83
+ - Update docs
84
+ - Rewrite Dockerfile
85
+ - Rewirte examples
86
+ - Full code of Fooocus include
87
+ - Remove related code
88
+ - Optimize project structure.
89
+
90
+ ## [v0.3.33] - 2024-04-07
91
+ ### Added
92
+ - Support for Lightning model.
93
+ - Update default checkpoint for Replicate.
94
+
95
+ ### Fixed
96
+ - Issue #244
97
+ - Issue #259
98
+ - Issue #232
99
+
100
+ ## [v0.3.32] - 2024-03-21
101
+ ### Added
102
+ - Support for Fooocus 2.3.0.
103
+
104
+ ### Changed
105
+ - Project structure optimization.
106
+
107
+ ### Fixed
108
+ - Removed unnecessary dependencies and optimized code.
109
+
110
+ ## [v0.3.31] - 2024-03-20
111
+ ### Added
112
+ - Save extension
113
+ - Secure API future with the use of API keys.
114
+ - Add seeds for predict output
115
+
116
+ ### Changed
117
+ - Update Docs
118
+
119
+ ### Fixed
120
+ - OOM when running a long time
121
+ - Some spell error
122
+ - Issue with the Fooocus-API version in startup output.
123
+
124
+ ## [v0.3.30] - 2024-01-26
125
+ ### Added
126
+ - Support url for input_image in v2 API.
127
+ - Image Prompt Mixing requirements implemented
128
+ - Add SQLite database support for history.
129
+
130
+ ### Changed
131
+ - Update Docs
132
+ - Large queue size support
133
+ - Optimized async task response when the queue is full
134
+ - Update cog branch
135
+ - Optimized cli flages parser.
136
+ - Optimized some code formatting.
137
+ - Optimized the underlying logic of task execution.
138
+ - Default queue history size to 0 for no limit.
139
+
140
+ ### Fixed
141
+ - Fix condition. default params broke here and this fixes auto mixing feature.
142
+ - Fix error when use `Extreme Speed' with cog.
143
+ - Fix typo of 'presistent'
144
+ - Image Prompt Mixing requirements implemented
145
+ - Some spell error, some translations.
146
+ - Fix image prompt must require 'input_image'.
147
+ - Implemented support for storing history to the database.
148
+
149
+ ## [v0.3.29] - 2024-01-04
150
+ ### Added
151
+ - Add example using ipynb
152
+ - Add error logging
153
+ - Add check for aspect_ratios_selection
154
+ - Image Prompt Mixing requirements implemented.
155
+
156
+ ### Changed
157
+ - Update Docs
158
+ - Merge Fooocus to v2.1.860
159
+
160
+ ### Fixed
161
+ - Various bugs and issues reported by the community.
162
+
163
+ ## [v0.3.28] - 2024-01-03
164
+ ### Added
165
+ - Add ping endpoint
166
+ - Describe interface to get prompts from images.
167
+ - Add image_prompt to text2img endpoint
168
+ - Add mirror for fooocus
169
+
170
+ ### Changed
171
+ - Update Docs
172
+ - Added query job history API and webhook_url support for each generation request.
173
+ - Change to exit when Fooocus check failed
174
+
175
+ ### Fixed
176
+ - Fix #122 query job not found error.
177
+
178
+ Please note that this ChangeLog is a summary and may not include all changes. For a complete list of changes, please refer to the commit history on the [Fooocus-API GitHub repository](https://github.com/mrhan1993/Fooocus-API).
docs/migrate.md ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 参数对照表
2
+
3
+ In next table, `AdvancedParams` is replaced with `adp`, and the rule of name change is to unify with Fooocus.
4
+
5
+ | Fooocus-API | FooocusAPI | 备注 |
6
+ |------------------------------------------|--------------------------------------|---------------------|
7
+ | prompt | prompt | |
8
+ | negative_prompt | negative_prompt | |
9
+ | style_selections | style_selections | |
10
+ | performance_selection | performance_selection | |
11
+ | aspect_ratios_selection | aspect_ratios_selection | |
12
+ | image_number | image_number | |
13
+ | image_seed | image_seed | |
14
+ | sharpness | sharpness | |
15
+ | guidance_scale | guidance_scale | |
16
+ | base_model_name | base_model_name | |
17
+ | refiner_model_name | refiner_model_name | |
18
+ | refiner_switch | refiner_switch | |
19
+ | loras | loras | same, a list of lora obj |
20
+ | | input_image_checkbox | this is always true |
21
+ | | current_tab | need not care this |
22
+ | uov_method | uov_method | |
23
+ | **input_image** | **uov_input_image** | use variable name in Fooocus |
24
+ | outpaint_selections | outpaint_selections | |
25
+ | **input_image** | **inpaint_input_image** | use variable name in Fooocus |
26
+ | inpaint_additional_prompt | inpaint_additional_prompt | |
27
+ | **input_mask** | **inpaint_mask_image_upload** | use variable name in Fooocus |
28
+ | adp.disable_preview | disable_preview | |
29
+ | adp.disable_intermediate_results | disable_intermediate_results | |
30
+ | adp.disable_seed_increment | disable_seed_increment | |
31
+ | adp.black_out_nsfw | black_out_nsfw | |
32
+ | adp.adm_scaler_positive | adm_scaler_positive | |
33
+ | adp.adm_scaler_negative | adm_scaler_negative | |
34
+ | adp.adm_scaler_end | adm_scaler_end | |
35
+ | adp.adaptive_cfg | adaptive_cfg | |
36
+ | adp.clip_skip | clip_skip | |
37
+ | adp.sampler_name | sampler_name | |
38
+ | adp.scheduler_name | scheduler_name | |
39
+ | adp.vae_name | vae_name | |
40
+ | adp.overwrite_step | overwrite_step | |
41
+ | adp.overwrite_switch | overwrite_switch | |
42
+ | adp.overwrite_width | overwrite_width | |
43
+ | adp.overwrite_height | overwrite_height | |
44
+ | adp.overwrite_vary_strength | overwrite_vary_strength | |
45
+ | adp.overwrite_upscale_strength | overwrite_upscale_strength | |
46
+ | adp.mixing_image_prompt_and_vary_upscale | mixing_image_prompt_and_vary_upscale | |
47
+ | adp.mixing_image_prompt_and_inpaint | mixing_image_prompt_and_inpaint | |
48
+ | adp.debugging_cn_preprocessor | debugging_cn_preprocessor | |
49
+ | adp.skipping_cn_preprocessor | skipping_cn_preprocessor | |
50
+ | adp.canny_low_threshold | canny_low_threshold | |
51
+ | adp.canny_high_threshold | canny_high_threshold | |
52
+ | adp.refiner_swap_method | refiner_swap_method | |
53
+ | adp.controlnet_softness | controlnet_softness | |
54
+ | adp.freeu_enabled | freeu_enabled | |
55
+ | adp.freeu_b1 | freeu_b1 | |
56
+ | adp.freeu_b2 | freeu_b2 | |
57
+ | adp.freeu_s1 | freeu_s1 | |
58
+ | adp.freeu_s2 | freeu_s2 | |
59
+ | adp.debugging_inpaint_preprocessor | debugging_inpaint_preprocessor | |
60
+ | adp.inpaint_disable_initial_latent | inpaint_disable_initial_latent | |
61
+ | adp.inpaint_engine | inpaint_engine | |
62
+ | adp.inpaint_strength | inpaint_strength | |
63
+ | adp.inpaint_respective_field | inpaint_respective_field | |
64
+ | adp.inpaint_mask_upload_checkbox | inpaint_mask_upload_checkbox | |
65
+ | adp.invert_mask_checkbox | invert_mask_checkbox | |
66
+ | adp.inpaint_erode_or_dilate | inpaint_erode_or_dilate | |
67
+ | **image_prompts** | **controlnet_image** | just change name |
68
+ | | generate_image_grid | new, default is better |
69
+ | outpaint_distance_left | outpaint_distance | merge these to one |
70
+ | outpaint_distance_right | | use a list to pass these four |
71
+ | outpaint_distance_top | | exp: [100, 50, 0, 0] |
72
+ | outpaint_distance_bottom | | Directions are: left, up, right, down |
73
+ | **upscale_value** | **upscale_multiple** | name change only |
74
+ | | preset | new, use this this specified preset |
75
+ | | stream_output | new, similar to LLM streaming output |
76
+ | **save_meta** | **save_metadata_to_images** | name change only |
77
+ | **meta_scheme** | **metadata_scheme** | name change only |
78
+ | **save_extension** | **output_format** | name change only |
79
+ | save_name | | remove |
80
+ | read_wildcards_in_order | read_wildcards_in_order | |
81
+ | require_base64 | require_base64 | will be remove |
82
+ | async_process | async_process | |
83
+ | webhook_url | webhook_url | |
84
+
85
+ simple is:
86
+
87
+ - All `AdvancedParams` move to upper level
88
+ - Modify some params name
89
+ - `input_image` -> `inpaint_input_image`
90
+ - `inpaint_mask` -> `inpaint_mask_image_upload`
91
+ - `input_image` -> `uov_input_image`
92
+ - `image_prompts` -> `controlnet_image`
93
+ - `upscale_value` -> `upscale_value`
94
+ - `save_meta` -> `upscale_multiple`
95
+ - `meta_scheme` -> `save_metadata_to_images`
96
+ - `save_extension` -> `output_format`
97
+ - Remove some params
98
+ - `save_name`
99
+ - Add some params
100
+ - `input_image_checkbox`
101
+ - `current_tab`
102
+ - `generate_image_grid`
103
+ - `preset`
104
+ - `stream_output`
105
+ - Merge some params
106
+ - `outpaint_distance_left,right,top,bottom` 四个参数合并为 `outpaint_distance`
107
+
108
+ ## Example for three types of return
109
+
110
+ ### async task
111
+
112
+ specify `async_process` as `True`
113
+
114
+ ```python
115
+ import requests
116
+ import json
117
+
118
+ endpoint = "http://127.0.0.1:7866/v1/engine/generate/"
119
+
120
+ params = {
121
+ "prompt": "",
122
+ "negative_prompt": "",
123
+ "performance_selection": "Lightning",
124
+ "async_process": True,
125
+ "webhook_url": ""
126
+ }
127
+
128
+ res = requests.post(
129
+ url=endpoint,
130
+ data=json.dumps(params),
131
+ timeout=60
132
+ )
133
+
134
+ print(res.json())
135
+ ```
136
+
137
+ output will be like this:
138
+
139
+ ```python
140
+ {'id': -1, 'task_id': '85c10c81e9e2482d90a64c3704137d3a', 'req_params': {}, 'in_queue_mills': -1, 'start_mills': -1, 'finish_mills': -1, 'task_status': 'pending', 'progress': -1, 'preview': '', 'webhook_url': '', 'result': []}
141
+ ```
142
+
143
+ use `task_id` request `http://127.0.0.1:7866/tasks/{task_id}` to get task info, if this task is currently running, return should be include `preview`
144
+
145
+ example for return
146
+
147
+ ```python
148
+ # pending
149
+ {
150
+ "id": -1,
151
+ "in_queue_mills": 1720085748199,
152
+ "finish_mills": null,
153
+ "progress": null,
154
+ "result": null,
155
+ "req_params": {
156
+ # full request params
157
+ ...
158
+ },
159
+ "task_id": "85c10c81e9e2482d90a64c3704137d3a",
160
+ "start_mills": null,
161
+ "task_status": null,
162
+ "webhook_url": ""
163
+ }
164
+
165
+ # running
166
+ {
167
+ "id": -1,
168
+ "task_id": "85c10c81e9e2482d90a64c3704137d3a",
169
+ "req_params": {
170
+ ...
171
+ },
172
+ "in_queue_mills": 1720086131653,
173
+ "start_mills": 1720086131865,
174
+ "finish_mills": -1,
175
+ "task_status": "running",
176
+ "progress": 18,
177
+ "preview": "a long text",
178
+ "webhook_url": "",
179
+ "result": []
180
+ }
181
+
182
+ # finished
183
+ {
184
+ "id": 71,
185
+ "in_queue_mills": 1720085748199,
186
+ "finish_mills": 1720085770046,
187
+ "progress": 100,
188
+ "result": [
189
+ "http://127.0.0.1:7866/outputs/2024-07-04/2024-07-04_17-36-09_5201.png"
190
+ ],
191
+ "req_params": {
192
+ ...
193
+ },
194
+ "task_id": "85c10c81e9e2482d90a64c3704137d3a",
195
+ "start_mills": 1720085748425,
196
+ "task_status": "finished",
197
+ "webhook_url": ""
198
+ }
199
+ ```
200
+
201
+ ### streaming output
202
+
203
+ this is like LLM streaming output, you will recieve from server until finish, refer to the above example:
204
+
205
+ ```python
206
+ import requests
207
+ import json
208
+
209
+ endpoint = "http://127.0.0.1:7866/v1/engine/generate/"
210
+
211
+ params = {
212
+ "prompt": "",
213
+ "negative_prompt": "",
214
+ "performance_selection": "Lightning",
215
+ "stream_output": True,
216
+ "webhook_url": ""
217
+ }
218
+
219
+ res = requests.post(
220
+ url=endpoint,
221
+ data=json.dumps(params),
222
+ stream=True,
223
+ timeout=60
224
+ )
225
+
226
+ for line in res.iter_lines():
227
+ if line:
228
+ print(line.decode('utf-8'))
229
+ ```
230
+
231
+ you will get response like this:
232
+
233
+ ```python
234
+ data: {"progress": 2, "preview": null, "message": "Loading models ...", "images": []}
235
+ data:
236
+ data: {"progress": 13, "preview": null, "message": "Preparing task 1/1 ...", "images": []}
237
+ data:
238
+ data: {"progress": 13, "preview": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASAAAA...", 'message': 'Sampling step 1/4, image 1/1 ...', 'images': []}
239
+ data:
240
+ data: {"progress": 34, "preview": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASAAAA...", 'message': 'Sampling step 2/4, image 1/1 ...', 'images': []}
241
+ data:
242
+ data: {"progress": 56, "preview": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASAAAA...", 'message': 'Sampling step 3/4, image 1/1 ...', 'images': []}
243
+ data:
244
+ data: {"progress": 78, "preview": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASAAAA...", 'message': 'Sampling step 4/4, image 1/1 ...', 'images': []}
245
+ data:
246
+ data: {"progress": 100, "preview": null, "message": "Saving image 1/1 to system ...", "images": []}
247
+ data:
248
+ data: {"progress": 100, "preview": null, "message": "Finished", "images": ["http://10.0.0.245:7866/outputs/2024-07-05/2024-07-05_09-31-10_1752.png"]}
249
+ data:
250
+ ```
251
+
252
+ just modify our code:
253
+
254
+ ```python
255
+ import requests
256
+ import json
257
+
258
+ endpoint = "http://127.0.0.1:7866/v1/engine/generate/"
259
+
260
+ params = {
261
+ "prompt": "",
262
+ "negative_prompt": "",
263
+ "performance_selection": "Lightning",
264
+ "stream_output": True,
265
+ "webhook_url": ""
266
+ }
267
+
268
+ res = requests.post(
269
+ url=endpoint,
270
+ data=json.dumps(params),
271
+ stream=True,
272
+ timeout=60
273
+ )
274
+
275
+ for line in res.iter_lines(chunk_size=8192):
276
+ line = line.decode('utf-8').split('\n')[0]
277
+
278
+ try:
279
+ json_data = json.loads(line[6:])
280
+ if json_data["preview"] is not None:
281
+ json_data["preview"] = "data:image/png;base64,iVBORw0KGgoAAAANSU..."
282
+ except json.decoder.JSONDecodeError:
283
+ continue
284
+ print(json_data)
285
+ ```
286
+
287
+ you will get this:
288
+
289
+ ```python
290
+ {'progress': 13, 'preview': None, 'message': 'Preparing task 1/1 ...', 'images': []}
291
+ {'progress': 13, 'preview': 'data:image/png;base64,iVBORw0KGgoAAAANSU...', 'message': 'Sampling step 1/4, image 1/1 ...', 'images': []}
292
+ {'progress': 34, 'preview': 'data:image/png;base64,iVBORw0KGgoAAAANSU...', 'message': 'Sampling step 2/4, image 1/1 ...', 'images': []}
293
+ {'progress': 56, 'preview': 'data:image/png;base64,iVBORw0KGgoAAAANSU...', 'message': 'Sampling step 3/4, image 1/1 ...', 'images': []}
294
+ {'progress': 78, 'preview': 'data:image/png;base64,iVBORw0KGgoAAAANSU...', 'message': 'Sampling step 4/4, image 1/1 ...', 'images': []}
295
+ {'progress': 100, 'preview': None, 'message': 'Saving image 1/1 to system ...', 'images': []}
296
+ {'progress': 100, 'preview': None, 'message': 'Finished', 'images': ['http://10.0.0.245:7866/outputs/2024-07-05/2024-07-05_10-02-22_2536.png']}
297
+ ```
298
+
299
+ it is better for frontend i think (but i am not good at this). with AI, i generate a [example.html](./docs/example.html), click `Generate` button, you will get a page with preview and progress.
300
+
301
+ ### binary output
302
+
303
+ this is simple, return is a image, pass `async_process` and `stream_output` both `false`, at this time, `image_number` force to `1`
304
+
305
+ ```python
306
+ import requests
307
+ import json
308
+ from PIL import Image
309
+ from io import BytesIO
310
+ import matplotlib.pyplot as plt
311
+
312
+ endpoint = "http://127.0.0.1:7866/v1/engine/generate/"
313
+
314
+ params = {
315
+ "prompt": "",
316
+ "negative_prompt": "",
317
+ "performance_selection": "Lightning",
318
+ "async_process": False,
319
+ "stream_output": False,
320
+ "webhook_url": ""
321
+ }
322
+
323
+ res = requests.post(
324
+ url=endpoint,
325
+ data=json.dumps(params),
326
+ timeout=60
327
+ )
328
+
329
+ image_stream = BytesIO(res.content)
330
+ image = Image.open(image_stream)
331
+
332
+ plt.imshow(image)
333
+ plt.show()
334
+ ```
335
+
336
+ # task query
337
+
338
+ Unlike [Fooocus-API](https://github.com/mrhan1993/Fooocus-API), the history saving will be automatic without a retention switch. The database is used with SQLite3 and stored in `outputs/db.sqlite3`. Taking lessons from the previous version, the table structure has been greatly simplified, and request parameters are stored as JSON in the `req_params` field. To reduce read and write operations, database operations are only performed when tasks enter and complete the queue. It is only used for generating records, and task status tracking is completed in memory.
339
+
340
+ In addition, this version will retain input images, uploaded images will calculate hash values and be saved in the `inputs` directory, and the image parameters in the database's `req_params` will be replaced with `url` information for saving, which means more complete historical record preservation, whether it is text-to-image or image-to-image or other types of images.
341
+
342
+ ## /tasks
343
+
344
+ This is a compound interface, but its return format is fixed. The interface will always return JSON data in the following format, regardless of how the parameters are specified.
345
+
346
+ ```python
347
+ {
348
+ "history": [],
349
+ "current": [], # Although it is a list, there will be no more than one element in it.
350
+ "pending": []
351
+ }
352
+ ```
353
+
354
+ All elements have a format that matches the scheme in the database, except for current which has an additional preview, as shown in the following figure:
355
+
356
+ ![](./assets/tasks.png)
357
+
358
+ more usage, see below:
359
+
360
+ > The return format of this interface is always fixed, regardless of how the parameters are adjusted.
361
+
362
+ ```shell
363
+ curl http://localhost:7866/tasks?query=current
364
+ # only return current task, other value for query include 'all', 'pending', 'history'
365
+
366
+ curl http://localhost:7866/tasks?query=history&page=3&page_size=5
367
+ # history and pending supports pagination and page size.
368
+
369
+ curl http://localhost:7866/tasks?query=history&start_at=2024-07-03T12:22:30
370
+ # You can specify a time range for the query, which will return all records within that time period. The time format is ISO8601, and if you do not specify end_at, it will be set to the current time.
371
+
372
+ curl http://localhost:7866/tasks?query=history&start_at=2024-07-03T12:22:30&action=delete
373
+ # Delete tasks within a specified time range, including database records and generated files. This is the only supported deletion method at present (input files will not be deleted).
374
+
375
+ curl http://localhost:7866/tasks/38ba92b188a64233a7336218cd902865
376
+ # This will return the information of the task, but it is just a dictionary. It is equivalent to taking the task with the specified task_id from the list above. If it happens to be the current task, it will also include preview. (Although it may look similar, this is actually another interface.)
377
+ ```
docs/migrate_zh.md ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 参数对照表
2
+
3
+ `AdvancedParams` 用 `adp` 代替,名称变动的原则是和 Fooocus 进行统一:
4
+
5
+ | Fooocus-API | FooocusAPI | 备注 |
6
+ |------------------------------------------|--------------------------------------|---------------------|
7
+ | prompt | prompt | |
8
+ | negative_prompt | negative_prompt | |
9
+ | style_selections | style_selections | |
10
+ | performance_selection | performance_selection | |
11
+ | aspect_ratios_selection | aspect_ratios_selection | |
12
+ | image_number | image_number | |
13
+ | image_seed | image_seed | |
14
+ | sharpness | sharpness | |
15
+ | guidance_scale | guidance_scale | |
16
+ | base_model_name | base_model_name | |
17
+ | refiner_model_name | refiner_model_name | |
18
+ | refiner_switch | refiner_switch | |
19
+ | loras | loras | 传入格式相同,都是 Lora 对象列表 |
20
+ | | input_image_checkbox | 可以忽略,它总是为 True |
21
+ | | current_tab | 可以忽略,根据参数会自动判断 |
22
+ | uov_method | uov_method | |
23
+ | **input_image** | **uov_input_image** | 使用 Fooocus 的变量名称 |
24
+ | outpaint_selections | outpaint_selections | |
25
+ | **input_image** | **inpaint_input_image** | 使用 Fooocus 的变量名称 |
26
+ | inpaint_additional_prompt | inpaint_additional_prompt | |
27
+ | **input_mask** | **inpaint_mask_image_upload** | 使用 Fooocus 的变量名称 |
28
+ | adp.disable_preview | disable_preview | |
29
+ | adp.disable_intermediate_results | disable_intermediate_results | |
30
+ | adp.disable_seed_increment | disable_seed_increment | |
31
+ | adp.black_out_nsfw | black_out_nsfw | |
32
+ | adp.adm_scaler_positive | adm_scaler_positive | |
33
+ | adp.adm_scaler_negative | adm_scaler_negative | |
34
+ | adp.adm_scaler_end | adm_scaler_end | |
35
+ | adp.adaptive_cfg | adaptive_cfg | |
36
+ | adp.clip_skip | clip_skip | |
37
+ | adp.sampler_name | sampler_name | |
38
+ | adp.scheduler_name | scheduler_name | |
39
+ | adp.vae_name | vae_name | |
40
+ | adp.overwrite_step | overwrite_step | |
41
+ | adp.overwrite_switch | overwrite_switch | |
42
+ | adp.overwrite_width | overwrite_width | |
43
+ | adp.overwrite_height | overwrite_height | |
44
+ | adp.overwrite_vary_strength | overwrite_vary_strength | |
45
+ | adp.overwrite_upscale_strength | overwrite_upscale_strength | |
46
+ | adp.mixing_image_prompt_and_vary_upscale | mixing_image_prompt_and_vary_upscale | |
47
+ | adp.mixing_image_prompt_and_inpaint | mixing_image_prompt_and_inpaint | |
48
+ | adp.debugging_cn_preprocessor | debugging_cn_preprocessor | |
49
+ | adp.skipping_cn_preprocessor | skipping_cn_preprocessor | |
50
+ | adp.canny_low_threshold | canny_low_threshold | |
51
+ | adp.canny_high_threshold | canny_high_threshold | |
52
+ | adp.refiner_swap_method | refiner_swap_method | |
53
+ | adp.controlnet_softness | controlnet_softness | |
54
+ | adp.freeu_enabled | freeu_enabled | |
55
+ | adp.freeu_b1 | freeu_b1 | |
56
+ | adp.freeu_b2 | freeu_b2 | |
57
+ | adp.freeu_s1 | freeu_s1 | |
58
+ | adp.freeu_s2 | freeu_s2 | |
59
+ | adp.debugging_inpaint_preprocessor | debugging_inpaint_preprocessor | |
60
+ | adp.inpaint_disable_initial_latent | inpaint_disable_initial_latent | |
61
+ | adp.inpaint_engine | inpaint_engine | |
62
+ | adp.inpaint_strength | inpaint_strength | |
63
+ | adp.inpaint_respective_field | inpaint_respective_field | |
64
+ | adp.inpaint_mask_upload_checkbox | inpaint_mask_upload_checkbox | |
65
+ | adp.invert_mask_checkbox | invert_mask_checkbox | |
66
+ | adp.inpaint_erode_or_dilate | inpaint_erode_or_dilate | |
67
+ | **image_prompts** | **controlnet_image** | 只是属性名称变更 |
68
+ | | generate_image_grid | 新增,这是个测试选项,建议默认 |
69
+ | outpaint_distance_left | outpaint_distance | 这四个属性合并为了一个属性 |
70
+ | outpaint_distance_right | | 可以通过一个列表传递这四个值 |
71
+ | outpaint_distance_top | | 例如:[100, 50, 0, 0] |
72
+ | outpaint_distance_bottom | | 方向是:左, 上, 右, 下 |
73
+ | **upscale_value** | **upscale_multiple** | 属性名变更 |
74
+ | | preset | 新增,可以通过该属性指定使用的预设 |
75
+ | | stream_output | 新增流式输出,类似 LLM 的流式输出 |
76
+ | **save_meta** | **save_metadata_to_images** | |
77
+ | **meta_scheme** | **metadata_scheme** | |
78
+ | **save_extension** | **output_format** | |
79
+ | save_name | | 移除,不支持自定义文件名 |
80
+ | read_wildcards_in_order | read_wildcards_in_order | |
81
+ | require_base64 | require_base64 | 该参数后续可能会被移除 |
82
+ | async_process | async_process | |
83
+ | webhook_url | webhook_url | |
84
+
85
+ 简单说来就是
86
+
87
+ - 将所有 `AdvancedParams` 平移到上一级
88
+ - 修改部分参数名
89
+ - `input_image` -> `inpaint_input_image`
90
+ - `inpaint_mask` -> `inpaint_mask_image_upload`
91
+ - `input_image` -> `uov_input_image`
92
+ - `image_prompts` -> `controlnet_image`
93
+ - `upscale_value` -> `upscale_value`
94
+ - `save_meta` -> `upscale_multiple`
95
+ - `meta_scheme` -> `save_metadata_to_images`
96
+ - `save_extension` -> `output_format`
97
+ - 移除部分参数名
98
+ - `save_name`
99
+ - 增加部分参数
100
+ - `input_image_checkbox`
101
+ - `current_tab`
102
+ - `generate_image_grid`
103
+ - `preset`
104
+ - `stream_output`
105
+ - 合并部分参数
106
+ - `outpaint_distance_left,right,top,bottom` 四个参数合并为 `outpaint_distance`
107
+
108
+ ## 三种返回示例
109
+
110
+ ### 异步任务
111
+
112
+ 在参数中指定 `async_process` 为 `True`
113
+
114
+ ```python
115
+ import requests
116
+ import json
117
+
118
+ endpoint = "http://127.0.0.1:7866/v1/engine/generate/"
119
+
120
+ params = {
121
+ "prompt": "",
122
+ "negative_prompt": "",
123
+ "performance_selection": "Lightning",
124
+ "async_process": True,
125
+ "webhook_url": ""
126
+ }
127
+
128
+ res = requests.post(
129
+ url=endpoint,
130
+ data=json.dumps(params),
131
+ timeout=60
132
+ )
133
+
134
+ print(res.json())
135
+ ```
136
+
137
+ 输出如下:
138
+
139
+ ```python
140
+ {'id': -1, 'task_id': '85c10c81e9e2482d90a64c3704137d3a', 'req_params': {}, 'in_queue_mills': -1, 'start_mills': -1, 'finish_mills': -1, 'task_status': 'pending', 'progress': -1, 'preview': '', 'webhook_url': '', 'result': []}
141
+ ```
142
+
143
+ 你可以通过 `task_id` 访问 `http://127.0.0.1:7866/tasks/{task_id}` 获取任务信息,如果该任务正在执行,返回信息中会包含 `preview`
144
+
145
+ 返回数据示例:
146
+
147
+ ```python
148
+ # 未开始
149
+ {
150
+ "id": -1,
151
+ "in_queue_mills": 1720085748199,
152
+ "finish_mills": null,
153
+ "progress": null,
154
+ "result": null,
155
+ "req_params": {
156
+ # 完整的请求参数
157
+ ...
158
+ },
159
+ "task_id": "85c10c81e9e2482d90a64c3704137d3a",
160
+ "start_mills": null,
161
+ "task_status": null,
162
+ "webhook_url": ""
163
+ }
164
+
165
+ # 执行中
166
+ {
167
+ "id": -1,
168
+ "task_id": "85c10c81e9e2482d90a64c3704137d3a",
169
+ "req_params": {
170
+ ...
171
+ },
172
+ "in_queue_mills": 1720086131653,
173
+ "start_mills": 1720086131865,
174
+ "finish_mills": -1,
175
+ "task_status": "running",
176
+ "progress": 18,
177
+ "preview": "a long text",
178
+ "webhook_url": "",
179
+ "result": []
180
+ }
181
+
182
+ # 已完成
183
+ {
184
+ "id": 71,
185
+ "in_queue_mills": 1720085748199,
186
+ "finish_mills": 1720085770046,
187
+ "progress": 100,
188
+ "result": [
189
+ "http://127.0.0.1:7866/outputs/2024-07-04/2024-07-04_17-36-09_5201.png"
190
+ ],
191
+ "req_params": {
192
+ ...
193
+ },
194
+ "task_id": "85c10c81e9e2482d90a64c3704137d3a",
195
+ "start_mills": 1720085748425,
196
+ "task_status": "finished",
197
+ "webhook_url": ""
198
+ }
199
+ ```
200
+
201
+ ### 流式输出
202
+
203
+ 这是一个类似 LLM 流式输出的方式,你会持续收到来自服务器的信息,直到结束,参照上面的示例:
204
+
205
+ ```python
206
+ import requests
207
+ import json
208
+
209
+ endpoint = "http://127.0.0.1:7866/v1/engine/generate/"
210
+
211
+ params = {
212
+ "prompt": "",
213
+ "negative_prompt": "",
214
+ "performance_selection": "Lightning",
215
+ "stream_output": True,
216
+ "webhook_url": ""
217
+ }
218
+
219
+ res = requests.post(
220
+ url=endpoint,
221
+ data=json.dumps(params),
222
+ stream=True,
223
+ timeout=60
224
+ )
225
+
226
+ for line in res.iter_lines():
227
+ if line:
228
+ print(line.decode('utf-8'))
229
+ ```
230
+
231
+ 你会获得类似下面的输出:
232
+
233
+ ```python
234
+ data: {"progress": 2, "preview": null, "message": "Loading models ...", "images": []}
235
+ data:
236
+ data: {"progress": 13, "preview": null, "message": "Preparing task 1/1 ...", "images": []}
237
+ data:
238
+ data: {"progress": 13, "preview": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASAAAA...", 'message': 'Sampling step 1/4, image 1/1 ...', 'images': []}
239
+ data:
240
+ data: {"progress": 34, "preview": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASAAAA...", 'message': 'Sampling step 2/4, image 1/1 ...', 'images': []}
241
+ data:
242
+ data: {"progress": 56, "preview": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASAAAA...", 'message': 'Sampling step 3/4, image 1/1 ...', 'images': []}
243
+ data:
244
+ data: {"progress": 78, "preview": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASAAAA...", 'message': 'Sampling step 4/4, image 1/1 ...', 'images': []}
245
+ data:
246
+ data: {"progress": 100, "preview": null, "message": "Saving image 1/1 to system ...", "images": []}
247
+ data:
248
+ data: {"progress": 100, "preview": null, "message": "Finished", "images": ["http://10.0.0.245:7866/outputs/2024-07-05/2024-07-05_09-31-10_1752.png"]}
249
+ data:
250
+ ```
251
+
252
+ 我们在稍微修改下:
253
+
254
+ ```python
255
+ import requests
256
+ import json
257
+
258
+ endpoint = "http://127.0.0.1:7866/v1/engine/generate/"
259
+
260
+ params = {
261
+ "prompt": "",
262
+ "negative_prompt": "",
263
+ "performance_selection": "Lightning",
264
+ "stream_output": True,
265
+ "webhook_url": ""
266
+ }
267
+
268
+ res = requests.post(
269
+ url=endpoint,
270
+ data=json.dumps(params),
271
+ stream=True,
272
+ timeout=60
273
+ )
274
+
275
+ for line in res.iter_lines(chunk_size=8192):
276
+ line = line.decode('utf-8').split('\n')[0]
277
+
278
+ try:
279
+ json_data = json.loads(line[6:])
280
+ if json_data["preview"] is not None:
281
+ json_data["preview"] = "data:image/png;base64,iVBORw0KGgoAAAANSU..."
282
+ except json.decoder.JSONDecodeError:
283
+ continue
284
+ print(json_data)
285
+ ```
286
+
287
+ 然后你就得到了一系列类似这样的输出:
288
+
289
+ ```python
290
+ {'progress': 13, 'preview': None, 'message': 'Preparing task 1/1 ...', 'images': []}
291
+ {'progress': 13, 'preview': 'data:image/png;base64,iVBORw0KGgoAAAANSU...', 'message': 'Sampling step 1/4, image 1/1 ...', 'images': []}
292
+ {'progress': 34, 'preview': 'data:image/png;base64,iVBORw0KGgoAAAANSU...', 'message': 'Sampling step 2/4, image 1/1 ...', 'images': []}
293
+ {'progress': 56, 'preview': 'data:image/png;base64,iVBORw0KGgoAAAANSU...', 'message': 'Sampling step 3/4, image 1/1 ...', 'images': []}
294
+ {'progress': 78, 'preview': 'data:image/png;base64,iVBORw0KGgoAAAANSU...', 'message': 'Sampling step 4/4, image 1/1 ...', 'images': []}
295
+ {'progress': 100, 'preview': None, 'message': 'Saving image 1/1 to system ...', 'images': []}
296
+ {'progress': 100, 'preview': None, 'message': 'Finished', 'images': ['http://10.0.0.245:7866/outputs/2024-07-05/2024-07-05_10-02-22_2536.png']}
297
+ ```
298
+
299
+ 这还挺适合前端套壳用的(可惜我完全搞不懂前端,要不高低套一个),比如��用 AI 生成了一个 [example.html](./docs/example.html) ,服务启动后点击 `Generate` 按钮,你就会得到一个有预览、有进度的生成过程。
300
+
301
+ ### 二进制输出
302
+
303
+ 这个就简单了,它就是返回一张图片,不过需要在请求时将 `async_process` 和 `stream_output` 同时指定为 `false`,此时 `image_number` 强制为 `1`
304
+
305
+ ```python
306
+ import requests
307
+ import json
308
+ from PIL import Image
309
+ from io import BytesIO
310
+ import matplotlib.pyplot as plt
311
+
312
+ endpoint = "http://127.0.0.1:7866/v1/engine/generate/"
313
+
314
+ params = {
315
+ "prompt": "",
316
+ "negative_prompt": "",
317
+ "performance_selection": "Lightning",
318
+ "async_process": False,
319
+ "stream_output": False,
320
+ "webhook_url": ""
321
+ }
322
+
323
+ res = requests.post(
324
+ url=endpoint,
325
+ data=json.dumps(params),
326
+ timeout=60
327
+ )
328
+
329
+ image_stream = BytesIO(res.content)
330
+ image = Image.open(image_stream)
331
+
332
+ plt.imshow(image)
333
+ plt.show()
334
+ ```
335
+
336
+ # 任务查询
337
+
338
+ 和 [Fooocus-API](https://github.com/mrhan1993/Fooocus-API) 不同的是历史记录的保存将是自动进行的,没有保留开关。数据库使用 `SQLite3` 并存放在 `outputs/db.sqlite3` 中。同时吸取了上次的教训,极大简化了表结构,将请求参数作为 JSON 存放在 `req_params` 字段。为了降低读写,仅在任务进入队列时和完成后进行数据库操作。其仅作为生成记录使用,任务状态的追踪会在内存中完成。
339
+
340
+ 此外,该版本会保留输入图像,上传的图像会计算哈希值并保存在 `inputs` 目录,数据库中的 `req_params` 会将图片参数替换为 `url` 信息进行保存,这意味着更完整的历史记录保存,无论是文生图还是图生图又或者是其他
341
+
342
+ ## /tasks
343
+
344
+ 这是个复合接口,但其返回格式是固定的,该接口总是会返回下面格式的 JSON 数据,无论参数如何指定
345
+
346
+ ```python
347
+ {
348
+ "history": [],
349
+ "current": [], # 尽管是个列表,但其中不会超过一个元素。
350
+ "pending": []
351
+ }
352
+ ```
353
+
354
+ 所有的元素其格式都是和数据库中的 scheme 匹配的,除了 `current` 会多一个 `preview` ,比如下图:
355
+
356
+ ![](./assets/tasks.png)
357
+
358
+ 该接口还支持更加精细的用法,参考下面的示例:
359
+
360
+ > 该接口返回格式总是固定的,不管参数如何调整
361
+
362
+ ```shell
363
+ curl http://localhost:7866/tasks?query=current
364
+ # 仅返回当前任务,query 参数还可以指定的值为 'all', 'pending', 'history'
365
+
366
+ curl http://localhost:7866/tasks?query=history&page=3&page_size=5
367
+ # history 和 pending 支持分页和页面大小
368
+
369
+ curl http://localhost:7866/tasks?query=history&start_at=2024-07-03T12:22:30
370
+ # 你可以指定一个时间范围进行查询,这会返回该时间段的所有记录。时间格式是 ISO8601,如果你不指定 end_at 则截止当前时间
371
+
372
+ curl http://localhost:7866/tasks?query=history&start_at=2024-07-03T12:22:30&action=delete
373
+ # 删除指定时间范围的任务,数据库记录和生成文件。目前仅支持这一种删除方法(不会删除 input 文件)。
374
+
375
+ curl http://localhost:7866/tasks/38ba92b188a64233a7336218cd902865
376
+ # 这会返回该任务的信息,但它只是一个字典。相当于从上面列表中取出指定 task_id 的任务,如果它刚好是当前任务,那它也会包含 preview
377
+ ```
docs/openapi.json ADDED
The diff for this file is too large to render. See raw diff
 
environment.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ name: fooocus-api
2
+ channels:
3
+ - defaults
4
+ dependencies:
5
+ - python=3.10
6
+ - pip=23.0
7
+ - packaging
examples/Note.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ All image in imgs folder are generated by AI, so there is no copyright issue.
2
+
3
+ 所有 imgs 目录中的图片都是 AI 生成的,不存在版权问题
examples/examples.ipynb ADDED
@@ -0,0 +1,521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# text to image"
8
+ ]
9
+ },
10
+ {
11
+ "cell_type": "code",
12
+ "execution_count": null,
13
+ "metadata": {
14
+ "ExecuteTime": {
15
+ "end_time": "2024-04-04T10:19:57.369099Z",
16
+ "start_time": "2024-04-04T10:19:57.328298Z"
17
+ }
18
+ },
19
+ "outputs": [],
20
+ "source": [
21
+ "import requests\n",
22
+ "import json\n",
23
+ "\n",
24
+ "# Vincent diagram example\n",
25
+ "host = \"http://127.0.0.1:8888\"\n",
26
+ "\n",
27
+ "def text2img(params: dict) -> dict:\n",
28
+ " \"\"\"\n",
29
+ " Vincent picture\n",
30
+ " \"\"\"\n",
31
+ " response = requests.post(\n",
32
+ " url=f\"{host}/v1/generation/text-to-image\",\n",
33
+ " data=json.dumps(params),\n",
34
+ " headers={\"Content-Type\": \"application/json\"})\n",
35
+ " return response.json()\n",
36
+ "\n",
37
+ "result =text2img({\n",
38
+ " \"performance_selection\": \"Lightning\",\n",
39
+ " \"async_process\": True\n",
40
+ "})\n",
41
+ "print(result)"
42
+ ]
43
+ },
44
+ {
45
+ "cell_type": "markdown",
46
+ "metadata": {},
47
+ "source": [
48
+ "# upscale or vary"
49
+ ]
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "execution_count": null,
54
+ "metadata": {},
55
+ "outputs": [],
56
+ "source": [
57
+ "import requests\n",
58
+ "import json\n",
59
+ "\n",
60
+ "\n",
61
+ "# upscale or vary v1 Interface example\n",
62
+ "host = \"http://127.0.0.1:8888\"\n",
63
+ "image = open(\"./imgs/bear.jpg\", \"rb\").read()\n",
64
+ "\n",
65
+ "def upscale_vary(image, params: dict) -> dict:\n",
66
+ " \"\"\"\n",
67
+ " Upscale or Vary\n",
68
+ " \"\"\"\n",
69
+ " response = requests.post(\n",
70
+ " url=f\"{host}/v1/generation/image-upscale-vary\",\n",
71
+ " data=params,\n",
72
+ " files={\"input_image\": image})\n",
73
+ " return response.json()\n",
74
+ "\n",
75
+ "result =upscale_vary(\n",
76
+ " image=image,\n",
77
+ " params={\n",
78
+ " \"uov_method\": \"Vary\",\n",
79
+ " \"async_process\": True\n",
80
+ " })\n",
81
+ "print(json.dumps(result, indent=4, ensure_ascii=False))"
82
+ ]
83
+ },
84
+ {
85
+ "cell_type": "code",
86
+ "execution_count": null,
87
+ "metadata": {},
88
+ "outputs": [],
89
+ "source": [
90
+ "import requests\n",
91
+ "import json\n",
92
+ "import base64\n",
93
+ "\n",
94
+ "\n",
95
+ "# upscale or vary v2 Interface example\n",
96
+ "host = \"http://127.0.0.1:8888\"\n",
97
+ "image = open(\"./imgs/bear.jpg\", \"rb\").read()\n",
98
+ "\n",
99
+ "def upscale_vary(params: dict) -> dict:\n",
100
+ " \"\"\"\n",
101
+ " Upscale or Vary\n",
102
+ " \"\"\"\n",
103
+ " response = requests.post(\n",
104
+ " url=f\"{host}/v2/generation/image-upscale-vary\",\n",
105
+ " data=json.dumps(params),\n",
106
+ " headers={\"Content-Type\": \"application/json\"},\n",
107
+ " timeout=300)\n",
108
+ " return response.json()\n",
109
+ "\n",
110
+ "result =upscale_vary(\n",
111
+ " params={\n",
112
+ " \"input_image\": base64.b64encode(image).decode('utf-8'),\n",
113
+ " \"uov_method\": \"Upscale (2x)\",\n",
114
+ " \"async_process\": True\n",
115
+ " })\n",
116
+ "print(json.dumps(result, indent=4, ensure_ascii=False))"
117
+ ]
118
+ },
119
+ {
120
+ "cell_type": "markdown",
121
+ "metadata": {},
122
+ "source": [
123
+ "# inpaint or outpaint"
124
+ ]
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "execution_count": null,
129
+ "metadata": {},
130
+ "outputs": [],
131
+ "source": [
132
+ "import requests\n",
133
+ "import json\n",
134
+ "\n",
135
+ "# Partial redraw v1 interface example\n",
136
+ "host = \"http://127.0.0.1:8888\"\n",
137
+ "image = open(\"./imgs/bear.jpg\", \"rb\").read()\n",
138
+ "\n",
139
+ "def inpaint_outpaint(params: dict, input_image: bytes, input_mask: bytes = None) -> dict:\n",
140
+ " \"\"\"\n",
141
+ " Partial redraw v1 interface example\n",
142
+ " \"\"\"\n",
143
+ " response = requests.post(\n",
144
+ " url=f\"{host}/v1/generation/image-inpaint-outpaint\",\n",
145
+ " data=params,\n",
146
+ " files={\"input_image\": input_image,\n",
147
+ " \"input_mask\": input_mask})\n",
148
+ " return response.json()\n",
149
+ "\n",
150
+ "\n",
151
+ "# Image extension example\n",
152
+ "result = inpaint_outpaint(\n",
153
+ " params={\n",
154
+ " \"outpaint_selections\": \"Left,Right\",\n",
155
+ " \"async_process\": True},\n",
156
+ " input_image=image,\n",
157
+ " input_mask=None)\n",
158
+ "print(json.dumps(result, indent=4, ensure_ascii=False))"
159
+ ]
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "execution_count": null,
164
+ "metadata": {},
165
+ "outputs": [],
166
+ "source": [
167
+ "#Partial redraw example\n",
168
+ "source = open(\"./imgs/inpaint_source.jpg\", \"rb\").read()\n",
169
+ "mask = open(\"./imgs/inpaint_mask.png\", \"rb\").read()\n",
170
+ "result = inpaint_outpaint(\n",
171
+ " params={\n",
172
+ " \"prompt\": \"a cat\",\n",
173
+ " \"async_process\": True\n",
174
+ " },\n",
175
+ " input_image=source,\n",
176
+ " input_mask=mask)\n",
177
+ "print(json.dumps(result, indent=4, ensure_ascii=False))"
178
+ ]
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "execution_count": null,
183
+ "metadata": {},
184
+ "outputs": [],
185
+ "source": [
186
+ "import requests\n",
187
+ "import json\n",
188
+ "import base64\n",
189
+ "\n",
190
+ "\n",
191
+ "# Partial redraw v2 interface example\n",
192
+ "host = \"http://127.0.0.1:8888\"\n",
193
+ "image = open(\"./imgs/bear.jpg\", \"rb\").read()\n",
194
+ "\n",
195
+ "def inpaint_outpaint(params: dict) -> dict:\n",
196
+ " \"\"\"\n",
197
+ " Partial redraw v2 interface example\n",
198
+ " \"\"\"\n",
199
+ " response = requests.post(\n",
200
+ " url=f\"{host}/v2/generation/image-inpaint-outpaint\",\n",
201
+ " data=json.dumps(params),\n",
202
+ " headers={\"Content-Type\": \"application/json\"})\n",
203
+ " return response.json()\n",
204
+ "\n",
205
+ "# Image extension example\n",
206
+ "result = inpaint_outpaint(\n",
207
+ " params={\n",
208
+ " \"input_image\": base64.b64encode(image).decode('utf-8'),\n",
209
+ " \"input_mask\": None,\n",
210
+ " \"outpaint_selections\": [\"Left\", \"Right\"],\n",
211
+ " \"async_process\": True\n",
212
+ " })\n",
213
+ "print(json.dumps(result, indent=4, ensure_ascii=False))"
214
+ ]
215
+ },
216
+ {
217
+ "cell_type": "code",
218
+ "execution_count": null,
219
+ "metadata": {},
220
+ "outputs": [],
221
+ "source": [
222
+ "# Partial redraw example\n",
223
+ "source = open(\"./imgs/inpaint_source.jpg\", \"rb\").read()\n",
224
+ "mask = open(\"./imgs/inpaint_mask.png\", \"rb\").read()\n",
225
+ "result = inpaint_outpaint(\n",
226
+ " params={\n",
227
+ " \"prompt\": \"a cat\",\n",
228
+ " \"input_image\": base64.b64encode(source).decode('utf-8'),\n",
229
+ " \"input_mask\": base64.b64encode(mask).decode('utf-8'),\n",
230
+ " \"async_process\": True\n",
231
+ " })\n",
232
+ "print(json.dumps(result, indent=4, ensure_ascii=False))"
233
+ ]
234
+ },
235
+ {
236
+ "cell_type": "markdown",
237
+ "metadata": {},
238
+ "source": [
239
+ "# image prompts"
240
+ ]
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "execution_count": null,
245
+ "metadata": {},
246
+ "outputs": [],
247
+ "source": [
248
+ "import requests\n",
249
+ "import json\n",
250
+ "\n",
251
+ "\n",
252
+ "# image_prompt v1 Interface example\n",
253
+ "host = \"http://127.0.0.1:8888\"\n",
254
+ "image = open(\"./imgs/bear.jpg\", \"rb\").read()\n",
255
+ "source = open(\"./imgs/inpaint_source.jpg\", \"rb\").read()\n",
256
+ "mask = open(\"./imgs/inpaint_mask.png\", \"rb\").read()\n",
257
+ "\n",
258
+ "def image_prompt(\n",
259
+ " params: dict,\n",
260
+ " input_image: bytes=None,\n",
261
+ " input_mask: bytes=None,\n",
262
+ " cn_img1: bytes=None,\n",
263
+ " cn_img2: bytes=None,\n",
264
+ " cn_img3: bytes=None,\n",
265
+ " cn_img4: bytes=None,) -> dict:\n",
266
+ " \"\"\"\n",
267
+ " image prompt\n",
268
+ " \"\"\"\n",
269
+ " response = requests.post(\n",
270
+ " url=f\"{host}/v1/generation/image-prompt\",\n",
271
+ " data=params,\n",
272
+ " files={\n",
273
+ " \"input_image\": input_image,\n",
274
+ " \"input_mask\": input_mask,\n",
275
+ " \"cn_img1\": cn_img1,\n",
276
+ " \"cn_img2\": cn_img2,\n",
277
+ " \"cn_img3\": cn_img3,\n",
278
+ " \"cn_img4\": cn_img4,\n",
279
+ " })\n",
280
+ " return response.json()\n",
281
+ "\n",
282
+ "# image extension\n",
283
+ "params = {\n",
284
+ " \"outpaint_selections\": [\"Left\", \"Right\"],\n",
285
+ " \"image_prompts\": [] # Required parameters, can be an empty list\n",
286
+ "}\n",
287
+ "result = image_prompt(params=params, input_image=image)\n",
288
+ "print(json.dumps(result, indent=4, ensure_ascii=False))"
289
+ ]
290
+ },
291
+ {
292
+ "cell_type": "code",
293
+ "execution_count": null,
294
+ "metadata": {},
295
+ "outputs": [],
296
+ "source": [
297
+ "# partial redraw\n",
298
+ "\n",
299
+ "params = {\n",
300
+ " \"prompt\": \"1girl sitting on the chair\",\n",
301
+ " \"image_prompts\": [], # Required parameters, can be an empty list\n",
302
+ " \"async_process\": True\n",
303
+ "}\n",
304
+ "result = image_prompt(params=params, input_image=source, input_mask=mask)\n",
305
+ "print(json.dumps(result, indent=4, ensure_ascii=False))"
306
+ ]
307
+ },
308
+ {
309
+ "cell_type": "code",
310
+ "execution_count": null,
311
+ "metadata": {},
312
+ "outputs": [],
313
+ "source": [
314
+ "# image prompt\n",
315
+ "\n",
316
+ "params = {\n",
317
+ " \"prompt\": \"1girl sitting on the chair\",\n",
318
+ " \"image_prompts\": [\n",
319
+ " {\n",
320
+ " \"cn_stop\": 0.6,\n",
321
+ " \"cn_weight\": 0.6,\n",
322
+ " \"cn_type\": \"ImagePrompt\"\n",
323
+ " },{\n",
324
+ " \"cn_stop\": 0.6,\n",
325
+ " \"cn_weight\": 0.6,\n",
326
+ " \"cn_type\": \"ImagePrompt\"\n",
327
+ " }]\n",
328
+ " }\n",
329
+ "result = image_prompt(params=params, cn_img1=image, cn_img2=source)\n",
330
+ "print(json.dumps(result, indent=4, ensure_ascii=False))"
331
+ ]
332
+ },
333
+ {
334
+ "cell_type": "code",
335
+ "execution_count": null,
336
+ "metadata": {},
337
+ "outputs": [],
338
+ "source": [
339
+ "import requests\n",
340
+ "import json\n",
341
+ "import base64\n",
342
+ "\n",
343
+ "# image_prompt v2 Interface example\n",
344
+ "host = \"http://127.0.0.1:8888\"\n",
345
+ "image = open(\"./imgs/bear.jpg\", \"rb\").read()\n",
346
+ "source = open(\"./imgs/inpaint_source.jpg\", \"rb\").read()\n",
347
+ "mask = open(\"./imgs/inpaint_mask.png\", \"rb\").read()\n",
348
+ "\n",
349
+ "def image_prompt(params: dict) -> dict:\n",
350
+ " \"\"\"\n",
351
+ " image prompt\n",
352
+ " \"\"\"\n",
353
+ " response = requests.post(\n",
354
+ " url=f\"{host}/v2/generation/image-prompt\",\n",
355
+ " data=json.dumps(params),\n",
356
+ " headers={\"Content-Type\": \"application/json\"})\n",
357
+ " return response.json()\n",
358
+ "\n",
359
+ "# image extension\n",
360
+ "params = {\n",
361
+ " \"input_image\": base64.b64encode(image).decode('utf-8'),\n",
362
+ " \"outpaint_selections\": [\"Left\", \"Right\"],\n",
363
+ " \"image_prompts\": [] # Required parameters, can be an empty list\n",
364
+ "}\n",
365
+ "result = image_prompt(params)\n",
366
+ "print(json.dumps(result, indent=4, ensure_ascii=False))"
367
+ ]
368
+ },
369
+ {
370
+ "cell_type": "code",
371
+ "execution_count": null,
372
+ "metadata": {},
373
+ "outputs": [],
374
+ "source": [
375
+ "# partial redraw\n",
376
+ "\n",
377
+ "params = {\n",
378
+ " \"prompt\": \"1girl sitting on the chair\",\n",
379
+ " \"input_image\": base64.b64encode(source).decode('utf-8'),\n",
380
+ " \"input_mask\": base64.b64encode(mask).decode('utf-8'),\n",
381
+ " \"image_prompts\": [], # Required parameters, can be an empty list\n",
382
+ " \"async_process\": True\n",
383
+ "}\n",
384
+ "result = image_prompt(params)\n",
385
+ "print(json.dumps(result, indent=4, ensure_ascii=False))"
386
+ ]
387
+ },
388
+ {
389
+ "cell_type": "code",
390
+ "execution_count": null,
391
+ "metadata": {},
392
+ "outputs": [],
393
+ "source": [
394
+ "# image prompt\n",
395
+ "\n",
396
+ "params = {\n",
397
+ " \"prompt\": \"1girl sitting on the chair\",\n",
398
+ " \"image_prompts\": [\n",
399
+ " {\n",
400
+ " \"cn_img\": base64.b64encode(source).decode('utf-8'),\n",
401
+ " \"cn_stop\": 0.6,\n",
402
+ " \"cn_weight\": 0.6,\n",
403
+ " \"cn_type\": \"ImagePrompt\"\n",
404
+ " },{\n",
405
+ " \"cn_img\": base64.b64encode(image).decode('utf-8'),\n",
406
+ " \"cn_stop\": 0.6,\n",
407
+ " \"cn_weight\": 0.6,\n",
408
+ " \"cn_type\": \"ImagePrompt\"\n",
409
+ " }]\n",
410
+ " }\n",
411
+ "result = image_prompt(params)\n",
412
+ "print(json.dumps(result, indent=4, ensure_ascii=False))"
413
+ ]
414
+ },
415
+ {
416
+ "cell_type": "markdown",
417
+ "metadata": {},
418
+ "source": [
419
+ " # text to image with image prompt"
420
+ ]
421
+ },
422
+ {
423
+ "cell_type": "code",
424
+ "execution_count": null,
425
+ "metadata": {},
426
+ "outputs": [],
427
+ "source": [
428
+ "import requests\n",
429
+ "import json\n",
430
+ "import base64\n",
431
+ "\n",
432
+ "# text to image with image prompt Example\n",
433
+ "host = \"http://127.0.0.1:8888\"\n",
434
+ "image = open(\"./imgs/image_prompt-1.png\", \"rb\").read()\n",
435
+ "source = open(\"./imgs/image_prompt-0.jpg\", \"rb\").read()\n",
436
+ "def image_prompt(params: dict) -> dict:\n",
437
+ " \"\"\"\n",
438
+ " image prompt\n",
439
+ " \"\"\"\n",
440
+ " response = requests.post(\n",
441
+ " url=f\"{host}/v2/generation/text-to-image-with-ip\",\n",
442
+ " data=json.dumps(params),\n",
443
+ " headers={\"Content-Type\": \"application/json\"})\n",
444
+ " return response.json()\n",
445
+ "\n",
446
+ "params = {\n",
447
+ " \"prompt\": \"A bear\",\n",
448
+ " \"image_prompts\": [\n",
449
+ " {\n",
450
+ " \"cn_img\": base64.b64encode(source).decode('utf-8'),\n",
451
+ " \"cn_stop\": 0.6,\n",
452
+ " \"cn_weight\": 0.6,\n",
453
+ " \"cn_type\": \"ImagePrompt\"\n",
454
+ " },{\n",
455
+ " \"cn_img\": base64.b64encode(image).decode('utf-8'),\n",
456
+ " \"cn_stop\": 0.6,\n",
457
+ " \"cn_weight\": 0.6,\n",
458
+ " \"cn_type\": \"ImagePrompt\"\n",
459
+ " }\n",
460
+ " ]\n",
461
+ "}\n",
462
+ "result = image_prompt(params)\n",
463
+ "print(json.dumps(result, indent=4, ensure_ascii=False))"
464
+ ]
465
+ },
466
+ {
467
+ "cell_type": "markdown",
468
+ "metadata": {},
469
+ "source": [
470
+ "# describe"
471
+ ]
472
+ },
473
+ {
474
+ "cell_type": "code",
475
+ "execution_count": null,
476
+ "metadata": {},
477
+ "outputs": [],
478
+ "source": [
479
+ "import requests\n",
480
+ "\n",
481
+ "image = open(\"./imgs/target_face.png\", \"rb\").read()\n",
482
+ "def describe_image(image: bytes,\n",
483
+ " params: dict = {\"type\": \"Photo\"}) -> dict:\n",
484
+ " \"\"\"\n",
485
+ " describe-image\n",
486
+ " \"\"\"\n",
487
+ " response = requests.post(\n",
488
+ " url=\"http://127.0.0.1:8888/v1/tools/describe-image\",\n",
489
+ " params=params,\n",
490
+ " files={\n",
491
+ " \"image\": image\n",
492
+ " },\n",
493
+ " timeout=30)\n",
494
+ " return response.json()\n",
495
+ "\n",
496
+ "describe_image(image=image)"
497
+ ]
498
+ }
499
+ ],
500
+ "metadata": {
501
+ "kernelspec": {
502
+ "display_name": "Python 3",
503
+ "language": "python",
504
+ "name": "python3"
505
+ },
506
+ "language_info": {
507
+ "codemirror_mode": {
508
+ "name": "ipython",
509
+ "version": 3
510
+ },
511
+ "file_extension": ".py",
512
+ "mimetype": "text/x-python",
513
+ "name": "python",
514
+ "nbconvert_exporter": "python",
515
+ "pygments_lexer": "ipython3",
516
+ "version": "3.10.13"
517
+ }
518
+ },
519
+ "nbformat": 4,
520
+ "nbformat_minor": 2
521
+ }
examples/examples_v1.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Examples codes for Fooocus API
3
+ """
4
+ import json
5
+ import os
6
+ import requests
7
+
8
+
9
+ class Config:
10
+ """
11
+ Config
12
+ Attributes:
13
+ fooocus_host (str): Fooocus API host
14
+ img_upscale (str): Upscale or Vary
15
+ inpaint_outpaint (str): Inpaint or Outpaint
16
+ img_prompt (str): Image Prompt
17
+ """
18
+ fooocus_host = 'http://127.0.0.1:8888'
19
+
20
+ text2image = '/v1/generation/text-to-image'
21
+ img_upscale = '/v1/generation/image-upscale-vary'
22
+ inpaint_outpaint = '/v1/generation/image-inpaint-outpaint'
23
+ img_prompt = '/v1/generation/image-prompt'
24
+
25
+
26
+ def read_image(image_name: str) -> bytes:
27
+ """
28
+ Read image from file
29
+ Args:
30
+ image_name (str): Image file name
31
+ Returns:
32
+ image (bytes): Image data
33
+ """
34
+ path = os.path.join('imgs', image_name)
35
+ with open(path, "rb") as f:
36
+ image = f.read()
37
+ f.close()
38
+ return image
39
+
40
+
41
+ class ImageList:
42
+ """
43
+ Image List
44
+ """
45
+ bear = read_image('bear.jpg')
46
+ image_prompt_0 = read_image('image_prompt-0.jpg')
47
+ image_prompt_1 = read_image('image_prompt-1.png')
48
+ image_prompt_2 = read_image('image_prompt-2.png')
49
+ image_prompt_3 = read_image('image_prompt-3.png')
50
+ inpaint_source = read_image('inpaint_source.jpg')
51
+ inpaint_mask = read_image('inpaint_mask.png')
52
+ source_face_f = read_image('source_face_female.png')
53
+ source_face_m = read_image('source_face_man.png')
54
+ target_face = read_image('target_face.png')
55
+
56
+
57
+ def text2image(params: dict) -> dict:
58
+ """
59
+ Text to image
60
+ Args:
61
+ params (dict): Params
62
+ Returns:
63
+ dict: Response
64
+ """
65
+ data = json.dumps(params)
66
+ response = requests.post(
67
+ url=f"{Config.fooocus_host}{Config.text2image}",
68
+ data=data,
69
+ timeout=300)
70
+ return response.json()
71
+
72
+
73
+ def upscale_vary(image: bytes, params: dict) -> dict:
74
+ """
75
+ Upscale or Vary
76
+ Args:
77
+ image (bytes): Image data
78
+ params (dict): Params
79
+ Returns:
80
+ dict: Response
81
+ """
82
+ response = requests.post(
83
+ url=f"{Config.fooocus_host}{Config.img_upscale}",
84
+ data=params,
85
+ files={
86
+ 'input_image': image,
87
+ },
88
+ timeout=300)
89
+ return response.json()
90
+
91
+
92
+ def inpaint_outpaint(
93
+ params: dict,
94
+ input_image: bytes,
95
+ input_mask: bytes = None) -> dict:
96
+ """
97
+ Inpaint or Outpaint
98
+ Args:
99
+ params (dict): Params
100
+ input_image (bytes): Image data
101
+ input_mask (bytes): Image mask data
102
+ Returns:
103
+ dict: Response
104
+ """
105
+ response = requests.post(
106
+ url=f"{Config.fooocus_host}{Config.inpaint_outpaint}",
107
+ data=params,
108
+ files={
109
+ 'input_image': input_image,
110
+ 'input_mask': input_mask
111
+ },
112
+ timeout=300)
113
+ return response.json()
114
+
115
+
116
+ def image_prompt(
117
+ params: dict,
118
+ input_image: bytes = None,
119
+ input_mask: bytes = None,
120
+ cn_img1: bytes = None,
121
+ cn_img2: bytes = None,
122
+ cn_img3: bytes = None,
123
+ cn_img4: bytes = None,) -> dict:
124
+ """
125
+ Image Prompt
126
+ Args:
127
+ params (dict): Params
128
+ input_image (bytes): Image data
129
+ input_mask (bytes): Image mask data
130
+ cn_img1 (bytes): Image data
131
+ cn_img2 (bytes): Image data
132
+ cn_img3 (bytes): Image data
133
+ cn_img4 (bytes): Image data
134
+ Returns:
135
+ dict: Response
136
+ """
137
+ response = requests.post(
138
+ url=f"{Config.fooocus_host}{Config.img_prompt}",
139
+ data=params,
140
+ files={
141
+ 'input_image': input_image,
142
+ 'input_mask': input_mask,
143
+ 'cn_img1': cn_img1,
144
+ 'cn_img2': cn_img2,
145
+ 'cn_img3': cn_img3,
146
+ 'cn_img4': cn_img4
147
+ },
148
+ timeout=300)
149
+ return response.json()
150
+
151
+
152
+ # ###############################################################
153
+ # Text to image example
154
+ # ################################################################
155
+
156
+ # Text to image example
157
+ t2i_params = {
158
+ "prompt": "a cat",
159
+ "performance_selection": "Lightning",
160
+ "aspect_ratios_selection": "896*1152",
161
+ "async_process": True
162
+ }
163
+
164
+ t2i_result = text2image(params=t2i_params)
165
+ print(json.dumps(t2i_result))
166
+
167
+
168
+ # ###############################################################
169
+ # Upscale or Vary example
170
+ # ################################################################
171
+
172
+ # Upscale or Vary example
173
+ up_params = {
174
+ "uov_method": "Upscale (2x)",
175
+ "async_process": True
176
+ }
177
+
178
+ up_result = upscale_vary(
179
+ image=ImageList.bear,
180
+ params=up_params
181
+ )
182
+ print(json.dumps(up_result))
183
+
184
+
185
+ # ###############################################################
186
+ # Inpaint or Outpaint example
187
+ # ################################################################
188
+
189
+ # Inpaint or Outpaint example
190
+ io_params = {
191
+ "prompt": "a cat",
192
+ "outpaint_selections": "Left,Top",
193
+ "async_process": True
194
+ }
195
+
196
+ io_result = inpaint_outpaint(
197
+ params=io_params,
198
+ input_image=ImageList.inpaint_source,
199
+ input_mask=ImageList.inpaint_mask
200
+ )
201
+ print(json.dumps(io_result))
202
+
203
+
204
+ # ###############################################################
205
+ # Image prompt example
206
+ # ################################################################
207
+
208
+ # Image prompt example
209
+ ip_params = {
210
+ "prompt": "a cat",
211
+ "image_prompts": [
212
+ {
213
+ "cn_stop": 0.6,
214
+ "cn_weight": 0.6,
215
+ "cn_type": "ImagePrompt"
216
+ },
217
+ {
218
+ "cn_stop": 0.6,
219
+ "cn_weight": 0.6,
220
+ "cn_type": "ImagePrompt"
221
+ }
222
+ ]
223
+ }
224
+
225
+ ip_result = image_prompt(
226
+ params=ip_params,
227
+ cn_img1=ImageList.image_prompt_0,
228
+ cn_img2=ImageList.image_prompt_1,
229
+ )
230
+ print(json.dumps(ip_result))
231
+
232
+ # ###############################################################
233
+ # Image Enhance
234
+ # ################################################################
235
+
236
+ # Image Enhance
237
+
238
+ import requests
239
+
240
+ url = "http://localhost:8888/v1/generation/image-enhance"
241
+
242
+ # Define the file path and other form data
243
+ file_path = "./examples/imgs/source_face_man.png"
244
+ form_data = {
245
+ "enhance_checkbox": True,
246
+ "enhance_uov_method": "Disabled",
247
+ "enhance_enabled_1": True,
248
+ "enhance_mask_dino_prompt_1": "face",
249
+ "enhance_enabled_2": True,
250
+ "enhance_mask_dino_prompt_2": "eyes",
251
+ }
252
+
253
+ # Open the file and prepare it for the request
254
+ with open(file_path, "rb") as f:
255
+ image = f.read()
256
+ f.close()
257
+
258
+ # Send the request
259
+ response = requests.post(
260
+ url,
261
+ files={"enhance_input_image": image},
262
+ data=form_data,
263
+ timeout=180)
264
+
265
+ # Print the response content
266
+ print(response.text)
examples/examples_v2.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Examples codes for Fooocus API
3
+ """
4
+ import json
5
+ import os
6
+ import base64
7
+ import requests
8
+
9
+
10
+ class Config:
11
+ """
12
+ Config
13
+ Attributes:
14
+ fooocus_host (str): Fooocus API host
15
+ text2img_ip (str): Text to Image with IP
16
+ img_upscale (str): Upscale or Vary
17
+ inpaint_outpaint (str): Inpaint or Outpaint
18
+ img_prompt (str): Image Prompt
19
+ """
20
+ fooocus_host = 'http://127.0.0.1:8888'
21
+
22
+ text2img_ip = '/v2/generation/text-to-image-with-ip'
23
+ img_upscale = '/v2/generation/image-upscale-vary'
24
+ inpaint_outpaint = '/v2/generation/image-inpaint-outpaint'
25
+ img_prompt = '/v2/generation/image-prompt'
26
+
27
+
28
+ def read_image(image_name: str) -> str:
29
+ """
30
+ Read image from file
31
+ Args:
32
+ image_name (str): Image file name
33
+ Returns:
34
+ str: Image base64
35
+ """
36
+ path = os.path.join('imgs', image_name)
37
+ with open(path, "rb") as f:
38
+ image = f.read()
39
+ f.close()
40
+ return base64.b64encode(image).decode('utf-8')
41
+
42
+
43
+ class ImageList:
44
+ """
45
+ Image List
46
+ """
47
+ bear = read_image('bear.jpg')
48
+ image_prompt_0 = read_image('image_prompt-0.jpg')
49
+ image_prompt_1 = read_image('image_prompt-1.png')
50
+ image_prompt_2 = read_image('image_prompt-2.png')
51
+ image_prompt_3 = read_image('image_prompt-3.png')
52
+ inpaint_source = read_image('inpaint_source.jpg')
53
+ inpaint_mask = read_image('inpaint_mask.png')
54
+ source_face_f = read_image('source_face_female.png')
55
+ source_face_m = read_image('source_face_man.png')
56
+ target_face = read_image('target_face.png')
57
+
58
+
59
+ def upscale_vary(params: dict) -> dict:
60
+ """
61
+ Upscale or Vary
62
+ Args:
63
+ params (dict): Params
64
+ Returns:
65
+ dict: Response
66
+ """
67
+ data = json.dumps(params)
68
+ response = requests.post(
69
+ url=f"{Config.fooocus_host}{Config.img_upscale}",
70
+ data=data,
71
+ timeout=300)
72
+ return response.json()
73
+
74
+
75
+ def inpaint_outpaint(params: dict = None) -> dict:
76
+ """
77
+ Inpaint or Outpaint
78
+ Args:
79
+ params (dict): Params
80
+ Returns:
81
+ dict: Response
82
+ """
83
+ data = json.dumps(params)
84
+ response = requests.post(
85
+ url=f"{Config.fooocus_host}{Config.inpaint_outpaint}",
86
+ data=data,
87
+ timeout=300)
88
+ return response.json()
89
+
90
+
91
+ def image_prompt(params: dict) -> dict:
92
+ """
93
+ Image Prompt
94
+ Args:
95
+ params (dict): Params
96
+ Returns:
97
+ dict: Response
98
+ """
99
+ data = json.dumps(params)
100
+ response = requests.post(
101
+ url=f"{Config.fooocus_host}{Config.img_prompt}",
102
+ data=data,
103
+ timeout=300)
104
+ return response.json()
105
+
106
+
107
+ def text2image_image_prompt(params: dict) -> dict:
108
+ """
109
+ Text to image with image Prompt
110
+ Args:
111
+ params (dict): Params
112
+ Returns:
113
+ dict: Response
114
+ """
115
+ params["outpaint_selections"] = ["Left", "Right"]
116
+ data = json.dumps(params)
117
+ response = requests.post(
118
+ url=f"{Config.fooocus_host}{Config.text2img_ip}",
119
+ data=data,
120
+ timeout=300)
121
+ return response.json()
122
+
123
+
124
+ # ################################################################
125
+ # Upscale or Vary
126
+ # ################################################################
127
+
128
+ # Upscale (2x) example
129
+ uov_params = {
130
+ "input_image": ImageList.image_prompt_0,
131
+ "performance_selection": "Lightning",
132
+ "uov_method": "Upscale (2x)",
133
+ "async_process": True
134
+ }
135
+
136
+ upscale_result = upscale_vary(params=uov_params)
137
+ print(
138
+ json.dumps(
139
+ upscale_result,
140
+ indent=4,
141
+ ensure_ascii=False
142
+ ))
143
+
144
+ # Vary (Strong) example
145
+ uov_params['uov_method'] = 'Vary (Strong)'
146
+
147
+ vary_result = upscale_vary(params=uov_params)
148
+ print(
149
+ json.dumps(
150
+ vary_result,
151
+ indent=4,
152
+ ensure_ascii=False
153
+ ))
154
+
155
+
156
+ # ################################################################
157
+ # Inpaint or Outpaint
158
+ # ################################################################
159
+
160
+ # Inpaint outpaint example
161
+ inpaint_params = {
162
+ "prompt": "a cat", # use background prompt to remove anything what you don't want
163
+ "performance_selection": "Speed", # use Lightning the quality is not good
164
+ "input_image": ImageList.inpaint_source,
165
+ "input_mask": ImageList.inpaint_mask,
166
+ "outpaint_selections": ["Left", "Right"],
167
+ "async_process": False
168
+ }
169
+
170
+ inpaint_result = inpaint_outpaint(params=inpaint_params)
171
+ print(json.dumps(inpaint_result))
172
+
173
+
174
+ # ################################################################
175
+ # Image Prompt example
176
+ # more detail for image prompt can be found:
177
+ # https://github.com/lllyasviel/Fooocus/discussions/557
178
+ # ################################################################
179
+
180
+ # face swap example
181
+ # This parameter comes from the default parameter of the Fooocus interface,
182
+ # but the effect of using this parameter for face swap with Fooocus is general.
183
+ # It is too large for the return of the original image. If necessary, try to adjust more parameters.
184
+ face_swap_params = {
185
+ "performance_selection": "Speed",
186
+ "aspect_ratios_selection": "896*1152",
187
+ "image_prompts": [
188
+ {
189
+ "cn_img": ImageList.source_face_m,
190
+ "cn_stop": 0.5,
191
+ "cn_weight": 0.6,
192
+ "cn_type": "ImagePrompt"
193
+ }, {
194
+ "cn_img": ImageList.target_face,
195
+ "cn_stop": 0.9,
196
+ "cn_weight": 0.75,
197
+ "cn_type": "FaceSwap"
198
+ }
199
+ ],
200
+ "async_process": False
201
+ }
202
+
203
+ face_swap_result = image_prompt(params=face_swap_params)
204
+ print(json.dumps(face_swap_result))
205
+
206
+
207
+ # ################################################################
208
+ # Text to image with image Prompt
209
+ # ################################################################
210
+
211
+ # Text to image with image Prompt example
212
+ t2i_ip_params = {
213
+ "prompt": "a cat",
214
+ "performance_selection": "Speed",
215
+ "image_prompts": [
216
+ {
217
+ "cn_img": ImageList.image_prompt_1,
218
+ "cn_stop": 0.6,
219
+ "cn_weight": 0.8,
220
+ "cn_type": "ImagePrompt"
221
+ }, {
222
+ "cn_img": ImageList.image_prompt_2,
223
+ "cn_stop": 0.6,
224
+ "cn_weight": 0.6,
225
+ "cn_type": "ImagePrompt"
226
+ }
227
+ ],
228
+ "async_process": False
229
+ }
230
+
231
+ t2i_ip_result = text2image_image_prompt(params=t2i_ip_params)
232
+ print(json.dumps(t2i_ip_result))
233
+
234
+ # ################################################################
235
+ # Image Enhance
236
+ # ################################################################
237
+
238
+ # Image Enhance
239
+
240
+ import requests
241
+ import json
242
+
243
+ url = "http://localhost:8888/v2/generation/image-enhance"
244
+
245
+ headers = {
246
+ "Content-Type": "application/json"
247
+ }
248
+
249
+ data = {
250
+ "enhance_input_image": "https://raw.githubusercontent.com/mrhan1993/Fooocus-API/main/examples/imgs/source_face_man.png",
251
+ "enhance_checkbox": True,
252
+ "enhance_uov_method": "Vary (Strong)",
253
+ "enhance_uov_processing_order": "Before First Enhancement",
254
+ "enhance_uov_prompt_type": "Original Prompts",
255
+ "enhance_ctrlnets": [
256
+ {
257
+ "enhance_enabled": True,
258
+ "enhance_mask_dino_prompt": "face",
259
+ "enhance_prompt": "",
260
+ "enhance_negative_prompt": "",
261
+ "enhance_mask_model": "sam",
262
+ "enhance_mask_cloth_category": "full",
263
+ "enhance_mask_sam_model": "vit_b",
264
+ "enhance_mask_text_threshold": 0.25,
265
+ "enhance_mask_box_threshold": 0.3,
266
+ "enhance_mask_sam_max_detections": 0,
267
+ "enhance_inpaint_disable_initial_latent": False,
268
+ "enhance_inpaint_engine": "v2.6",
269
+ "enhance_inpaint_strength": 1.0,
270
+ "enhance_inpaint_respective_field": 0.618,
271
+ "enhance_inpaint_erode_or_dilate": 0.0,
272
+ "enhance_mask_invert": False
273
+ }
274
+ ]
275
+ }
276
+
277
+ response = requests.post(
278
+ url,
279
+ headers=headers,
280
+ data=json.dumps(data),
281
+ timeout=180)
282
+
283
+ if response.status_code == 200:
284
+ print("Request successful!")
285
+ print("Response:", response.json())
286
+ else:
287
+ print("Request failed with status code:", response.status_code)
288
+ print("Response:", response.text)
extras/BLIP/configs/bert_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertModel"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "hidden_act": "gelu",
7
+ "hidden_dropout_prob": 0.1,
8
+ "hidden_size": 768,
9
+ "initializer_range": 0.02,
10
+ "intermediate_size": 3072,
11
+ "layer_norm_eps": 1e-12,
12
+ "max_position_embeddings": 512,
13
+ "model_type": "bert",
14
+ "num_attention_heads": 12,
15
+ "num_hidden_layers": 12,
16
+ "pad_token_id": 0,
17
+ "type_vocab_size": 2,
18
+ "vocab_size": 30522,
19
+ "encoder_width": 768,
20
+ "add_cross_attention": true
21
+ }
extras/BLIP/configs/caption_coco.yaml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ image_root: '/export/share/datasets/vision/coco/images/'
2
+ ann_root: 'annotation'
3
+ coco_gt_root: 'annotation/coco_gt'
4
+
5
+ # set pretrained as a file path or an url
6
+ pretrained: 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_caption_capfilt_large.pth'
7
+
8
+ # size of vit model; base or large
9
+ vit: 'base'
10
+ vit_grad_ckpt: False
11
+ vit_ckpt_layer: 0
12
+ batch_size: 32
13
+ init_lr: 1e-5
14
+
15
+ # vit: 'large'
16
+ # vit_grad_ckpt: True
17
+ # vit_ckpt_layer: 5
18
+ # batch_size: 16
19
+ # init_lr: 2e-6
20
+
21
+ image_size: 384
22
+
23
+ # generation configs
24
+ max_length: 20
25
+ min_length: 5
26
+ num_beams: 3
27
+ prompt: 'a picture of '
28
+
29
+ # optimizer
30
+ weight_decay: 0.05
31
+ min_lr: 0
32
+ max_epoch: 5
33
+
extras/BLIP/configs/med_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertModel"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "hidden_act": "gelu",
7
+ "hidden_dropout_prob": 0.1,
8
+ "hidden_size": 768,
9
+ "initializer_range": 0.02,
10
+ "intermediate_size": 3072,
11
+ "layer_norm_eps": 1e-12,
12
+ "max_position_embeddings": 512,
13
+ "model_type": "bert",
14
+ "num_attention_heads": 12,
15
+ "num_hidden_layers": 12,
16
+ "pad_token_id": 0,
17
+ "type_vocab_size": 2,
18
+ "vocab_size": 30524,
19
+ "encoder_width": 768,
20
+ "add_cross_attention": true
21
+ }
extras/BLIP/configs/nlvr.yaml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ image_root: '/export/share/datasets/vision/NLVR2/'
2
+ ann_root: 'annotation'
3
+
4
+ # set pretrained as a file path or an url
5
+ pretrained: 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_nlvr.pth'
6
+
7
+ #size of vit model; base or large
8
+ vit: 'base'
9
+ batch_size_train: 16
10
+ batch_size_test: 64
11
+ vit_grad_ckpt: False
12
+ vit_ckpt_layer: 0
13
+ max_epoch: 15
14
+
15
+ image_size: 384
16
+
17
+ # optimizer
18
+ weight_decay: 0.05
19
+ init_lr: 3e-5
20
+ min_lr: 0
21
+
extras/BLIP/configs/nocaps.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ image_root: '/export/share/datasets/vision/nocaps/'
2
+ ann_root: 'annotation'
3
+
4
+ # set pretrained as a file path or an url
5
+ pretrained: 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_caption_capfilt_large.pth'
6
+
7
+ vit: 'base'
8
+ batch_size: 32
9
+
10
+ image_size: 384
11
+
12
+ max_length: 20
13
+ min_length: 5
14
+ num_beams: 3
15
+ prompt: 'a picture of '
extras/BLIP/configs/pretrain.yaml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ train_file: ['/export/share/junnan-li/VL_pretrain/annotation/coco_karpathy_train.json',
2
+ '/export/share/junnan-li/VL_pretrain/annotation/vg_caption.json',
3
+ ]
4
+ laion_path: ''
5
+
6
+ # size of vit model; base or large
7
+ vit: 'base'
8
+ vit_grad_ckpt: False
9
+ vit_ckpt_layer: 0
10
+
11
+ image_size: 224
12
+ batch_size: 75
13
+
14
+ queue_size: 57600
15
+ alpha: 0.4
16
+
17
+ # optimizer
18
+ weight_decay: 0.05
19
+ init_lr: 3e-4
20
+ min_lr: 1e-6
21
+ warmup_lr: 1e-6
22
+ lr_decay_rate: 0.9
23
+ max_epoch: 20
24
+ warmup_steps: 3000
25
+
26
+
27
+
extras/BLIP/configs/retrieval_coco.yaml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ image_root: '/export/share/datasets/vision/coco/images/'
2
+ ann_root: 'annotation'
3
+ dataset: 'coco'
4
+
5
+ # set pretrained as a file path or an url
6
+ pretrained: 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth'
7
+
8
+ # size of vit model; base or large
9
+
10
+ vit: 'base'
11
+ batch_size_train: 32
12
+ batch_size_test: 64
13
+ vit_grad_ckpt: True
14
+ vit_ckpt_layer: 4
15
+ init_lr: 1e-5
16
+
17
+ # vit: 'large'
18
+ # batch_size_train: 16
19
+ # batch_size_test: 32
20
+ # vit_grad_ckpt: True
21
+ # vit_ckpt_layer: 12
22
+ # init_lr: 5e-6
23
+
24
+ image_size: 384
25
+ queue_size: 57600
26
+ alpha: 0.4
27
+ k_test: 256
28
+ negative_all_rank: True
29
+
30
+ # optimizer
31
+ weight_decay: 0.05
32
+ min_lr: 0
33
+ max_epoch: 6
34
+
extras/BLIP/configs/retrieval_flickr.yaml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ image_root: '/export/share/datasets/vision/flickr30k/'
2
+ ann_root: 'annotation'
3
+ dataset: 'flickr'
4
+
5
+ # set pretrained as a file path or an url
6
+ pretrained: 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_flickr.pth'
7
+
8
+ # size of vit model; base or large
9
+
10
+ vit: 'base'
11
+ batch_size_train: 32
12
+ batch_size_test: 64
13
+ vit_grad_ckpt: True
14
+ vit_ckpt_layer: 4
15
+ init_lr: 1e-5
16
+
17
+ # vit: 'large'
18
+ # batch_size_train: 16
19
+ # batch_size_test: 32
20
+ # vit_grad_ckpt: True
21
+ # vit_ckpt_layer: 10
22
+ # init_lr: 5e-6
23
+
24
+ image_size: 384
25
+ queue_size: 57600
26
+ alpha: 0.4
27
+ k_test: 128
28
+ negative_all_rank: False
29
+
30
+ # optimizer
31
+ weight_decay: 0.05
32
+ min_lr: 0
33
+ max_epoch: 6
34
+
extras/BLIP/configs/retrieval_msrvtt.yaml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ video_root: '/export/share/dongxuli/data/msrvtt_retrieval/videos'
2
+ ann_root: 'annotation'
3
+
4
+ # set pretrained as a file path or an url
5
+ pretrained: 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth'
6
+
7
+ # size of vit model; base or large
8
+ vit: 'base'
9
+ batch_size: 64
10
+ k_test: 128
11
+ image_size: 384
12
+ num_frm_test: 8
extras/BLIP/configs/vqa.yaml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ vqa_root: '/export/share/datasets/vision/VQA/Images/mscoco/' #followed by train2014/
2
+ vg_root: '/export/share/datasets/vision/visual-genome/' #followed by image/
3
+ train_files: ['vqa_train','vqa_val','vg_qa']
4
+ ann_root: 'annotation'
5
+
6
+ # set pretrained as a file path or an url
7
+ pretrained: 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth'
8
+
9
+ # size of vit model; base or large
10
+ vit: 'base'
11
+ batch_size_train: 16
12
+ batch_size_test: 32
13
+ vit_grad_ckpt: False
14
+ vit_ckpt_layer: 0
15
+ init_lr: 2e-5
16
+
17
+ image_size: 480
18
+
19
+ k_test: 128
20
+ inference: 'rank'
21
+
22
+ # optimizer
23
+ weight_decay: 0.05
24
+ min_lr: 0
25
+ max_epoch: 10
extras/BLIP/models/bert_tokenizer/config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertForMaskedLM"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "gradient_checkpointing": false,
7
+ "hidden_act": "gelu",
8
+ "hidden_dropout_prob": 0.1,
9
+ "hidden_size": 768,
10
+ "initializer_range": 0.02,
11
+ "intermediate_size": 3072,
12
+ "layer_norm_eps": 1e-12,
13
+ "max_position_embeddings": 512,
14
+ "model_type": "bert",
15
+ "num_attention_heads": 12,
16
+ "num_hidden_layers": 12,
17
+ "pad_token_id": 0,
18
+ "position_embedding_type": "absolute",
19
+ "transformers_version": "4.6.0.dev0",
20
+ "type_vocab_size": 2,
21
+ "use_cache": true,
22
+ "vocab_size": 30522
23
+ }
extras/BLIP/models/bert_tokenizer/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
extras/BLIP/models/bert_tokenizer/tokenizer_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "do_lower_case": true
3
+ }
extras/BLIP/models/bert_tokenizer/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
extras/BLIP/models/blip.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ * Copyright (c) 2022, salesforce.com, inc.
3
+ * All rights reserved.
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6
+ * By Junnan Li
7
+ '''
8
+ import warnings
9
+ warnings.filterwarnings("ignore")
10
+
11
+ from extras.BLIP.models.vit import VisionTransformer, interpolate_pos_embed
12
+ from extras.BLIP.models.med import BertConfig, BertModel, BertLMHeadModel
13
+ from transformers import BertTokenizer
14
+
15
+ import torch
16
+ from torch import nn
17
+ import torch.nn.functional as F
18
+
19
+ import os
20
+ from urllib.parse import urlparse
21
+ from timm.models.hub import download_cached_file
22
+
23
+ class BLIP_Base(nn.Module):
24
+ def __init__(self,
25
+ med_config = 'configs/med_config.json',
26
+ image_size = 224,
27
+ vit = 'base',
28
+ vit_grad_ckpt = False,
29
+ vit_ckpt_layer = 0,
30
+ ):
31
+ """
32
+ Args:
33
+ med_config (str): path for the mixture of encoder-decoder model's configuration file
34
+ image_size (int): input image size
35
+ vit (str): model size of vision transformer
36
+ """
37
+ super().__init__()
38
+
39
+ self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer)
40
+ self.tokenizer = init_tokenizer()
41
+ med_config = BertConfig.from_json_file(med_config)
42
+ med_config.encoder_width = vision_width
43
+ self.text_encoder = BertModel(config=med_config, add_pooling_layer=False)
44
+
45
+
46
+ def forward(self, image, caption, mode):
47
+
48
+ assert mode in ['image', 'text', 'multimodal'], "mode parameter must be image, text, or multimodal"
49
+ text = self.tokenizer(caption, return_tensors="pt").to(image.device)
50
+
51
+ if mode=='image':
52
+ # return image features
53
+ image_embeds = self.visual_encoder(image)
54
+ return image_embeds
55
+
56
+ elif mode=='text':
57
+ # return text features
58
+ text_output = self.text_encoder(text.input_ids, attention_mask = text.attention_mask,
59
+ return_dict = True, mode = 'text')
60
+ return text_output.last_hidden_state
61
+
62
+ elif mode=='multimodal':
63
+ # return multimodel features
64
+ image_embeds = self.visual_encoder(image)
65
+ image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
66
+
67
+ text.input_ids[:,0] = self.tokenizer.enc_token_id
68
+ output = self.text_encoder(text.input_ids,
69
+ attention_mask = text.attention_mask,
70
+ encoder_hidden_states = image_embeds,
71
+ encoder_attention_mask = image_atts,
72
+ return_dict = True,
73
+ )
74
+ return output.last_hidden_state
75
+
76
+
77
+
78
+ class BLIP_Decoder(nn.Module):
79
+ def __init__(self,
80
+ med_config = 'configs/med_config.json',
81
+ image_size = 384,
82
+ vit = 'base',
83
+ vit_grad_ckpt = False,
84
+ vit_ckpt_layer = 0,
85
+ prompt = 'a picture of ',
86
+ ):
87
+ """
88
+ Args:
89
+ med_config (str): path for the mixture of encoder-decoder model's configuration file
90
+ image_size (int): input image size
91
+ vit (str): model size of vision transformer
92
+ """
93
+ super().__init__()
94
+
95
+ self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer)
96
+ self.tokenizer = init_tokenizer()
97
+ med_config = BertConfig.from_json_file(med_config)
98
+ med_config.encoder_width = vision_width
99
+ self.text_decoder = BertLMHeadModel(config=med_config)
100
+
101
+ self.prompt = prompt
102
+ self.prompt_length = len(self.tokenizer(self.prompt).input_ids)-1
103
+
104
+
105
+ def forward(self, image, caption):
106
+
107
+ image_embeds = self.visual_encoder(image)
108
+ image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
109
+
110
+ text = self.tokenizer(caption, padding='longest', truncation=True, max_length=40, return_tensors="pt").to(image.device)
111
+
112
+ text.input_ids[:,0] = self.tokenizer.bos_token_id
113
+
114
+ decoder_targets = text.input_ids.masked_fill(text.input_ids == self.tokenizer.pad_token_id, -100)
115
+ decoder_targets[:,:self.prompt_length] = -100
116
+
117
+ decoder_output = self.text_decoder(text.input_ids,
118
+ attention_mask = text.attention_mask,
119
+ encoder_hidden_states = image_embeds,
120
+ encoder_attention_mask = image_atts,
121
+ labels = decoder_targets,
122
+ return_dict = True,
123
+ )
124
+ loss_lm = decoder_output.loss
125
+
126
+ return loss_lm
127
+
128
+ def generate(self, image, sample=False, num_beams=3, max_length=30, min_length=10, top_p=0.9, repetition_penalty=1.0):
129
+ image_embeds = self.visual_encoder(image)
130
+
131
+ if not sample:
132
+ image_embeds = image_embeds.repeat_interleave(num_beams,dim=0)
133
+
134
+ image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
135
+ model_kwargs = {"encoder_hidden_states": image_embeds, "encoder_attention_mask":image_atts}
136
+
137
+ prompt = [self.prompt] * image.size(0)
138
+ input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids.to(image.device)
139
+ input_ids[:,0] = self.tokenizer.bos_token_id
140
+ input_ids = input_ids[:, :-1]
141
+
142
+ if sample:
143
+ #nucleus sampling
144
+ outputs = self.text_decoder.generate(input_ids=input_ids,
145
+ max_length=max_length,
146
+ min_length=min_length,
147
+ do_sample=True,
148
+ top_p=top_p,
149
+ num_return_sequences=1,
150
+ eos_token_id=self.tokenizer.sep_token_id,
151
+ pad_token_id=self.tokenizer.pad_token_id,
152
+ repetition_penalty=1.1,
153
+ **model_kwargs)
154
+ else:
155
+ #beam search
156
+ outputs = self.text_decoder.generate(input_ids=input_ids,
157
+ max_length=max_length,
158
+ min_length=min_length,
159
+ num_beams=num_beams,
160
+ eos_token_id=self.tokenizer.sep_token_id,
161
+ pad_token_id=self.tokenizer.pad_token_id,
162
+ repetition_penalty=repetition_penalty,
163
+ **model_kwargs)
164
+
165
+ captions = []
166
+ for output in outputs:
167
+ caption = self.tokenizer.decode(output, skip_special_tokens=True)
168
+ captions.append(caption[len(self.prompt):])
169
+ return captions
170
+
171
+
172
+ def blip_decoder(pretrained='',**kwargs):
173
+ model = BLIP_Decoder(**kwargs)
174
+ if pretrained:
175
+ model,msg = load_checkpoint(model,pretrained)
176
+ assert(len(msg.missing_keys)==0)
177
+ return model
178
+
179
+ def blip_feature_extractor(pretrained='',**kwargs):
180
+ model = BLIP_Base(**kwargs)
181
+ if pretrained:
182
+ model,msg = load_checkpoint(model,pretrained)
183
+ assert(len(msg.missing_keys)==0)
184
+ return model
185
+
186
+ def init_tokenizer():
187
+ tokenizer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "bert_tokenizer")
188
+ tokenizer = BertTokenizer.from_pretrained(tokenizer_path)
189
+ tokenizer.add_special_tokens({'bos_token':'[DEC]'})
190
+ tokenizer.add_special_tokens({'additional_special_tokens':['[ENC]']})
191
+ tokenizer.enc_token_id = tokenizer.additional_special_tokens_ids[0]
192
+ return tokenizer
193
+
194
+
195
+ def create_vit(vit, image_size, use_grad_checkpointing=False, ckpt_layer=0, drop_path_rate=0):
196
+
197
+ assert vit in ['base', 'large'], "vit parameter must be base or large"
198
+ if vit=='base':
199
+ vision_width = 768
200
+ visual_encoder = VisionTransformer(img_size=image_size, patch_size=16, embed_dim=vision_width, depth=12,
201
+ num_heads=12, use_grad_checkpointing=use_grad_checkpointing, ckpt_layer=ckpt_layer,
202
+ drop_path_rate=0 or drop_path_rate
203
+ )
204
+ elif vit=='large':
205
+ vision_width = 1024
206
+ visual_encoder = VisionTransformer(img_size=image_size, patch_size=16, embed_dim=vision_width, depth=24,
207
+ num_heads=16, use_grad_checkpointing=use_grad_checkpointing, ckpt_layer=ckpt_layer,
208
+ drop_path_rate=0.1 or drop_path_rate
209
+ )
210
+ return visual_encoder, vision_width
211
+
212
+ def is_url(url_or_filename):
213
+ parsed = urlparse(url_or_filename)
214
+ return parsed.scheme in ("http", "https")
215
+
216
+ def load_checkpoint(model,url_or_filename):
217
+ if is_url(url_or_filename):
218
+ cached_file = download_cached_file(url_or_filename, check_hash=False, progress=True)
219
+ checkpoint = torch.load(cached_file, map_location='cpu', weights_only=True)
220
+ elif os.path.isfile(url_or_filename):
221
+ checkpoint = torch.load(url_or_filename, map_location='cpu', weights_only=True)
222
+ else:
223
+ raise RuntimeError('checkpoint url or path is invalid')
224
+
225
+ state_dict = checkpoint['model']
226
+
227
+ state_dict['visual_encoder.pos_embed'] = interpolate_pos_embed(state_dict['visual_encoder.pos_embed'],model.visual_encoder)
228
+ if 'visual_encoder_m.pos_embed' in model.state_dict().keys():
229
+ state_dict['visual_encoder_m.pos_embed'] = interpolate_pos_embed(state_dict['visual_encoder_m.pos_embed'],
230
+ model.visual_encoder_m)
231
+ for key in model.state_dict().keys():
232
+ if key in state_dict.keys():
233
+ if state_dict[key].shape!=model.state_dict()[key].shape:
234
+ del state_dict[key]
235
+
236
+ msg = model.load_state_dict(state_dict,strict=False)
237
+ print('load checkpoint from %s'%url_or_filename)
238
+ return model,msg
239
+
extras/BLIP/models/blip_itm.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from extras.BLIP.models.med import BertConfig, BertModel
2
+ from transformers import BertTokenizer
3
+
4
+ import torch
5
+ from torch import nn
6
+ import torch.nn.functional as F
7
+
8
+ from extras.BLIP.models.blip import create_vit, init_tokenizer, load_checkpoint
9
+
10
+ class BLIP_ITM(nn.Module):
11
+ def __init__(self,
12
+ med_config = 'configs/med_config.json',
13
+ image_size = 384,
14
+ vit = 'base',
15
+ vit_grad_ckpt = False,
16
+ vit_ckpt_layer = 0,
17
+ embed_dim = 256,
18
+ ):
19
+ """
20
+ Args:
21
+ med_config (str): path for the mixture of encoder-decoder model's configuration file
22
+ image_size (int): input image size
23
+ vit (str): model size of vision transformer
24
+ """
25
+ super().__init__()
26
+
27
+ self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer)
28
+ self.tokenizer = init_tokenizer()
29
+ med_config = BertConfig.from_json_file(med_config)
30
+ med_config.encoder_width = vision_width
31
+ self.text_encoder = BertModel(config=med_config, add_pooling_layer=False)
32
+
33
+ text_width = self.text_encoder.config.hidden_size
34
+
35
+ self.vision_proj = nn.Linear(vision_width, embed_dim)
36
+ self.text_proj = nn.Linear(text_width, embed_dim)
37
+
38
+ self.itm_head = nn.Linear(text_width, 2)
39
+
40
+
41
+ def forward(self, image, caption, match_head='itm'):
42
+
43
+ image_embeds = self.visual_encoder(image)
44
+ image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
45
+
46
+ text = self.tokenizer(caption, padding='max_length', truncation=True, max_length=35,
47
+ return_tensors="pt").to(image.device)
48
+
49
+
50
+ if match_head=='itm':
51
+ output = self.text_encoder(text.input_ids,
52
+ attention_mask = text.attention_mask,
53
+ encoder_hidden_states = image_embeds,
54
+ encoder_attention_mask = image_atts,
55
+ return_dict = True,
56
+ )
57
+ itm_output = self.itm_head(output.last_hidden_state[:,0,:])
58
+ return itm_output
59
+
60
+ elif match_head=='itc':
61
+ text_output = self.text_encoder(text.input_ids, attention_mask = text.attention_mask,
62
+ return_dict = True, mode = 'text')
63
+ image_feat = F.normalize(self.vision_proj(image_embeds[:,0,:]),dim=-1)
64
+ text_feat = F.normalize(self.text_proj(text_output.last_hidden_state[:,0,:]),dim=-1)
65
+
66
+ sim = image_feat @ text_feat.t()
67
+ return sim
68
+
69
+
70
+ def blip_itm(pretrained='',**kwargs):
71
+ model = BLIP_ITM(**kwargs)
72
+ if pretrained:
73
+ model,msg = load_checkpoint(model,pretrained)
74
+ assert(len(msg.missing_keys)==0)
75
+ return model
76
+
extras/BLIP/models/blip_nlvr.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from extras.BLIP.models.med import BertConfig
2
+ from extras.BLIP.models.nlvr_encoder import BertModel
3
+ from extras.BLIP.models.vit import interpolate_pos_embed
4
+ from extras.BLIP.models.blip import create_vit, init_tokenizer, is_url
5
+
6
+ from timm.models.hub import download_cached_file
7
+
8
+ import torch
9
+ from torch import nn
10
+ import torch.nn.functional as F
11
+ from transformers import BertTokenizer
12
+ import numpy as np
13
+ import os
14
+
15
+
16
+ class BLIP_NLVR(nn.Module):
17
+ def __init__(self,
18
+ med_config = 'configs/med_config.json',
19
+ image_size = 480,
20
+ vit = 'base',
21
+ vit_grad_ckpt = False,
22
+ vit_ckpt_layer = 0,
23
+ ):
24
+ """
25
+ Args:
26
+ med_config (str): path for the mixture of encoder-decoder model's configuration file
27
+ image_size (int): input image size
28
+ vit (str): model size of vision transformer
29
+ """
30
+ super().__init__()
31
+
32
+ self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer, drop_path_rate=0.1)
33
+ self.tokenizer = init_tokenizer()
34
+ med_config = BertConfig.from_json_file(med_config)
35
+ med_config.encoder_width = vision_width
36
+ self.text_encoder = BertModel(config=med_config, add_pooling_layer=False)
37
+
38
+ self.cls_head = nn.Sequential(
39
+ nn.Linear(self.text_encoder.config.hidden_size, self.text_encoder.config.hidden_size),
40
+ nn.ReLU(),
41
+ nn.Linear(self.text_encoder.config.hidden_size, 2)
42
+ )
43
+
44
+ def forward(self, image, text, targets, train=True):
45
+
46
+ image_embeds = self.visual_encoder(image)
47
+ image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
48
+ image0_embeds, image1_embeds = torch.split(image_embeds,targets.size(0))
49
+
50
+ text = self.tokenizer(text, padding='longest', return_tensors="pt").to(image.device)
51
+ text.input_ids[:,0] = self.tokenizer.enc_token_id
52
+
53
+ output = self.text_encoder(text.input_ids,
54
+ attention_mask = text.attention_mask,
55
+ encoder_hidden_states = [image0_embeds,image1_embeds],
56
+ encoder_attention_mask = [image_atts[:image0_embeds.size(0)],
57
+ image_atts[image0_embeds.size(0):]],
58
+ return_dict = True,
59
+ )
60
+ hidden_state = output.last_hidden_state[:,0,:]
61
+ prediction = self.cls_head(hidden_state)
62
+
63
+ if train:
64
+ loss = F.cross_entropy(prediction, targets)
65
+ return loss
66
+ else:
67
+ return prediction
68
+
69
+ def blip_nlvr(pretrained='',**kwargs):
70
+ model = BLIP_NLVR(**kwargs)
71
+ if pretrained:
72
+ model,msg = load_checkpoint(model,pretrained)
73
+ print("missing keys:")
74
+ print(msg.missing_keys)
75
+ return model
76
+
77
+
78
+ def load_checkpoint(model,url_or_filename):
79
+ if is_url(url_or_filename):
80
+ cached_file = download_cached_file(url_or_filename, check_hash=False, progress=True)
81
+ checkpoint = torch.load(cached_file, map_location='cpu', weights_only=True)
82
+ elif os.path.isfile(url_or_filename):
83
+ checkpoint = torch.load(url_or_filename, map_location='cpu', weights_only=True)
84
+ else:
85
+ raise RuntimeError('checkpoint url or path is invalid')
86
+ state_dict = checkpoint['model']
87
+
88
+ state_dict['visual_encoder.pos_embed'] = interpolate_pos_embed(state_dict['visual_encoder.pos_embed'],model.visual_encoder)
89
+
90
+ for key in list(state_dict.keys()):
91
+ if 'crossattention.self.' in key:
92
+ new_key0 = key.replace('self','self0')
93
+ new_key1 = key.replace('self','self1')
94
+ state_dict[new_key0] = state_dict[key]
95
+ state_dict[new_key1] = state_dict[key]
96
+ elif 'crossattention.output.dense.' in key:
97
+ new_key0 = key.replace('dense','dense0')
98
+ new_key1 = key.replace('dense','dense1')
99
+ state_dict[new_key0] = state_dict[key]
100
+ state_dict[new_key1] = state_dict[key]
101
+
102
+ msg = model.load_state_dict(state_dict,strict=False)
103
+ print('load checkpoint from %s'%url_or_filename)
104
+ return model,msg
105
+
extras/BLIP/models/blip_pretrain.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ * Copyright (c) 2022, salesforce.com, inc.
3
+ * All rights reserved.
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6
+ * By Junnan Li
7
+ '''
8
+ from extras.BLIP.models.med import BertConfig, BertModel, BertLMHeadModel
9
+ from transformers import BertTokenizer
10
+ import transformers
11
+ transformers.logging.set_verbosity_error()
12
+
13
+ import torch
14
+ from torch import nn
15
+ import torch.nn.functional as F
16
+
17
+ from extras.BLIP.models.blip import create_vit, init_tokenizer, load_checkpoint
18
+
19
+ class BLIP_Pretrain(nn.Module):
20
+ def __init__(self,
21
+ med_config = 'configs/bert_config.json',
22
+ image_size = 224,
23
+ vit = 'base',
24
+ vit_grad_ckpt = False,
25
+ vit_ckpt_layer = 0,
26
+ embed_dim = 256,
27
+ queue_size = 57600,
28
+ momentum = 0.995,
29
+ ):
30
+ """
31
+ Args:
32
+ med_config (str): path for the mixture of encoder-decoder model's configuration file
33
+ image_size (int): input image size
34
+ vit (str): model size of vision transformer
35
+ """
36
+ super().__init__()
37
+
38
+ self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer, 0)
39
+
40
+ if vit=='base':
41
+ checkpoint = torch.hub.load_state_dict_from_url(
42
+ url="https://dl.fbaipublicfiles.com/deit/deit_base_patch16_224-b5f2ef4d.pth",
43
+ map_location="cpu", check_hash=True)
44
+ state_dict = checkpoint["model"]
45
+ msg = self.visual_encoder.load_state_dict(state_dict,strict=False)
46
+ elif vit=='large':
47
+ from timm.models.helpers import load_custom_pretrained
48
+ from timm.models.vision_transformer import default_cfgs
49
+ load_custom_pretrained(self.visual_encoder,default_cfgs['vit_large_patch16_224_in21k'])
50
+
51
+ self.tokenizer = init_tokenizer()
52
+ encoder_config = BertConfig.from_json_file(med_config)
53
+ encoder_config.encoder_width = vision_width
54
+ self.text_encoder = BertModel.from_pretrained('bert-base-uncased',config=encoder_config, add_pooling_layer=False)
55
+ self.text_encoder.resize_token_embeddings(len(self.tokenizer))
56
+
57
+ text_width = self.text_encoder.config.hidden_size
58
+
59
+ self.vision_proj = nn.Linear(vision_width, embed_dim)
60
+ self.text_proj = nn.Linear(text_width, embed_dim)
61
+
62
+ self.itm_head = nn.Linear(text_width, 2)
63
+
64
+ # create momentum encoders
65
+ self.visual_encoder_m, vision_width = create_vit(vit,image_size)
66
+ self.vision_proj_m = nn.Linear(vision_width, embed_dim)
67
+ self.text_encoder_m = BertModel(config=encoder_config, add_pooling_layer=False)
68
+ self.text_proj_m = nn.Linear(text_width, embed_dim)
69
+
70
+ self.model_pairs = [[self.visual_encoder,self.visual_encoder_m],
71
+ [self.vision_proj,self.vision_proj_m],
72
+ [self.text_encoder,self.text_encoder_m],
73
+ [self.text_proj,self.text_proj_m],
74
+ ]
75
+ self.copy_params()
76
+
77
+ # create the queue
78
+ self.register_buffer("image_queue", torch.randn(embed_dim, queue_size))
79
+ self.register_buffer("text_queue", torch.randn(embed_dim, queue_size))
80
+ self.register_buffer("queue_ptr", torch.zeros(1, dtype=torch.long))
81
+
82
+ self.image_queue = nn.functional.normalize(self.image_queue, dim=0)
83
+ self.text_queue = nn.functional.normalize(self.text_queue, dim=0)
84
+
85
+ self.queue_size = queue_size
86
+ self.momentum = momentum
87
+ self.temp = nn.Parameter(0.07*torch.ones([]))
88
+
89
+ # create the decoder
90
+ decoder_config = BertConfig.from_json_file(med_config)
91
+ decoder_config.encoder_width = vision_width
92
+ self.text_decoder = BertLMHeadModel.from_pretrained('bert-base-uncased',config=decoder_config)
93
+ self.text_decoder.resize_token_embeddings(len(self.tokenizer))
94
+ tie_encoder_decoder_weights(self.text_encoder,self.text_decoder.bert,'','/attention')
95
+
96
+
97
+ def forward(self, image, caption, alpha):
98
+ with torch.no_grad():
99
+ self.temp.clamp_(0.001,0.5)
100
+
101
+ image_embeds = self.visual_encoder(image)
102
+ image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
103
+ image_feat = F.normalize(self.vision_proj(image_embeds[:,0,:]),dim=-1)
104
+
105
+ text = self.tokenizer(caption, padding='max_length', truncation=True, max_length=30,
106
+ return_tensors="pt").to(image.device)
107
+ text_output = self.text_encoder(text.input_ids, attention_mask = text.attention_mask,
108
+ return_dict = True, mode = 'text')
109
+ text_feat = F.normalize(self.text_proj(text_output.last_hidden_state[:,0,:]),dim=-1)
110
+
111
+ # get momentum features
112
+ with torch.no_grad():
113
+ self._momentum_update()
114
+ image_embeds_m = self.visual_encoder_m(image)
115
+ image_feat_m = F.normalize(self.vision_proj_m(image_embeds_m[:,0,:]),dim=-1)
116
+ image_feat_all = torch.cat([image_feat_m.t(),self.image_queue.clone().detach()],dim=1)
117
+
118
+ text_output_m = self.text_encoder_m(text.input_ids, attention_mask = text.attention_mask,
119
+ return_dict = True, mode = 'text')
120
+ text_feat_m = F.normalize(self.text_proj_m(text_output_m.last_hidden_state[:,0,:]),dim=-1)
121
+ text_feat_all = torch.cat([text_feat_m.t(),self.text_queue.clone().detach()],dim=1)
122
+
123
+ sim_i2t_m = image_feat_m @ text_feat_all / self.temp
124
+ sim_t2i_m = text_feat_m @ image_feat_all / self.temp
125
+
126
+ sim_targets = torch.zeros(sim_i2t_m.size()).to(image.device)
127
+ sim_targets.fill_diagonal_(1)
128
+
129
+ sim_i2t_targets = alpha * F.softmax(sim_i2t_m, dim=1) + (1 - alpha) * sim_targets
130
+ sim_t2i_targets = alpha * F.softmax(sim_t2i_m, dim=1) + (1 - alpha) * sim_targets
131
+
132
+ sim_i2t = image_feat @ text_feat_all / self.temp
133
+ sim_t2i = text_feat @ image_feat_all / self.temp
134
+
135
+ loss_i2t = -torch.sum(F.log_softmax(sim_i2t, dim=1)*sim_i2t_targets,dim=1).mean()
136
+ loss_t2i = -torch.sum(F.log_softmax(sim_t2i, dim=1)*sim_t2i_targets,dim=1).mean()
137
+
138
+ loss_ita = (loss_i2t+loss_t2i)/2
139
+
140
+ self._dequeue_and_enqueue(image_feat_m, text_feat_m)
141
+
142
+ ###============== Image-text Matching ===================###
143
+ encoder_input_ids = text.input_ids.clone()
144
+ encoder_input_ids[:,0] = self.tokenizer.enc_token_id
145
+
146
+ # forward the positve image-text pair
147
+ bs = image.size(0)
148
+ output_pos = self.text_encoder(encoder_input_ids,
149
+ attention_mask = text.attention_mask,
150
+ encoder_hidden_states = image_embeds,
151
+ encoder_attention_mask = image_atts,
152
+ return_dict = True,
153
+ )
154
+ with torch.no_grad():
155
+ weights_t2i = F.softmax(sim_t2i[:,:bs],dim=1)+1e-4
156
+ weights_t2i.fill_diagonal_(0)
157
+ weights_i2t = F.softmax(sim_i2t[:,:bs],dim=1)+1e-4
158
+ weights_i2t.fill_diagonal_(0)
159
+
160
+ # select a negative image for each text
161
+ image_embeds_neg = []
162
+ for b in range(bs):
163
+ neg_idx = torch.multinomial(weights_t2i[b], 1).item()
164
+ image_embeds_neg.append(image_embeds[neg_idx])
165
+ image_embeds_neg = torch.stack(image_embeds_neg,dim=0)
166
+
167
+ # select a negative text for each image
168
+ text_ids_neg = []
169
+ text_atts_neg = []
170
+ for b in range(bs):
171
+ neg_idx = torch.multinomial(weights_i2t[b], 1).item()
172
+ text_ids_neg.append(encoder_input_ids[neg_idx])
173
+ text_atts_neg.append(text.attention_mask[neg_idx])
174
+
175
+ text_ids_neg = torch.stack(text_ids_neg,dim=0)
176
+ text_atts_neg = torch.stack(text_atts_neg,dim=0)
177
+
178
+ text_ids_all = torch.cat([encoder_input_ids, text_ids_neg],dim=0)
179
+ text_atts_all = torch.cat([text.attention_mask, text_atts_neg],dim=0)
180
+
181
+ image_embeds_all = torch.cat([image_embeds_neg,image_embeds],dim=0)
182
+ image_atts_all = torch.cat([image_atts,image_atts],dim=0)
183
+
184
+ output_neg = self.text_encoder(text_ids_all,
185
+ attention_mask = text_atts_all,
186
+ encoder_hidden_states = image_embeds_all,
187
+ encoder_attention_mask = image_atts_all,
188
+ return_dict = True,
189
+ )
190
+
191
+ vl_embeddings = torch.cat([output_pos.last_hidden_state[:,0,:], output_neg.last_hidden_state[:,0,:]],dim=0)
192
+ vl_output = self.itm_head(vl_embeddings)
193
+
194
+ itm_labels = torch.cat([torch.ones(bs,dtype=torch.long),torch.zeros(2*bs,dtype=torch.long)],
195
+ dim=0).to(image.device)
196
+ loss_itm = F.cross_entropy(vl_output, itm_labels)
197
+
198
+ ##================= LM ========================##
199
+ decoder_input_ids = text.input_ids.clone()
200
+ decoder_input_ids[:,0] = self.tokenizer.bos_token_id
201
+ decoder_targets = decoder_input_ids.masked_fill(decoder_input_ids == self.tokenizer.pad_token_id, -100)
202
+
203
+ decoder_output = self.text_decoder(decoder_input_ids,
204
+ attention_mask = text.attention_mask,
205
+ encoder_hidden_states = image_embeds,
206
+ encoder_attention_mask = image_atts,
207
+ labels = decoder_targets,
208
+ return_dict = True,
209
+ )
210
+
211
+ loss_lm = decoder_output.loss
212
+ return loss_ita, loss_itm, loss_lm
213
+
214
+
215
+
216
+ @torch.no_grad()
217
+ def copy_params(self):
218
+ for model_pair in self.model_pairs:
219
+ for param, param_m in zip(model_pair[0].parameters(), model_pair[1].parameters()):
220
+ param_m.data.copy_(param.data) # initialize
221
+ param_m.requires_grad = False # not update by gradient
222
+
223
+
224
+ @torch.no_grad()
225
+ def _momentum_update(self):
226
+ for model_pair in self.model_pairs:
227
+ for param, param_m in zip(model_pair[0].parameters(), model_pair[1].parameters()):
228
+ param_m.data = param_m.data * self.momentum + param.data * (1. - self.momentum)
229
+
230
+
231
+ @torch.no_grad()
232
+ def _dequeue_and_enqueue(self, image_feat, text_feat):
233
+ # gather keys before updating queue
234
+ image_feats = concat_all_gather(image_feat)
235
+ text_feats = concat_all_gather(text_feat)
236
+
237
+ batch_size = image_feats.shape[0]
238
+
239
+ ptr = int(self.queue_ptr)
240
+ assert self.queue_size % batch_size == 0 # for simplicity
241
+
242
+ # replace the keys at ptr (dequeue and enqueue)
243
+ self.image_queue[:, ptr:ptr + batch_size] = image_feats.T
244
+ self.text_queue[:, ptr:ptr + batch_size] = text_feats.T
245
+ ptr = (ptr + batch_size) % self.queue_size # move pointer
246
+
247
+ self.queue_ptr[0] = ptr
248
+
249
+
250
+ def blip_pretrain(**kwargs):
251
+ model = BLIP_Pretrain(**kwargs)
252
+ return model
253
+
254
+
255
+ @torch.no_grad()
256
+ def concat_all_gather(tensor):
257
+ """
258
+ Performs all_gather operation on the provided tensors.
259
+ *** Warning ***: torch.distributed.all_gather has no gradient.
260
+ """
261
+ tensors_gather = [torch.ones_like(tensor)
262
+ for _ in range(torch.distributed.get_world_size())]
263
+ torch.distributed.all_gather(tensors_gather, tensor, async_op=False)
264
+
265
+ output = torch.cat(tensors_gather, dim=0)
266
+ return output
267
+
268
+
269
+ from typing import List
270
+ def tie_encoder_decoder_weights(encoder: nn.Module, decoder: nn.Module, base_model_prefix: str, skip_key:str):
271
+ uninitialized_encoder_weights: List[str] = []
272
+ if decoder.__class__ != encoder.__class__:
273
+ print(
274
+ f"{decoder.__class__} and {encoder.__class__} are not equal. In this case make sure that all encoder weights are correctly initialized."
275
+ )
276
+
277
+ def tie_encoder_to_decoder_recursively(
278
+ decoder_pointer: nn.Module,
279
+ encoder_pointer: nn.Module,
280
+ module_name: str,
281
+ uninitialized_encoder_weights: List[str],
282
+ skip_key: str,
283
+ depth=0,
284
+ ):
285
+ assert isinstance(decoder_pointer, nn.Module) and isinstance(
286
+ encoder_pointer, nn.Module
287
+ ), f"{decoder_pointer} and {encoder_pointer} have to be of type torch.nn.Module"
288
+ if hasattr(decoder_pointer, "weight") and skip_key not in module_name:
289
+ assert hasattr(encoder_pointer, "weight")
290
+ encoder_pointer.weight = decoder_pointer.weight
291
+ if hasattr(decoder_pointer, "bias"):
292
+ assert hasattr(encoder_pointer, "bias")
293
+ encoder_pointer.bias = decoder_pointer.bias
294
+ print(module_name+' is tied')
295
+ return
296
+
297
+ encoder_modules = encoder_pointer._modules
298
+ decoder_modules = decoder_pointer._modules
299
+ if len(decoder_modules) > 0:
300
+ assert (
301
+ len(encoder_modules) > 0
302
+ ), f"Encoder module {encoder_pointer} does not match decoder module {decoder_pointer}"
303
+
304
+ all_encoder_weights = set([module_name + "/" + sub_name for sub_name in encoder_modules.keys()])
305
+ encoder_layer_pos = 0
306
+ for name, module in decoder_modules.items():
307
+ if name.isdigit():
308
+ encoder_name = str(int(name) + encoder_layer_pos)
309
+ decoder_name = name
310
+ if not isinstance(decoder_modules[decoder_name], type(encoder_modules[encoder_name])) and len(
311
+ encoder_modules
312
+ ) != len(decoder_modules):
313
+ # this can happen if the name corresponds to the position in a list module list of layers
314
+ # in this case the decoder has added a cross-attention that the encoder does not have
315
+ # thus skip this step and subtract one layer pos from encoder
316
+ encoder_layer_pos -= 1
317
+ continue
318
+ elif name not in encoder_modules:
319
+ continue
320
+ elif depth > 500:
321
+ raise ValueError(
322
+ "Max depth of recursive function `tie_encoder_to_decoder` reached. It seems that there is a circular dependency between two or more `nn.Modules` of your model."
323
+ )
324
+ else:
325
+ decoder_name = encoder_name = name
326
+ tie_encoder_to_decoder_recursively(
327
+ decoder_modules[decoder_name],
328
+ encoder_modules[encoder_name],
329
+ module_name + "/" + name,
330
+ uninitialized_encoder_weights,
331
+ skip_key,
332
+ depth=depth + 1,
333
+ )
334
+ all_encoder_weights.remove(module_name + "/" + encoder_name)
335
+
336
+ uninitialized_encoder_weights += list(all_encoder_weights)
337
+
338
+ # tie weights recursively
339
+ tie_encoder_to_decoder_recursively(decoder, encoder, base_model_prefix, uninitialized_encoder_weights, skip_key)
extras/BLIP/models/blip_retrieval.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from extras.BLIP.models.med import BertConfig, BertModel
2
+ from transformers import BertTokenizer
3
+
4
+ import torch
5
+ from torch import nn
6
+ import torch.nn.functional as F
7
+
8
+ from extras.BLIP.models.blip import create_vit, init_tokenizer, load_checkpoint
9
+
10
+ class BLIP_Retrieval(nn.Module):
11
+ def __init__(self,
12
+ med_config = 'configs/med_config.json',
13
+ image_size = 384,
14
+ vit = 'base',
15
+ vit_grad_ckpt = False,
16
+ vit_ckpt_layer = 0,
17
+ embed_dim = 256,
18
+ queue_size = 57600,
19
+ momentum = 0.995,
20
+ negative_all_rank = False,
21
+ ):
22
+ """
23
+ Args:
24
+ med_config (str): path for the mixture of encoder-decoder model's configuration file
25
+ image_size (int): input image size
26
+ vit (str): model size of vision transformer
27
+ """
28
+ super().__init__()
29
+
30
+ self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer)
31
+ self.tokenizer = init_tokenizer()
32
+ med_config = BertConfig.from_json_file(med_config)
33
+ med_config.encoder_width = vision_width
34
+ self.text_encoder = BertModel(config=med_config, add_pooling_layer=False)
35
+
36
+ text_width = self.text_encoder.config.hidden_size
37
+
38
+ self.vision_proj = nn.Linear(vision_width, embed_dim)
39
+ self.text_proj = nn.Linear(text_width, embed_dim)
40
+
41
+ self.itm_head = nn.Linear(text_width, 2)
42
+
43
+ # create momentum encoders
44
+ self.visual_encoder_m, vision_width = create_vit(vit,image_size)
45
+ self.vision_proj_m = nn.Linear(vision_width, embed_dim)
46
+ self.text_encoder_m = BertModel(config=med_config, add_pooling_layer=False)
47
+ self.text_proj_m = nn.Linear(text_width, embed_dim)
48
+
49
+ self.model_pairs = [[self.visual_encoder,self.visual_encoder_m],
50
+ [self.vision_proj,self.vision_proj_m],
51
+ [self.text_encoder,self.text_encoder_m],
52
+ [self.text_proj,self.text_proj_m],
53
+ ]
54
+ self.copy_params()
55
+
56
+ # create the queue
57
+ self.register_buffer("image_queue", torch.randn(embed_dim, queue_size))
58
+ self.register_buffer("text_queue", torch.randn(embed_dim, queue_size))
59
+ self.register_buffer("idx_queue", torch.full((1,queue_size),-100))
60
+ self.register_buffer("ptr_queue", torch.zeros(1, dtype=torch.long))
61
+
62
+ self.image_queue = nn.functional.normalize(self.image_queue, dim=0)
63
+ self.text_queue = nn.functional.normalize(self.text_queue, dim=0)
64
+
65
+ self.queue_size = queue_size
66
+ self.momentum = momentum
67
+ self.temp = nn.Parameter(0.07*torch.ones([]))
68
+
69
+ self.negative_all_rank = negative_all_rank
70
+
71
+
72
+ def forward(self, image, caption, alpha, idx):
73
+ with torch.no_grad():
74
+ self.temp.clamp_(0.001,0.5)
75
+
76
+ image_embeds = self.visual_encoder(image)
77
+ image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
78
+ image_feat = F.normalize(self.vision_proj(image_embeds[:,0,:]),dim=-1)
79
+
80
+ text = self.tokenizer(caption, padding='max_length', truncation=True, max_length=35,
81
+ return_tensors="pt").to(image.device)
82
+
83
+ text_output = self.text_encoder(text.input_ids, attention_mask = text.attention_mask,
84
+ return_dict = True, mode = 'text')
85
+ text_feat = F.normalize(self.text_proj(text_output.last_hidden_state[:,0,:]),dim=-1)
86
+
87
+ ###============== Image-text Contrastive Learning ===================###
88
+ idx = idx.view(-1,1)
89
+ idx_all = torch.cat([idx.t(), self.idx_queue.clone().detach()],dim=1)
90
+ pos_idx = torch.eq(idx, idx_all).float()
91
+ sim_targets = pos_idx / pos_idx.sum(1,keepdim=True)
92
+
93
+ # get momentum features
94
+ with torch.no_grad():
95
+ self._momentum_update()
96
+ image_embeds_m = self.visual_encoder_m(image)
97
+ image_feat_m = F.normalize(self.vision_proj_m(image_embeds_m[:,0,:]),dim=-1)
98
+ image_feat_m_all = torch.cat([image_feat_m.t(),self.image_queue.clone().detach()],dim=1)
99
+
100
+ text_output_m = self.text_encoder_m(text.input_ids, attention_mask = text.attention_mask,
101
+ return_dict = True, mode = 'text')
102
+ text_feat_m = F.normalize(self.text_proj_m(text_output_m.last_hidden_state[:,0,:]),dim=-1)
103
+ text_feat_m_all = torch.cat([text_feat_m.t(),self.text_queue.clone().detach()],dim=1)
104
+
105
+ sim_i2t_m = image_feat_m @ text_feat_m_all / self.temp
106
+ sim_t2i_m = text_feat_m @ image_feat_m_all / self.temp
107
+
108
+ sim_i2t_targets = alpha * F.softmax(sim_i2t_m, dim=1) + (1 - alpha) * sim_targets
109
+ sim_t2i_targets = alpha * F.softmax(sim_t2i_m, dim=1) + (1 - alpha) * sim_targets
110
+
111
+ sim_i2t = image_feat @ text_feat_m_all / self.temp
112
+ sim_t2i = text_feat @ image_feat_m_all / self.temp
113
+
114
+ loss_i2t = -torch.sum(F.log_softmax(sim_i2t, dim=1)*sim_i2t_targets,dim=1).mean()
115
+ loss_t2i = -torch.sum(F.log_softmax(sim_t2i, dim=1)*sim_t2i_targets,dim=1).mean()
116
+
117
+ loss_ita = (loss_i2t+loss_t2i)/2
118
+
119
+ idxs = concat_all_gather(idx)
120
+ self._dequeue_and_enqueue(image_feat_m, text_feat_m, idxs)
121
+
122
+ ###============== Image-text Matching ===================###
123
+ encoder_input_ids = text.input_ids.clone()
124
+ encoder_input_ids[:,0] = self.tokenizer.enc_token_id
125
+
126
+ # forward the positve image-text pair
127
+ bs = image.size(0)
128
+ output_pos = self.text_encoder(encoder_input_ids,
129
+ attention_mask = text.attention_mask,
130
+ encoder_hidden_states = image_embeds,
131
+ encoder_attention_mask = image_atts,
132
+ return_dict = True,
133
+ )
134
+
135
+
136
+ if self.negative_all_rank:
137
+ # compute sample similarity
138
+ with torch.no_grad():
139
+ mask = torch.eq(idx, idxs.t())
140
+
141
+ image_feat_world = concat_all_gather(image_feat)
142
+ text_feat_world = concat_all_gather(text_feat)
143
+
144
+ sim_i2t = image_feat @ text_feat_world.t() / self.temp
145
+ sim_t2i = text_feat @ image_feat_world.t() / self.temp
146
+
147
+ weights_i2t = F.softmax(sim_i2t,dim=1)
148
+ weights_i2t.masked_fill_(mask, 0)
149
+
150
+ weights_t2i = F.softmax(sim_t2i,dim=1)
151
+ weights_t2i.masked_fill_(mask, 0)
152
+
153
+ image_embeds_world = all_gather_with_grad(image_embeds)
154
+
155
+ # select a negative image (from all ranks) for each text
156
+ image_embeds_neg = []
157
+ for b in range(bs):
158
+ neg_idx = torch.multinomial(weights_t2i[b], 1).item()
159
+ image_embeds_neg.append(image_embeds_world[neg_idx])
160
+ image_embeds_neg = torch.stack(image_embeds_neg,dim=0)
161
+
162
+ # select a negative text (from all ranks) for each image
163
+ input_ids_world = concat_all_gather(encoder_input_ids)
164
+ att_mask_world = concat_all_gather(text.attention_mask)
165
+
166
+ text_ids_neg = []
167
+ text_atts_neg = []
168
+ for b in range(bs):
169
+ neg_idx = torch.multinomial(weights_i2t[b], 1).item()
170
+ text_ids_neg.append(input_ids_world[neg_idx])
171
+ text_atts_neg.append(att_mask_world[neg_idx])
172
+
173
+ else:
174
+ with torch.no_grad():
175
+ mask = torch.eq(idx, idx.t())
176
+
177
+ sim_i2t = image_feat @ text_feat.t() / self.temp
178
+ sim_t2i = text_feat @ image_feat.t() / self.temp
179
+
180
+ weights_i2t = F.softmax(sim_i2t,dim=1)
181
+ weights_i2t.masked_fill_(mask, 0)
182
+
183
+ weights_t2i = F.softmax(sim_t2i,dim=1)
184
+ weights_t2i.masked_fill_(mask, 0)
185
+
186
+ # select a negative image (from same rank) for each text
187
+ image_embeds_neg = []
188
+ for b in range(bs):
189
+ neg_idx = torch.multinomial(weights_t2i[b], 1).item()
190
+ image_embeds_neg.append(image_embeds[neg_idx])
191
+ image_embeds_neg = torch.stack(image_embeds_neg,dim=0)
192
+
193
+ # select a negative text (from same rank) for each image
194
+ text_ids_neg = []
195
+ text_atts_neg = []
196
+ for b in range(bs):
197
+ neg_idx = torch.multinomial(weights_i2t[b], 1).item()
198
+ text_ids_neg.append(encoder_input_ids[neg_idx])
199
+ text_atts_neg.append(text.attention_mask[neg_idx])
200
+
201
+ text_ids_neg = torch.stack(text_ids_neg,dim=0)
202
+ text_atts_neg = torch.stack(text_atts_neg,dim=0)
203
+
204
+ text_ids_all = torch.cat([encoder_input_ids, text_ids_neg],dim=0)
205
+ text_atts_all = torch.cat([text.attention_mask, text_atts_neg],dim=0)
206
+
207
+ image_embeds_all = torch.cat([image_embeds_neg,image_embeds],dim=0)
208
+ image_atts_all = torch.cat([image_atts,image_atts],dim=0)
209
+
210
+ output_neg = self.text_encoder(text_ids_all,
211
+ attention_mask = text_atts_all,
212
+ encoder_hidden_states = image_embeds_all,
213
+ encoder_attention_mask = image_atts_all,
214
+ return_dict = True,
215
+ )
216
+
217
+
218
+ vl_embeddings = torch.cat([output_pos.last_hidden_state[:,0,:], output_neg.last_hidden_state[:,0,:]],dim=0)
219
+ vl_output = self.itm_head(vl_embeddings)
220
+
221
+ itm_labels = torch.cat([torch.ones(bs,dtype=torch.long),torch.zeros(2*bs,dtype=torch.long)],
222
+ dim=0).to(image.device)
223
+ loss_itm = F.cross_entropy(vl_output, itm_labels)
224
+
225
+ return loss_ita, loss_itm
226
+
227
+
228
+ @torch.no_grad()
229
+ def copy_params(self):
230
+ for model_pair in self.model_pairs:
231
+ for param, param_m in zip(model_pair[0].parameters(), model_pair[1].parameters()):
232
+ param_m.data.copy_(param.data) # initialize
233
+ param_m.requires_grad = False # not update by gradient
234
+
235
+
236
+ @torch.no_grad()
237
+ def _momentum_update(self):
238
+ for model_pair in self.model_pairs:
239
+ for param, param_m in zip(model_pair[0].parameters(), model_pair[1].parameters()):
240
+ param_m.data = param_m.data * self.momentum + param.data * (1. - self.momentum)
241
+
242
+
243
+ @torch.no_grad()
244
+ def _dequeue_and_enqueue(self, image_feat, text_feat, idxs):
245
+ # gather keys before updating queue
246
+ image_feats = concat_all_gather(image_feat)
247
+ text_feats = concat_all_gather(text_feat)
248
+
249
+
250
+ batch_size = image_feats.shape[0]
251
+
252
+ ptr = int(self.ptr_queue)
253
+ assert self.queue_size % batch_size == 0 # for simplicity
254
+
255
+ # replace the keys at ptr (dequeue and enqueue)
256
+ self.image_queue[:, ptr:ptr + batch_size] = image_feats.T
257
+ self.text_queue[:, ptr:ptr + batch_size] = text_feats.T
258
+ self.idx_queue[:, ptr:ptr + batch_size] = idxs.T
259
+ ptr = (ptr + batch_size) % self.queue_size # move pointer
260
+
261
+ self.ptr_queue[0] = ptr
262
+
263
+
264
+ def blip_retrieval(pretrained='',**kwargs):
265
+ model = BLIP_Retrieval(**kwargs)
266
+ if pretrained:
267
+ model,msg = load_checkpoint(model,pretrained)
268
+ print("missing keys:")
269
+ print(msg.missing_keys)
270
+ return model
271
+
272
+
273
+ @torch.no_grad()
274
+ def concat_all_gather(tensor):
275
+ """
276
+ Performs all_gather operation on the provided tensors.
277
+ *** Warning ***: torch.distributed.all_gather has no gradient.
278
+ """
279
+ tensors_gather = [torch.ones_like(tensor)
280
+ for _ in range(torch.distributed.get_world_size())]
281
+ torch.distributed.all_gather(tensors_gather, tensor, async_op=False)
282
+
283
+ output = torch.cat(tensors_gather, dim=0)
284
+ return output
285
+
286
+
287
+ class GatherLayer(torch.autograd.Function):
288
+ """
289
+ Gather tensors from all workers with support for backward propagation:
290
+ This implementation does not cut the gradients as torch.distributed.all_gather does.
291
+ """
292
+
293
+ @staticmethod
294
+ def forward(ctx, x):
295
+ output = [torch.zeros_like(x) for _ in range(torch.distributed.get_world_size())]
296
+ torch.distributed.all_gather(output, x)
297
+ return tuple(output)
298
+
299
+ @staticmethod
300
+ def backward(ctx, *grads):
301
+ all_gradients = torch.stack(grads)
302
+ torch.distributed.all_reduce(all_gradients)
303
+ return all_gradients[torch.distributed.get_rank()]
304
+
305
+
306
+ def all_gather_with_grad(tensors):
307
+ """
308
+ Performs all_gather operation on the provided tensors.
309
+ Graph remains connected for backward grad computation.
310
+ """
311
+ # Queue the gathered tensors
312
+ world_size = torch.distributed.get_world_size()
313
+ # There is no need for reduction in the single-proc case
314
+ if world_size == 1:
315
+ return tensors
316
+
317
+ tensor_all = GatherLayer.apply(tensors)
318
+
319
+ return torch.cat(tensor_all, dim=0)
extras/BLIP/models/blip_vqa.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from extras.BLIP.models.med import BertConfig, BertModel, BertLMHeadModel
2
+ from extras.BLIP.models.blip import create_vit, init_tokenizer, load_checkpoint
3
+
4
+ import torch
5
+ from torch import nn
6
+ import torch.nn.functional as F
7
+ from transformers import BertTokenizer
8
+ import numpy as np
9
+
10
+ class BLIP_VQA(nn.Module):
11
+ def __init__(self,
12
+ med_config = 'configs/med_config.json',
13
+ image_size = 480,
14
+ vit = 'base',
15
+ vit_grad_ckpt = False,
16
+ vit_ckpt_layer = 0,
17
+ ):
18
+ """
19
+ Args:
20
+ med_config (str): path for the mixture of encoder-decoder model's configuration file
21
+ image_size (int): input image size
22
+ vit (str): model size of vision transformer
23
+ """
24
+ super().__init__()
25
+
26
+ self.visual_encoder, vision_width = create_vit(vit, image_size, vit_grad_ckpt, vit_ckpt_layer, drop_path_rate=0.1)
27
+ self.tokenizer = init_tokenizer()
28
+
29
+ encoder_config = BertConfig.from_json_file(med_config)
30
+ encoder_config.encoder_width = vision_width
31
+ self.text_encoder = BertModel(config=encoder_config, add_pooling_layer=False)
32
+
33
+ decoder_config = BertConfig.from_json_file(med_config)
34
+ self.text_decoder = BertLMHeadModel(config=decoder_config)
35
+
36
+
37
+ def forward(self, image, question, answer=None, n=None, weights=None, train=True, inference='rank', k_test=128):
38
+
39
+ image_embeds = self.visual_encoder(image)
40
+ image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
41
+
42
+ question = self.tokenizer(question, padding='longest', truncation=True, max_length=35,
43
+ return_tensors="pt").to(image.device)
44
+ question.input_ids[:,0] = self.tokenizer.enc_token_id
45
+
46
+ if train:
47
+ '''
48
+ n: number of answers for each question
49
+ weights: weight for each answer
50
+ '''
51
+ answer = self.tokenizer(answer, padding='longest', return_tensors="pt").to(image.device)
52
+ answer.input_ids[:,0] = self.tokenizer.bos_token_id
53
+ answer_targets = answer.input_ids.masked_fill(answer.input_ids == self.tokenizer.pad_token_id, -100)
54
+
55
+ question_output = self.text_encoder(question.input_ids,
56
+ attention_mask = question.attention_mask,
57
+ encoder_hidden_states = image_embeds,
58
+ encoder_attention_mask = image_atts,
59
+ return_dict = True)
60
+
61
+ question_states = []
62
+ question_atts = []
63
+ for b, n in enumerate(n):
64
+ question_states += [question_output.last_hidden_state[b]]*n
65
+ question_atts += [question.attention_mask[b]]*n
66
+ question_states = torch.stack(question_states,0)
67
+ question_atts = torch.stack(question_atts,0)
68
+
69
+ answer_output = self.text_decoder(answer.input_ids,
70
+ attention_mask = answer.attention_mask,
71
+ encoder_hidden_states = question_states,
72
+ encoder_attention_mask = question_atts,
73
+ labels = answer_targets,
74
+ return_dict = True,
75
+ reduction = 'none',
76
+ )
77
+
78
+ loss = weights * answer_output.loss
79
+ loss = loss.sum()/image.size(0)
80
+
81
+ return loss
82
+
83
+
84
+ else:
85
+ question_output = self.text_encoder(question.input_ids,
86
+ attention_mask = question.attention_mask,
87
+ encoder_hidden_states = image_embeds,
88
+ encoder_attention_mask = image_atts,
89
+ return_dict = True)
90
+
91
+ if inference=='generate':
92
+ num_beams = 3
93
+ question_states = question_output.last_hidden_state.repeat_interleave(num_beams,dim=0)
94
+ question_atts = torch.ones(question_states.size()[:-1],dtype=torch.long).to(question_states.device)
95
+ model_kwargs = {"encoder_hidden_states": question_states, "encoder_attention_mask":question_atts}
96
+
97
+ bos_ids = torch.full((image.size(0),1),fill_value=self.tokenizer.bos_token_id,device=image.device)
98
+
99
+ outputs = self.text_decoder.generate(input_ids=bos_ids,
100
+ max_length=10,
101
+ min_length=1,
102
+ num_beams=num_beams,
103
+ eos_token_id=self.tokenizer.sep_token_id,
104
+ pad_token_id=self.tokenizer.pad_token_id,
105
+ **model_kwargs)
106
+
107
+ answers = []
108
+ for output in outputs:
109
+ answer = self.tokenizer.decode(output, skip_special_tokens=True)
110
+ answers.append(answer)
111
+ return answers
112
+
113
+ elif inference=='rank':
114
+ max_ids = self.rank_answer(question_output.last_hidden_state, question.attention_mask,
115
+ answer.input_ids, answer.attention_mask, k_test)
116
+ return max_ids
117
+
118
+
119
+
120
+ def rank_answer(self, question_states, question_atts, answer_ids, answer_atts, k):
121
+
122
+ num_ques = question_states.size(0)
123
+ start_ids = answer_ids[0,0].repeat(num_ques,1) # bos token
124
+
125
+ start_output = self.text_decoder(start_ids,
126
+ encoder_hidden_states = question_states,
127
+ encoder_attention_mask = question_atts,
128
+ return_dict = True,
129
+ reduction = 'none')
130
+ logits = start_output.logits[:,0,:] # first token's logit
131
+
132
+ # topk_probs: top-k probability
133
+ # topk_ids: [num_question, k]
134
+ answer_first_token = answer_ids[:,1]
135
+ prob_first_token = F.softmax(logits,dim=1).index_select(dim=1, index=answer_first_token)
136
+ topk_probs, topk_ids = prob_first_token.topk(k,dim=1)
137
+
138
+ # answer input: [num_question*k, answer_len]
139
+ input_ids = []
140
+ input_atts = []
141
+ for b, topk_id in enumerate(topk_ids):
142
+ input_ids.append(answer_ids.index_select(dim=0, index=topk_id))
143
+ input_atts.append(answer_atts.index_select(dim=0, index=topk_id))
144
+ input_ids = torch.cat(input_ids,dim=0)
145
+ input_atts = torch.cat(input_atts,dim=0)
146
+
147
+ targets_ids = input_ids.masked_fill(input_ids == self.tokenizer.pad_token_id, -100)
148
+
149
+ # repeat encoder's output for top-k answers
150
+ question_states = tile(question_states, 0, k)
151
+ question_atts = tile(question_atts, 0, k)
152
+
153
+ output = self.text_decoder(input_ids,
154
+ attention_mask = input_atts,
155
+ encoder_hidden_states = question_states,
156
+ encoder_attention_mask = question_atts,
157
+ labels = targets_ids,
158
+ return_dict = True,
159
+ reduction = 'none')
160
+
161
+ log_probs_sum = -output.loss
162
+ log_probs_sum = log_probs_sum.view(num_ques,k)
163
+
164
+ max_topk_ids = log_probs_sum.argmax(dim=1)
165
+ max_ids = topk_ids[max_topk_ids>=0,max_topk_ids]
166
+
167
+ return max_ids
168
+
169
+
170
+ def blip_vqa(pretrained='',**kwargs):
171
+ model = BLIP_VQA(**kwargs)
172
+ if pretrained:
173
+ model,msg = load_checkpoint(model,pretrained)
174
+ # assert(len(msg.missing_keys)==0)
175
+ return model
176
+
177
+
178
+ def tile(x, dim, n_tile):
179
+ init_dim = x.size(dim)
180
+ repeat_idx = [1] * x.dim()
181
+ repeat_idx[dim] = n_tile
182
+ x = x.repeat(*(repeat_idx))
183
+ order_index = torch.LongTensor(np.concatenate([init_dim * np.arange(n_tile) + i for i in range(init_dim)]))
184
+ return torch.index_select(x, dim, order_index.to(x.device))
185
+
186
+
extras/BLIP/models/med.py ADDED
@@ -0,0 +1,955 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ * Copyright (c) 2022, salesforce.com, inc.
3
+ * All rights reserved.
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6
+ * By Junnan Li
7
+ * Based on huggingface code base
8
+ * https://github.com/huggingface/transformers/blob/v4.15.0/src/transformers/models/bert
9
+ '''
10
+
11
+ import math
12
+ import os
13
+ import warnings
14
+ from dataclasses import dataclass
15
+ from typing import Optional, Tuple
16
+
17
+ import torch
18
+ from torch import Tensor, device, dtype, nn
19
+ import torch.utils.checkpoint
20
+ from torch import nn
21
+ from torch.nn import CrossEntropyLoss
22
+ import torch.nn.functional as F
23
+
24
+ from transformers.activations import ACT2FN
25
+ from transformers.file_utils import (
26
+ ModelOutput,
27
+ )
28
+ from transformers.modeling_outputs import (
29
+ BaseModelOutputWithPastAndCrossAttentions,
30
+ BaseModelOutputWithPoolingAndCrossAttentions,
31
+ CausalLMOutputWithCrossAttentions,
32
+ MaskedLMOutput,
33
+ MultipleChoiceModelOutput,
34
+ NextSentencePredictorOutput,
35
+ QuestionAnsweringModelOutput,
36
+ SequenceClassifierOutput,
37
+ TokenClassifierOutput,
38
+ )
39
+ from transformers.modeling_utils import (
40
+ PreTrainedModel,
41
+ apply_chunking_to_forward,
42
+ find_pruneable_heads_and_indices,
43
+ prune_linear_layer,
44
+ )
45
+ from transformers.utils import logging
46
+ from transformers.models.bert.configuration_bert import BertConfig
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+
52
+ class BertEmbeddings(nn.Module):
53
+ """Construct the embeddings from word and position embeddings."""
54
+
55
+ def __init__(self, config):
56
+ super().__init__()
57
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
58
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
59
+
60
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
61
+ # any TensorFlow checkpoint file
62
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
63
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
64
+
65
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
66
+ self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
67
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
68
+
69
+ self.config = config
70
+
71
+ def forward(
72
+ self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
73
+ ):
74
+ if input_ids is not None:
75
+ input_shape = input_ids.size()
76
+ else:
77
+ input_shape = inputs_embeds.size()[:-1]
78
+
79
+ seq_length = input_shape[1]
80
+
81
+ if position_ids is None:
82
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
83
+
84
+ if inputs_embeds is None:
85
+ inputs_embeds = self.word_embeddings(input_ids)
86
+
87
+ embeddings = inputs_embeds
88
+
89
+ if self.position_embedding_type == "absolute":
90
+ position_embeddings = self.position_embeddings(position_ids)
91
+ embeddings += position_embeddings
92
+ embeddings = self.LayerNorm(embeddings)
93
+ embeddings = self.dropout(embeddings)
94
+ return embeddings
95
+
96
+
97
+ class BertSelfAttention(nn.Module):
98
+ def __init__(self, config, is_cross_attention):
99
+ super().__init__()
100
+ self.config = config
101
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
102
+ raise ValueError(
103
+ "The hidden size (%d) is not a multiple of the number of attention "
104
+ "heads (%d)" % (config.hidden_size, config.num_attention_heads)
105
+ )
106
+
107
+ self.num_attention_heads = config.num_attention_heads
108
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
109
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
110
+
111
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
112
+ if is_cross_attention:
113
+ self.key = nn.Linear(config.encoder_width, self.all_head_size)
114
+ self.value = nn.Linear(config.encoder_width, self.all_head_size)
115
+ else:
116
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
117
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
118
+
119
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
120
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
121
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
122
+ self.max_position_embeddings = config.max_position_embeddings
123
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
124
+ self.save_attention = False
125
+
126
+ def save_attn_gradients(self, attn_gradients):
127
+ self.attn_gradients = attn_gradients
128
+
129
+ def get_attn_gradients(self):
130
+ return self.attn_gradients
131
+
132
+ def save_attention_map(self, attention_map):
133
+ self.attention_map = attention_map
134
+
135
+ def get_attention_map(self):
136
+ return self.attention_map
137
+
138
+ def transpose_for_scores(self, x):
139
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
140
+ x = x.view(*new_x_shape)
141
+ return x.permute(0, 2, 1, 3)
142
+
143
+ def forward(
144
+ self,
145
+ hidden_states,
146
+ attention_mask=None,
147
+ head_mask=None,
148
+ encoder_hidden_states=None,
149
+ encoder_attention_mask=None,
150
+ past_key_value=None,
151
+ output_attentions=False,
152
+ ):
153
+ mixed_query_layer = self.query(hidden_states)
154
+
155
+ # If this is instantiated as a cross-attention module, the keys
156
+ # and values come from an encoder; the attention mask needs to be
157
+ # such that the encoder's padding tokens are not attended to.
158
+ is_cross_attention = encoder_hidden_states is not None
159
+
160
+ if is_cross_attention:
161
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
162
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
163
+ attention_mask = encoder_attention_mask
164
+ elif past_key_value is not None:
165
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
166
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
167
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
168
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
169
+ else:
170
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
171
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
172
+
173
+ query_layer = self.transpose_for_scores(mixed_query_layer)
174
+
175
+ past_key_value = (key_layer, value_layer)
176
+
177
+ # Take the dot product between "query" and "key" to get the raw attention scores.
178
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
179
+
180
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
181
+ seq_length = hidden_states.size()[1]
182
+ position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
183
+ position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
184
+ distance = position_ids_l - position_ids_r
185
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
186
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
187
+
188
+ if self.position_embedding_type == "relative_key":
189
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
190
+ attention_scores = attention_scores + relative_position_scores
191
+ elif self.position_embedding_type == "relative_key_query":
192
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
193
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
194
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
195
+
196
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
197
+ if attention_mask is not None:
198
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
199
+ attention_scores = attention_scores + attention_mask
200
+
201
+ # Normalize the attention scores to probabilities.
202
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
203
+
204
+ if is_cross_attention and self.save_attention:
205
+ self.save_attention_map(attention_probs)
206
+ attention_probs.register_hook(self.save_attn_gradients)
207
+
208
+ # This is actually dropping out entire tokens to attend to, which might
209
+ # seem a bit unusual, but is taken from the original Transformer paper.
210
+ attention_probs_dropped = self.dropout(attention_probs)
211
+
212
+ # Mask heads if we want to
213
+ if head_mask is not None:
214
+ attention_probs_dropped = attention_probs_dropped * head_mask
215
+
216
+ context_layer = torch.matmul(attention_probs_dropped, value_layer)
217
+
218
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
219
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
220
+ context_layer = context_layer.view(*new_context_layer_shape)
221
+
222
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
223
+
224
+ outputs = outputs + (past_key_value,)
225
+ return outputs
226
+
227
+
228
+ class BertSelfOutput(nn.Module):
229
+ def __init__(self, config):
230
+ super().__init__()
231
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
232
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
233
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
234
+
235
+ def forward(self, hidden_states, input_tensor):
236
+ hidden_states = self.dense(hidden_states)
237
+ hidden_states = self.dropout(hidden_states)
238
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
239
+ return hidden_states
240
+
241
+
242
+ class BertAttention(nn.Module):
243
+ def __init__(self, config, is_cross_attention=False):
244
+ super().__init__()
245
+ self.self = BertSelfAttention(config, is_cross_attention)
246
+ self.output = BertSelfOutput(config)
247
+ self.pruned_heads = set()
248
+
249
+ def prune_heads(self, heads):
250
+ if len(heads) == 0:
251
+ return
252
+ heads, index = find_pruneable_heads_and_indices(
253
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
254
+ )
255
+
256
+ # Prune linear layers
257
+ self.self.query = prune_linear_layer(self.self.query, index)
258
+ self.self.key = prune_linear_layer(self.self.key, index)
259
+ self.self.value = prune_linear_layer(self.self.value, index)
260
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
261
+
262
+ # Update hyper params and store pruned heads
263
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
264
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
265
+ self.pruned_heads = self.pruned_heads.union(heads)
266
+
267
+ def forward(
268
+ self,
269
+ hidden_states,
270
+ attention_mask=None,
271
+ head_mask=None,
272
+ encoder_hidden_states=None,
273
+ encoder_attention_mask=None,
274
+ past_key_value=None,
275
+ output_attentions=False,
276
+ ):
277
+ self_outputs = self.self(
278
+ hidden_states,
279
+ attention_mask,
280
+ head_mask,
281
+ encoder_hidden_states,
282
+ encoder_attention_mask,
283
+ past_key_value,
284
+ output_attentions,
285
+ )
286
+ attention_output = self.output(self_outputs[0], hidden_states)
287
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
288
+ return outputs
289
+
290
+
291
+ class BertIntermediate(nn.Module):
292
+ def __init__(self, config):
293
+ super().__init__()
294
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
295
+ if isinstance(config.hidden_act, str):
296
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
297
+ else:
298
+ self.intermediate_act_fn = config.hidden_act
299
+
300
+ def forward(self, hidden_states):
301
+ hidden_states = self.dense(hidden_states)
302
+ hidden_states = self.intermediate_act_fn(hidden_states)
303
+ return hidden_states
304
+
305
+
306
+ class BertOutput(nn.Module):
307
+ def __init__(self, config):
308
+ super().__init__()
309
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
310
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
311
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
312
+
313
+ def forward(self, hidden_states, input_tensor):
314
+ hidden_states = self.dense(hidden_states)
315
+ hidden_states = self.dropout(hidden_states)
316
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
317
+ return hidden_states
318
+
319
+
320
+ class BertLayer(nn.Module):
321
+ def __init__(self, config, layer_num):
322
+ super().__init__()
323
+ self.config = config
324
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
325
+ self.seq_len_dim = 1
326
+ self.attention = BertAttention(config)
327
+ self.layer_num = layer_num
328
+ if self.config.add_cross_attention:
329
+ self.crossattention = BertAttention(config, is_cross_attention=self.config.add_cross_attention)
330
+ self.intermediate = BertIntermediate(config)
331
+ self.output = BertOutput(config)
332
+
333
+ def forward(
334
+ self,
335
+ hidden_states,
336
+ attention_mask=None,
337
+ head_mask=None,
338
+ encoder_hidden_states=None,
339
+ encoder_attention_mask=None,
340
+ past_key_value=None,
341
+ output_attentions=False,
342
+ mode=None,
343
+ ):
344
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
345
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
346
+ self_attention_outputs = self.attention(
347
+ hidden_states,
348
+ attention_mask,
349
+ head_mask,
350
+ output_attentions=output_attentions,
351
+ past_key_value=self_attn_past_key_value,
352
+ )
353
+ attention_output = self_attention_outputs[0]
354
+
355
+ outputs = self_attention_outputs[1:-1]
356
+ present_key_value = self_attention_outputs[-1]
357
+
358
+ if mode=='multimodal':
359
+ assert encoder_hidden_states is not None, "encoder_hidden_states must be given for cross-attention layers"
360
+
361
+ cross_attention_outputs = self.crossattention(
362
+ attention_output,
363
+ attention_mask,
364
+ head_mask,
365
+ encoder_hidden_states,
366
+ encoder_attention_mask,
367
+ output_attentions=output_attentions,
368
+ )
369
+ attention_output = cross_attention_outputs[0]
370
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
371
+ layer_output = apply_chunking_to_forward(
372
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
373
+ )
374
+ outputs = (layer_output,) + outputs
375
+
376
+ outputs = outputs + (present_key_value,)
377
+
378
+ return outputs
379
+
380
+ def feed_forward_chunk(self, attention_output):
381
+ intermediate_output = self.intermediate(attention_output)
382
+ layer_output = self.output(intermediate_output, attention_output)
383
+ return layer_output
384
+
385
+
386
+ class BertEncoder(nn.Module):
387
+ def __init__(self, config):
388
+ super().__init__()
389
+ self.config = config
390
+ self.layer = nn.ModuleList([BertLayer(config,i) for i in range(config.num_hidden_layers)])
391
+ self.gradient_checkpointing = False
392
+
393
+ def forward(
394
+ self,
395
+ hidden_states,
396
+ attention_mask=None,
397
+ head_mask=None,
398
+ encoder_hidden_states=None,
399
+ encoder_attention_mask=None,
400
+ past_key_values=None,
401
+ use_cache=None,
402
+ output_attentions=False,
403
+ output_hidden_states=False,
404
+ return_dict=True,
405
+ mode='multimodal',
406
+ ):
407
+ all_hidden_states = () if output_hidden_states else None
408
+ all_self_attentions = () if output_attentions else None
409
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
410
+
411
+ next_decoder_cache = () if use_cache else None
412
+
413
+ for i in range(self.config.num_hidden_layers):
414
+ layer_module = self.layer[i]
415
+ if output_hidden_states:
416
+ all_hidden_states = all_hidden_states + (hidden_states,)
417
+
418
+ layer_head_mask = head_mask[i] if head_mask is not None else None
419
+ past_key_value = past_key_values[i] if past_key_values is not None else None
420
+
421
+ if self.gradient_checkpointing and self.training:
422
+
423
+ if use_cache:
424
+ logger.warn(
425
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
426
+ )
427
+ use_cache = False
428
+
429
+ def create_custom_forward(module):
430
+ def custom_forward(*inputs):
431
+ return module(*inputs, past_key_value, output_attentions)
432
+
433
+ return custom_forward
434
+
435
+ layer_outputs = torch.utils.checkpoint.checkpoint(
436
+ create_custom_forward(layer_module),
437
+ hidden_states,
438
+ attention_mask,
439
+ layer_head_mask,
440
+ encoder_hidden_states,
441
+ encoder_attention_mask,
442
+ mode=mode,
443
+ )
444
+ else:
445
+ layer_outputs = layer_module(
446
+ hidden_states,
447
+ attention_mask,
448
+ layer_head_mask,
449
+ encoder_hidden_states,
450
+ encoder_attention_mask,
451
+ past_key_value,
452
+ output_attentions,
453
+ mode=mode,
454
+ )
455
+
456
+ hidden_states = layer_outputs[0]
457
+ if use_cache:
458
+ next_decoder_cache += (layer_outputs[-1],)
459
+ if output_attentions:
460
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
461
+
462
+ if output_hidden_states:
463
+ all_hidden_states = all_hidden_states + (hidden_states,)
464
+
465
+ if not return_dict:
466
+ return tuple(
467
+ v
468
+ for v in [
469
+ hidden_states,
470
+ next_decoder_cache,
471
+ all_hidden_states,
472
+ all_self_attentions,
473
+ all_cross_attentions,
474
+ ]
475
+ if v is not None
476
+ )
477
+ return BaseModelOutputWithPastAndCrossAttentions(
478
+ last_hidden_state=hidden_states,
479
+ past_key_values=next_decoder_cache,
480
+ hidden_states=all_hidden_states,
481
+ attentions=all_self_attentions,
482
+ cross_attentions=all_cross_attentions,
483
+ )
484
+
485
+
486
+ class BertPooler(nn.Module):
487
+ def __init__(self, config):
488
+ super().__init__()
489
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
490
+ self.activation = nn.Tanh()
491
+
492
+ def forward(self, hidden_states):
493
+ # We "pool" the model by simply taking the hidden state corresponding
494
+ # to the first token.
495
+ first_token_tensor = hidden_states[:, 0]
496
+ pooled_output = self.dense(first_token_tensor)
497
+ pooled_output = self.activation(pooled_output)
498
+ return pooled_output
499
+
500
+
501
+ class BertPredictionHeadTransform(nn.Module):
502
+ def __init__(self, config):
503
+ super().__init__()
504
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
505
+ if isinstance(config.hidden_act, str):
506
+ self.transform_act_fn = ACT2FN[config.hidden_act]
507
+ else:
508
+ self.transform_act_fn = config.hidden_act
509
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
510
+
511
+ def forward(self, hidden_states):
512
+ hidden_states = self.dense(hidden_states)
513
+ hidden_states = self.transform_act_fn(hidden_states)
514
+ hidden_states = self.LayerNorm(hidden_states)
515
+ return hidden_states
516
+
517
+
518
+ class BertLMPredictionHead(nn.Module):
519
+ def __init__(self, config):
520
+ super().__init__()
521
+ self.transform = BertPredictionHeadTransform(config)
522
+
523
+ # The output weights are the same as the input embeddings, but there is
524
+ # an output-only bias for each token.
525
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
526
+
527
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
528
+
529
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
530
+ self.decoder.bias = self.bias
531
+
532
+ def forward(self, hidden_states):
533
+ hidden_states = self.transform(hidden_states)
534
+ hidden_states = self.decoder(hidden_states)
535
+ return hidden_states
536
+
537
+
538
+ class BertOnlyMLMHead(nn.Module):
539
+ def __init__(self, config):
540
+ super().__init__()
541
+ self.predictions = BertLMPredictionHead(config)
542
+
543
+ def forward(self, sequence_output):
544
+ prediction_scores = self.predictions(sequence_output)
545
+ return prediction_scores
546
+
547
+
548
+ class BertPreTrainedModel(PreTrainedModel):
549
+ """
550
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
551
+ models.
552
+ """
553
+
554
+ config_class = BertConfig
555
+ base_model_prefix = "bert"
556
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
557
+
558
+ def _init_weights(self, module):
559
+ """ Initialize the weights """
560
+ if isinstance(module, (nn.Linear, nn.Embedding)):
561
+ # Slightly different from the TF version which uses truncated_normal for initialization
562
+ # cf https://github.com/pytorch/pytorch/pull/5617
563
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
564
+ elif isinstance(module, nn.LayerNorm):
565
+ module.bias.data.zero_()
566
+ module.weight.data.fill_(1.0)
567
+ if isinstance(module, nn.Linear) and module.bias is not None:
568
+ module.bias.data.zero_()
569
+
570
+
571
+ class BertModel(BertPreTrainedModel):
572
+ """
573
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
574
+ cross-attention is added between the self-attention layers, following the architecture described in `Attention is
575
+ all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
576
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
577
+ argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
578
+ input to the forward pass.
579
+ """
580
+
581
+ def __init__(self, config, add_pooling_layer=True):
582
+ super().__init__(config)
583
+ self.config = config
584
+
585
+ self.embeddings = BertEmbeddings(config)
586
+
587
+ self.encoder = BertEncoder(config)
588
+
589
+ self.pooler = BertPooler(config) if add_pooling_layer else None
590
+
591
+ self.init_weights()
592
+
593
+
594
+ def get_input_embeddings(self):
595
+ return self.embeddings.word_embeddings
596
+
597
+ def set_input_embeddings(self, value):
598
+ self.embeddings.word_embeddings = value
599
+
600
+ def _prune_heads(self, heads_to_prune):
601
+ """
602
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
603
+ class PreTrainedModel
604
+ """
605
+ for layer, heads in heads_to_prune.items():
606
+ self.encoder.layer[layer].attention.prune_heads(heads)
607
+
608
+
609
+ def get_extended_attention_mask(self, attention_mask: Tensor, input_shape: Tuple[int], device: device, is_decoder: bool) -> Tensor:
610
+ """
611
+ Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
612
+
613
+ Arguments:
614
+ attention_mask (:obj:`torch.Tensor`):
615
+ Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
616
+ input_shape (:obj:`Tuple[int]`):
617
+ The shape of the input to the model.
618
+ device: (:obj:`torch.device`):
619
+ The device of the input to the model.
620
+
621
+ Returns:
622
+ :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`.
623
+ """
624
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
625
+ # ourselves in which case we just need to make it broadcastable to all heads.
626
+ if attention_mask.dim() == 3:
627
+ extended_attention_mask = attention_mask[:, None, :, :]
628
+ elif attention_mask.dim() == 2:
629
+ # Provided a padding mask of dimensions [batch_size, seq_length]
630
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
631
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
632
+ if is_decoder:
633
+ batch_size, seq_length = input_shape
634
+
635
+ seq_ids = torch.arange(seq_length, device=device)
636
+ causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None]
637
+ # in case past_key_values are used we need to add a prefix ones mask to the causal mask
638
+ # causal and attention masks must have same type with pytorch version < 1.3
639
+ causal_mask = causal_mask.to(attention_mask.dtype)
640
+
641
+ if causal_mask.shape[1] < attention_mask.shape[1]:
642
+ prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
643
+ causal_mask = torch.cat(
644
+ [
645
+ torch.ones((batch_size, seq_length, prefix_seq_len), device=device, dtype=causal_mask.dtype),
646
+ causal_mask,
647
+ ],
648
+ axis=-1,
649
+ )
650
+
651
+ extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
652
+ else:
653
+ extended_attention_mask = attention_mask[:, None, None, :]
654
+ else:
655
+ raise ValueError(
656
+ "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
657
+ input_shape, attention_mask.shape
658
+ )
659
+ )
660
+
661
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
662
+ # masked positions, this operation will create a tensor which is 0.0 for
663
+ # positions we want to attend and -10000.0 for masked positions.
664
+ # Since we are adding it to the raw scores before the softmax, this is
665
+ # effectively the same as removing these entirely.
666
+ extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
667
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
668
+ return extended_attention_mask
669
+
670
+ def forward(
671
+ self,
672
+ input_ids=None,
673
+ attention_mask=None,
674
+ position_ids=None,
675
+ head_mask=None,
676
+ inputs_embeds=None,
677
+ encoder_embeds=None,
678
+ encoder_hidden_states=None,
679
+ encoder_attention_mask=None,
680
+ past_key_values=None,
681
+ use_cache=None,
682
+ output_attentions=None,
683
+ output_hidden_states=None,
684
+ return_dict=None,
685
+ is_decoder=False,
686
+ mode='multimodal',
687
+ ):
688
+ r"""
689
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
690
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
691
+ the model is configured as a decoder.
692
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
693
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
694
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
695
+ - 1 for tokens that are **not masked**,
696
+ - 0 for tokens that are **masked**.
697
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
698
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
699
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
700
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
701
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
702
+ use_cache (:obj:`bool`, `optional`):
703
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
704
+ decoding (see :obj:`past_key_values`).
705
+ """
706
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
707
+ output_hidden_states = (
708
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
709
+ )
710
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
711
+
712
+ if is_decoder:
713
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
714
+ else:
715
+ use_cache = False
716
+
717
+ if input_ids is not None and inputs_embeds is not None:
718
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
719
+ elif input_ids is not None:
720
+ input_shape = input_ids.size()
721
+ batch_size, seq_length = input_shape
722
+ device = input_ids.device
723
+ elif inputs_embeds is not None:
724
+ input_shape = inputs_embeds.size()[:-1]
725
+ batch_size, seq_length = input_shape
726
+ device = inputs_embeds.device
727
+ elif encoder_embeds is not None:
728
+ input_shape = encoder_embeds.size()[:-1]
729
+ batch_size, seq_length = input_shape
730
+ device = encoder_embeds.device
731
+ else:
732
+ raise ValueError("You have to specify either input_ids or inputs_embeds or encoder_embeds")
733
+
734
+ # past_key_values_length
735
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
736
+
737
+ if attention_mask is None:
738
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
739
+
740
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
741
+ # ourselves in which case we just need to make it broadcastable to all heads.
742
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape,
743
+ device, is_decoder)
744
+
745
+ # If a 2D or 3D attention mask is provided for the cross-attention
746
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
747
+ if encoder_hidden_states is not None:
748
+ if type(encoder_hidden_states) == list:
749
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size()
750
+ else:
751
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
752
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
753
+
754
+ if type(encoder_attention_mask) == list:
755
+ encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask]
756
+ elif encoder_attention_mask is None:
757
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
758
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
759
+ else:
760
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
761
+ else:
762
+ encoder_extended_attention_mask = None
763
+
764
+ # Prepare head mask if needed
765
+ # 1.0 in head_mask indicate we keep the head
766
+ # attention_probs has shape bsz x n_heads x N x N
767
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
768
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
769
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
770
+
771
+ if encoder_embeds is None:
772
+ embedding_output = self.embeddings(
773
+ input_ids=input_ids,
774
+ position_ids=position_ids,
775
+ inputs_embeds=inputs_embeds,
776
+ past_key_values_length=past_key_values_length,
777
+ )
778
+ else:
779
+ embedding_output = encoder_embeds
780
+
781
+ encoder_outputs = self.encoder(
782
+ embedding_output,
783
+ attention_mask=extended_attention_mask,
784
+ head_mask=head_mask,
785
+ encoder_hidden_states=encoder_hidden_states,
786
+ encoder_attention_mask=encoder_extended_attention_mask,
787
+ past_key_values=past_key_values,
788
+ use_cache=use_cache,
789
+ output_attentions=output_attentions,
790
+ output_hidden_states=output_hidden_states,
791
+ return_dict=return_dict,
792
+ mode=mode,
793
+ )
794
+ sequence_output = encoder_outputs[0]
795
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
796
+
797
+ if not return_dict:
798
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
799
+
800
+ return BaseModelOutputWithPoolingAndCrossAttentions(
801
+ last_hidden_state=sequence_output,
802
+ pooler_output=pooled_output,
803
+ past_key_values=encoder_outputs.past_key_values,
804
+ hidden_states=encoder_outputs.hidden_states,
805
+ attentions=encoder_outputs.attentions,
806
+ cross_attentions=encoder_outputs.cross_attentions,
807
+ )
808
+
809
+
810
+
811
+ class BertLMHeadModel(BertPreTrainedModel):
812
+
813
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
814
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
815
+
816
+ def __init__(self, config):
817
+ super().__init__(config)
818
+
819
+ self.bert = BertModel(config, add_pooling_layer=False)
820
+ self.cls = BertOnlyMLMHead(config)
821
+
822
+ self.init_weights()
823
+
824
+ def get_output_embeddings(self):
825
+ return self.cls.predictions.decoder
826
+
827
+ def set_output_embeddings(self, new_embeddings):
828
+ self.cls.predictions.decoder = new_embeddings
829
+
830
+ def forward(
831
+ self,
832
+ input_ids=None,
833
+ attention_mask=None,
834
+ position_ids=None,
835
+ head_mask=None,
836
+ inputs_embeds=None,
837
+ encoder_hidden_states=None,
838
+ encoder_attention_mask=None,
839
+ labels=None,
840
+ past_key_values=None,
841
+ use_cache=None,
842
+ output_attentions=None,
843
+ output_hidden_states=None,
844
+ return_dict=None,
845
+ return_logits=False,
846
+ is_decoder=True,
847
+ reduction='mean',
848
+ mode='multimodal',
849
+ ):
850
+ r"""
851
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
852
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
853
+ the model is configured as a decoder.
854
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
855
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
856
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
857
+ - 1 for tokens that are **not masked**,
858
+ - 0 for tokens that are **masked**.
859
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
860
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
861
+ ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are
862
+ ignored (masked), the loss is only computed for the tokens with labels n ``[0, ..., config.vocab_size]``
863
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
864
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
865
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
866
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
867
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
868
+ use_cache (:obj:`bool`, `optional`):
869
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
870
+ decoding (see :obj:`past_key_values`).
871
+ Returns:
872
+ Example::
873
+ >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig
874
+ >>> import torch
875
+ >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
876
+ >>> config = BertConfig.from_pretrained("bert-base-cased")
877
+ >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config)
878
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
879
+ >>> outputs = model(**inputs)
880
+ >>> prediction_logits = outputs.logits
881
+ """
882
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
883
+ if labels is not None:
884
+ use_cache = False
885
+
886
+ outputs = self.bert(
887
+ input_ids,
888
+ attention_mask=attention_mask,
889
+ position_ids=position_ids,
890
+ head_mask=head_mask,
891
+ inputs_embeds=inputs_embeds,
892
+ encoder_hidden_states=encoder_hidden_states,
893
+ encoder_attention_mask=encoder_attention_mask,
894
+ past_key_values=past_key_values,
895
+ use_cache=use_cache,
896
+ output_attentions=output_attentions,
897
+ output_hidden_states=output_hidden_states,
898
+ return_dict=return_dict,
899
+ is_decoder=is_decoder,
900
+ mode=mode,
901
+ )
902
+
903
+ sequence_output = outputs[0]
904
+ prediction_scores = self.cls(sequence_output)
905
+
906
+ if return_logits:
907
+ return prediction_scores[:, :-1, :].contiguous()
908
+
909
+ lm_loss = None
910
+ if labels is not None:
911
+ # we are doing next-token prediction; shift prediction scores and input ids by one
912
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
913
+ labels = labels[:, 1:].contiguous()
914
+ loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=0.1)
915
+ lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
916
+ if reduction=='none':
917
+ lm_loss = lm_loss.view(prediction_scores.size(0),-1).sum(1)
918
+
919
+ if not return_dict:
920
+ output = (prediction_scores,) + outputs[2:]
921
+ return ((lm_loss,) + output) if lm_loss is not None else output
922
+
923
+ return CausalLMOutputWithCrossAttentions(
924
+ loss=lm_loss,
925
+ logits=prediction_scores,
926
+ past_key_values=outputs.past_key_values,
927
+ hidden_states=outputs.hidden_states,
928
+ attentions=outputs.attentions,
929
+ cross_attentions=outputs.cross_attentions,
930
+ )
931
+
932
+ def prepare_inputs_for_generation(self, input_ids, past=None, attention_mask=None, **model_kwargs):
933
+ input_shape = input_ids.shape
934
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
935
+ if attention_mask is None:
936
+ attention_mask = input_ids.new_ones(input_shape)
937
+
938
+ # cut decoder_input_ids if past is used
939
+ if past is not None:
940
+ input_ids = input_ids[:, -1:]
941
+
942
+ return {
943
+ "input_ids": input_ids,
944
+ "attention_mask": attention_mask,
945
+ "past_key_values": past,
946
+ "encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None),
947
+ "encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None),
948
+ "is_decoder": True,
949
+ }
950
+
951
+ def _reorder_cache(self, past, beam_idx):
952
+ reordered_past = ()
953
+ for layer_past in past:
954
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
955
+ return reordered_past
extras/BLIP/models/nlvr_encoder.py ADDED
@@ -0,0 +1,843 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import warnings
4
+ from dataclasses import dataclass
5
+ from typing import Optional, Tuple
6
+
7
+ import torch
8
+ from torch import Tensor, device, dtype, nn
9
+ import torch.utils.checkpoint
10
+ from torch import nn
11
+ from torch.nn import CrossEntropyLoss
12
+ import torch.nn.functional as F
13
+
14
+ from transformers.activations import ACT2FN
15
+ from transformers.file_utils import (
16
+ ModelOutput,
17
+ )
18
+ from transformers.modeling_outputs import (
19
+ BaseModelOutputWithPastAndCrossAttentions,
20
+ BaseModelOutputWithPoolingAndCrossAttentions,
21
+ CausalLMOutputWithCrossAttentions,
22
+ MaskedLMOutput,
23
+ MultipleChoiceModelOutput,
24
+ NextSentencePredictorOutput,
25
+ QuestionAnsweringModelOutput,
26
+ SequenceClassifierOutput,
27
+ TokenClassifierOutput,
28
+ )
29
+ from transformers.modeling_utils import (
30
+ PreTrainedModel,
31
+ apply_chunking_to_forward,
32
+ find_pruneable_heads_and_indices,
33
+ prune_linear_layer,
34
+ )
35
+ from transformers.utils import logging
36
+ from transformers.models.bert.configuration_bert import BertConfig
37
+
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+
42
+ class BertEmbeddings(nn.Module):
43
+ """Construct the embeddings from word and position embeddings."""
44
+
45
+ def __init__(self, config):
46
+ super().__init__()
47
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
48
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
49
+
50
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
51
+ # any TensorFlow checkpoint file
52
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
53
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
54
+
55
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
56
+ self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
57
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
58
+
59
+ self.config = config
60
+
61
+ def forward(
62
+ self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
63
+ ):
64
+ if input_ids is not None:
65
+ input_shape = input_ids.size()
66
+ else:
67
+ input_shape = inputs_embeds.size()[:-1]
68
+
69
+ seq_length = input_shape[1]
70
+
71
+ if position_ids is None:
72
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
73
+
74
+ if inputs_embeds is None:
75
+ inputs_embeds = self.word_embeddings(input_ids)
76
+
77
+ embeddings = inputs_embeds
78
+
79
+ if self.position_embedding_type == "absolute":
80
+ position_embeddings = self.position_embeddings(position_ids)
81
+ embeddings += position_embeddings
82
+ embeddings = self.LayerNorm(embeddings)
83
+ embeddings = self.dropout(embeddings)
84
+ return embeddings
85
+
86
+
87
+ class BertSelfAttention(nn.Module):
88
+ def __init__(self, config, is_cross_attention):
89
+ super().__init__()
90
+ self.config = config
91
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
92
+ raise ValueError(
93
+ "The hidden size (%d) is not a multiple of the number of attention "
94
+ "heads (%d)" % (config.hidden_size, config.num_attention_heads)
95
+ )
96
+
97
+ self.num_attention_heads = config.num_attention_heads
98
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
99
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
100
+
101
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
102
+ if is_cross_attention:
103
+ self.key = nn.Linear(config.encoder_width, self.all_head_size)
104
+ self.value = nn.Linear(config.encoder_width, self.all_head_size)
105
+ else:
106
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
107
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
108
+
109
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
110
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
111
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
112
+ self.max_position_embeddings = config.max_position_embeddings
113
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
114
+ self.save_attention = False
115
+
116
+ def save_attn_gradients(self, attn_gradients):
117
+ self.attn_gradients = attn_gradients
118
+
119
+ def get_attn_gradients(self):
120
+ return self.attn_gradients
121
+
122
+ def save_attention_map(self, attention_map):
123
+ self.attention_map = attention_map
124
+
125
+ def get_attention_map(self):
126
+ return self.attention_map
127
+
128
+ def transpose_for_scores(self, x):
129
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
130
+ x = x.view(*new_x_shape)
131
+ return x.permute(0, 2, 1, 3)
132
+
133
+ def forward(
134
+ self,
135
+ hidden_states,
136
+ attention_mask=None,
137
+ head_mask=None,
138
+ encoder_hidden_states=None,
139
+ encoder_attention_mask=None,
140
+ past_key_value=None,
141
+ output_attentions=False,
142
+ ):
143
+ mixed_query_layer = self.query(hidden_states)
144
+
145
+ # If this is instantiated as a cross-attention module, the keys
146
+ # and values come from an encoder; the attention mask needs to be
147
+ # such that the encoder's padding tokens are not attended to.
148
+ is_cross_attention = encoder_hidden_states is not None
149
+
150
+ if is_cross_attention:
151
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
152
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
153
+ attention_mask = encoder_attention_mask
154
+ elif past_key_value is not None:
155
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
156
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
157
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
158
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
159
+ else:
160
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
161
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
162
+
163
+ query_layer = self.transpose_for_scores(mixed_query_layer)
164
+
165
+ past_key_value = (key_layer, value_layer)
166
+
167
+ # Take the dot product between "query" and "key" to get the raw attention scores.
168
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
169
+
170
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
171
+ seq_length = hidden_states.size()[1]
172
+ position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
173
+ position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
174
+ distance = position_ids_l - position_ids_r
175
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
176
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
177
+
178
+ if self.position_embedding_type == "relative_key":
179
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
180
+ attention_scores = attention_scores + relative_position_scores
181
+ elif self.position_embedding_type == "relative_key_query":
182
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
183
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
184
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
185
+
186
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
187
+ if attention_mask is not None:
188
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
189
+ attention_scores = attention_scores + attention_mask
190
+
191
+ # Normalize the attention scores to probabilities.
192
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
193
+
194
+ if is_cross_attention and self.save_attention:
195
+ self.save_attention_map(attention_probs)
196
+ attention_probs.register_hook(self.save_attn_gradients)
197
+
198
+ # This is actually dropping out entire tokens to attend to, which might
199
+ # seem a bit unusual, but is taken from the original Transformer paper.
200
+ attention_probs_dropped = self.dropout(attention_probs)
201
+
202
+ # Mask heads if we want to
203
+ if head_mask is not None:
204
+ attention_probs_dropped = attention_probs_dropped * head_mask
205
+
206
+ context_layer = torch.matmul(attention_probs_dropped, value_layer)
207
+
208
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
209
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
210
+ context_layer = context_layer.view(*new_context_layer_shape)
211
+
212
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
213
+
214
+ outputs = outputs + (past_key_value,)
215
+ return outputs
216
+
217
+
218
+ class BertSelfOutput(nn.Module):
219
+ def __init__(self, config, twin=False, merge=False):
220
+ super().__init__()
221
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
222
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
223
+ if twin:
224
+ self.dense0 = nn.Linear(config.hidden_size, config.hidden_size)
225
+ self.dense1 = nn.Linear(config.hidden_size, config.hidden_size)
226
+ else:
227
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
228
+ if merge:
229
+ self.act = ACT2FN[config.hidden_act]
230
+ self.merge_layer = nn.Linear(config.hidden_size * 2, config.hidden_size)
231
+ self.merge = True
232
+ else:
233
+ self.merge = False
234
+
235
+ def forward(self, hidden_states, input_tensor):
236
+ if type(hidden_states) == list:
237
+ hidden_states0 = self.dense0(hidden_states[0])
238
+ hidden_states1 = self.dense1(hidden_states[1])
239
+ if self.merge:
240
+ #hidden_states = self.merge_layer(self.act(torch.cat([hidden_states0,hidden_states1],dim=-1)))
241
+ hidden_states = self.merge_layer(torch.cat([hidden_states0,hidden_states1],dim=-1))
242
+ else:
243
+ hidden_states = (hidden_states0+hidden_states1)/2
244
+ else:
245
+ hidden_states = self.dense(hidden_states)
246
+ hidden_states = self.dropout(hidden_states)
247
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
248
+ return hidden_states
249
+
250
+
251
+ class BertAttention(nn.Module):
252
+ def __init__(self, config, is_cross_attention=False, layer_num=-1):
253
+ super().__init__()
254
+ if is_cross_attention:
255
+ self.self0 = BertSelfAttention(config, is_cross_attention)
256
+ self.self1 = BertSelfAttention(config, is_cross_attention)
257
+ else:
258
+ self.self = BertSelfAttention(config, is_cross_attention)
259
+ self.output = BertSelfOutput(config, twin=is_cross_attention, merge=(is_cross_attention and layer_num>=6))
260
+ self.pruned_heads = set()
261
+
262
+ def prune_heads(self, heads):
263
+ if len(heads) == 0:
264
+ return
265
+ heads, index = find_pruneable_heads_and_indices(
266
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
267
+ )
268
+
269
+ # Prune linear layers
270
+ self.self.query = prune_linear_layer(self.self.query, index)
271
+ self.self.key = prune_linear_layer(self.self.key, index)
272
+ self.self.value = prune_linear_layer(self.self.value, index)
273
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
274
+
275
+ # Update hyper params and store pruned heads
276
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
277
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
278
+ self.pruned_heads = self.pruned_heads.union(heads)
279
+
280
+ def forward(
281
+ self,
282
+ hidden_states,
283
+ attention_mask=None,
284
+ head_mask=None,
285
+ encoder_hidden_states=None,
286
+ encoder_attention_mask=None,
287
+ past_key_value=None,
288
+ output_attentions=False,
289
+ ):
290
+ if type(encoder_hidden_states)==list:
291
+ self_outputs0 = self.self0(
292
+ hidden_states,
293
+ attention_mask,
294
+ head_mask,
295
+ encoder_hidden_states[0],
296
+ encoder_attention_mask[0],
297
+ past_key_value,
298
+ output_attentions,
299
+ )
300
+ self_outputs1 = self.self1(
301
+ hidden_states,
302
+ attention_mask,
303
+ head_mask,
304
+ encoder_hidden_states[1],
305
+ encoder_attention_mask[1],
306
+ past_key_value,
307
+ output_attentions,
308
+ )
309
+ attention_output = self.output([self_outputs0[0],self_outputs1[0]], hidden_states)
310
+
311
+ outputs = (attention_output,) + self_outputs0[1:] # add attentions if we output them
312
+ else:
313
+ self_outputs = self.self(
314
+ hidden_states,
315
+ attention_mask,
316
+ head_mask,
317
+ encoder_hidden_states,
318
+ encoder_attention_mask,
319
+ past_key_value,
320
+ output_attentions,
321
+ )
322
+ attention_output = self.output(self_outputs[0], hidden_states)
323
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
324
+ return outputs
325
+
326
+
327
+ class BertIntermediate(nn.Module):
328
+ def __init__(self, config):
329
+ super().__init__()
330
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
331
+ if isinstance(config.hidden_act, str):
332
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
333
+ else:
334
+ self.intermediate_act_fn = config.hidden_act
335
+
336
+ def forward(self, hidden_states):
337
+ hidden_states = self.dense(hidden_states)
338
+ hidden_states = self.intermediate_act_fn(hidden_states)
339
+ return hidden_states
340
+
341
+
342
+ class BertOutput(nn.Module):
343
+ def __init__(self, config):
344
+ super().__init__()
345
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
346
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
347
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
348
+
349
+ def forward(self, hidden_states, input_tensor):
350
+ hidden_states = self.dense(hidden_states)
351
+ hidden_states = self.dropout(hidden_states)
352
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
353
+ return hidden_states
354
+
355
+
356
+ class BertLayer(nn.Module):
357
+ def __init__(self, config, layer_num):
358
+ super().__init__()
359
+ self.config = config
360
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
361
+ self.seq_len_dim = 1
362
+ self.attention = BertAttention(config)
363
+ self.layer_num = layer_num
364
+ if self.config.add_cross_attention:
365
+ self.crossattention = BertAttention(config, is_cross_attention=self.config.add_cross_attention, layer_num=layer_num)
366
+ self.intermediate = BertIntermediate(config)
367
+ self.output = BertOutput(config)
368
+
369
+ def forward(
370
+ self,
371
+ hidden_states,
372
+ attention_mask=None,
373
+ head_mask=None,
374
+ encoder_hidden_states=None,
375
+ encoder_attention_mask=None,
376
+ past_key_value=None,
377
+ output_attentions=False,
378
+ mode=None,
379
+ ):
380
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
381
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
382
+ self_attention_outputs = self.attention(
383
+ hidden_states,
384
+ attention_mask,
385
+ head_mask,
386
+ output_attentions=output_attentions,
387
+ past_key_value=self_attn_past_key_value,
388
+ )
389
+ attention_output = self_attention_outputs[0]
390
+
391
+ outputs = self_attention_outputs[1:-1]
392
+ present_key_value = self_attention_outputs[-1]
393
+
394
+ if mode=='multimodal':
395
+ assert encoder_hidden_states is not None, "encoder_hidden_states must be given for cross-attention layers"
396
+ cross_attention_outputs = self.crossattention(
397
+ attention_output,
398
+ attention_mask,
399
+ head_mask,
400
+ encoder_hidden_states,
401
+ encoder_attention_mask,
402
+ output_attentions=output_attentions,
403
+ )
404
+ attention_output = cross_attention_outputs[0]
405
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
406
+ layer_output = apply_chunking_to_forward(
407
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
408
+ )
409
+ outputs = (layer_output,) + outputs
410
+
411
+ outputs = outputs + (present_key_value,)
412
+
413
+ return outputs
414
+
415
+ def feed_forward_chunk(self, attention_output):
416
+ intermediate_output = self.intermediate(attention_output)
417
+ layer_output = self.output(intermediate_output, attention_output)
418
+ return layer_output
419
+
420
+
421
+ class BertEncoder(nn.Module):
422
+ def __init__(self, config):
423
+ super().__init__()
424
+ self.config = config
425
+ self.layer = nn.ModuleList([BertLayer(config,i) for i in range(config.num_hidden_layers)])
426
+ self.gradient_checkpointing = False
427
+
428
+ def forward(
429
+ self,
430
+ hidden_states,
431
+ attention_mask=None,
432
+ head_mask=None,
433
+ encoder_hidden_states=None,
434
+ encoder_attention_mask=None,
435
+ past_key_values=None,
436
+ use_cache=None,
437
+ output_attentions=False,
438
+ output_hidden_states=False,
439
+ return_dict=True,
440
+ mode='multimodal',
441
+ ):
442
+ all_hidden_states = () if output_hidden_states else None
443
+ all_self_attentions = () if output_attentions else None
444
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
445
+
446
+ next_decoder_cache = () if use_cache else None
447
+
448
+ for i in range(self.config.num_hidden_layers):
449
+ layer_module = self.layer[i]
450
+ if output_hidden_states:
451
+ all_hidden_states = all_hidden_states + (hidden_states,)
452
+
453
+ layer_head_mask = head_mask[i] if head_mask is not None else None
454
+ past_key_value = past_key_values[i] if past_key_values is not None else None
455
+
456
+ if self.gradient_checkpointing and self.training:
457
+
458
+ if use_cache:
459
+ logger.warn(
460
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
461
+ )
462
+ use_cache = False
463
+
464
+ def create_custom_forward(module):
465
+ def custom_forward(*inputs):
466
+ return module(*inputs, past_key_value, output_attentions)
467
+
468
+ return custom_forward
469
+
470
+ layer_outputs = torch.utils.checkpoint.checkpoint(
471
+ create_custom_forward(layer_module),
472
+ hidden_states,
473
+ attention_mask,
474
+ layer_head_mask,
475
+ encoder_hidden_states,
476
+ encoder_attention_mask,
477
+ mode=mode,
478
+ )
479
+ else:
480
+ layer_outputs = layer_module(
481
+ hidden_states,
482
+ attention_mask,
483
+ layer_head_mask,
484
+ encoder_hidden_states,
485
+ encoder_attention_mask,
486
+ past_key_value,
487
+ output_attentions,
488
+ mode=mode,
489
+ )
490
+
491
+ hidden_states = layer_outputs[0]
492
+ if use_cache:
493
+ next_decoder_cache += (layer_outputs[-1],)
494
+ if output_attentions:
495
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
496
+
497
+ if output_hidden_states:
498
+ all_hidden_states = all_hidden_states + (hidden_states,)
499
+
500
+ if not return_dict:
501
+ return tuple(
502
+ v
503
+ for v in [
504
+ hidden_states,
505
+ next_decoder_cache,
506
+ all_hidden_states,
507
+ all_self_attentions,
508
+ all_cross_attentions,
509
+ ]
510
+ if v is not None
511
+ )
512
+ return BaseModelOutputWithPastAndCrossAttentions(
513
+ last_hidden_state=hidden_states,
514
+ past_key_values=next_decoder_cache,
515
+ hidden_states=all_hidden_states,
516
+ attentions=all_self_attentions,
517
+ cross_attentions=all_cross_attentions,
518
+ )
519
+
520
+
521
+ class BertPooler(nn.Module):
522
+ def __init__(self, config):
523
+ super().__init__()
524
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
525
+ self.activation = nn.Tanh()
526
+
527
+ def forward(self, hidden_states):
528
+ # We "pool" the model by simply taking the hidden state corresponding
529
+ # to the first token.
530
+ first_token_tensor = hidden_states[:, 0]
531
+ pooled_output = self.dense(first_token_tensor)
532
+ pooled_output = self.activation(pooled_output)
533
+ return pooled_output
534
+
535
+
536
+ class BertPredictionHeadTransform(nn.Module):
537
+ def __init__(self, config):
538
+ super().__init__()
539
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
540
+ if isinstance(config.hidden_act, str):
541
+ self.transform_act_fn = ACT2FN[config.hidden_act]
542
+ else:
543
+ self.transform_act_fn = config.hidden_act
544
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
545
+
546
+ def forward(self, hidden_states):
547
+ hidden_states = self.dense(hidden_states)
548
+ hidden_states = self.transform_act_fn(hidden_states)
549
+ hidden_states = self.LayerNorm(hidden_states)
550
+ return hidden_states
551
+
552
+
553
+ class BertLMPredictionHead(nn.Module):
554
+ def __init__(self, config):
555
+ super().__init__()
556
+ self.transform = BertPredictionHeadTransform(config)
557
+
558
+ # The output weights are the same as the input embeddings, but there is
559
+ # an output-only bias for each token.
560
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
561
+
562
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
563
+
564
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
565
+ self.decoder.bias = self.bias
566
+
567
+ def forward(self, hidden_states):
568
+ hidden_states = self.transform(hidden_states)
569
+ hidden_states = self.decoder(hidden_states)
570
+ return hidden_states
571
+
572
+
573
+ class BertOnlyMLMHead(nn.Module):
574
+ def __init__(self, config):
575
+ super().__init__()
576
+ self.predictions = BertLMPredictionHead(config)
577
+
578
+ def forward(self, sequence_output):
579
+ prediction_scores = self.predictions(sequence_output)
580
+ return prediction_scores
581
+
582
+
583
+ class BertPreTrainedModel(PreTrainedModel):
584
+ """
585
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
586
+ models.
587
+ """
588
+
589
+ config_class = BertConfig
590
+ base_model_prefix = "bert"
591
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
592
+
593
+ def _init_weights(self, module):
594
+ """ Initialize the weights """
595
+ if isinstance(module, (nn.Linear, nn.Embedding)):
596
+ # Slightly different from the TF version which uses truncated_normal for initialization
597
+ # cf https://github.com/pytorch/pytorch/pull/5617
598
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
599
+ elif isinstance(module, nn.LayerNorm):
600
+ module.bias.data.zero_()
601
+ module.weight.data.fill_(1.0)
602
+ if isinstance(module, nn.Linear) and module.bias is not None:
603
+ module.bias.data.zero_()
604
+
605
+
606
+ class BertModel(BertPreTrainedModel):
607
+ """
608
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
609
+ cross-attention is added between the self-attention layers, following the architecture described in `Attention is
610
+ all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
611
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
612
+ argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
613
+ input to the forward pass.
614
+ """
615
+
616
+ def __init__(self, config, add_pooling_layer=True):
617
+ super().__init__(config)
618
+ self.config = config
619
+
620
+ self.embeddings = BertEmbeddings(config)
621
+
622
+ self.encoder = BertEncoder(config)
623
+
624
+ self.pooler = BertPooler(config) if add_pooling_layer else None
625
+
626
+ self.init_weights()
627
+
628
+
629
+ def get_input_embeddings(self):
630
+ return self.embeddings.word_embeddings
631
+
632
+ def set_input_embeddings(self, value):
633
+ self.embeddings.word_embeddings = value
634
+
635
+ def _prune_heads(self, heads_to_prune):
636
+ """
637
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
638
+ class PreTrainedModel
639
+ """
640
+ for layer, heads in heads_to_prune.items():
641
+ self.encoder.layer[layer].attention.prune_heads(heads)
642
+
643
+
644
+ def get_extended_attention_mask(self, attention_mask: Tensor, input_shape: Tuple[int], device: device, is_decoder: bool) -> Tensor:
645
+ """
646
+ Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
647
+
648
+ Arguments:
649
+ attention_mask (:obj:`torch.Tensor`):
650
+ Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
651
+ input_shape (:obj:`Tuple[int]`):
652
+ The shape of the input to the model.
653
+ device: (:obj:`torch.device`):
654
+ The device of the input to the model.
655
+
656
+ Returns:
657
+ :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`.
658
+ """
659
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
660
+ # ourselves in which case we just need to make it broadcastable to all heads.
661
+ if attention_mask.dim() == 3:
662
+ extended_attention_mask = attention_mask[:, None, :, :]
663
+ elif attention_mask.dim() == 2:
664
+ # Provided a padding mask of dimensions [batch_size, seq_length]
665
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
666
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
667
+ if is_decoder:
668
+ batch_size, seq_length = input_shape
669
+
670
+ seq_ids = torch.arange(seq_length, device=device)
671
+ causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None]
672
+ # in case past_key_values are used we need to add a prefix ones mask to the causal mask
673
+ # causal and attention masks must have same type with pytorch version < 1.3
674
+ causal_mask = causal_mask.to(attention_mask.dtype)
675
+
676
+ if causal_mask.shape[1] < attention_mask.shape[1]:
677
+ prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
678
+ causal_mask = torch.cat(
679
+ [
680
+ torch.ones((batch_size, seq_length, prefix_seq_len), device=device, dtype=causal_mask.dtype),
681
+ causal_mask,
682
+ ],
683
+ axis=-1,
684
+ )
685
+
686
+ extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
687
+ else:
688
+ extended_attention_mask = attention_mask[:, None, None, :]
689
+ else:
690
+ raise ValueError(
691
+ "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
692
+ input_shape, attention_mask.shape
693
+ )
694
+ )
695
+
696
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
697
+ # masked positions, this operation will create a tensor which is 0.0 for
698
+ # positions we want to attend and -10000.0 for masked positions.
699
+ # Since we are adding it to the raw scores before the softmax, this is
700
+ # effectively the same as removing these entirely.
701
+ extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
702
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
703
+ return extended_attention_mask
704
+
705
+ def forward(
706
+ self,
707
+ input_ids=None,
708
+ attention_mask=None,
709
+ position_ids=None,
710
+ head_mask=None,
711
+ inputs_embeds=None,
712
+ encoder_embeds=None,
713
+ encoder_hidden_states=None,
714
+ encoder_attention_mask=None,
715
+ past_key_values=None,
716
+ use_cache=None,
717
+ output_attentions=None,
718
+ output_hidden_states=None,
719
+ return_dict=None,
720
+ is_decoder=False,
721
+ mode='multimodal',
722
+ ):
723
+ r"""
724
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
725
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
726
+ the model is configured as a decoder.
727
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
728
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
729
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
730
+ - 1 for tokens that are **not masked**,
731
+ - 0 for tokens that are **masked**.
732
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
733
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
734
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
735
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
736
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
737
+ use_cache (:obj:`bool`, `optional`):
738
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
739
+ decoding (see :obj:`past_key_values`).
740
+ """
741
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
742
+ output_hidden_states = (
743
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
744
+ )
745
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
746
+
747
+ if is_decoder:
748
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
749
+ else:
750
+ use_cache = False
751
+
752
+ if input_ids is not None and inputs_embeds is not None:
753
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
754
+ elif input_ids is not None:
755
+ input_shape = input_ids.size()
756
+ batch_size, seq_length = input_shape
757
+ device = input_ids.device
758
+ elif inputs_embeds is not None:
759
+ input_shape = inputs_embeds.size()[:-1]
760
+ batch_size, seq_length = input_shape
761
+ device = inputs_embeds.device
762
+ elif encoder_embeds is not None:
763
+ input_shape = encoder_embeds.size()[:-1]
764
+ batch_size, seq_length = input_shape
765
+ device = encoder_embeds.device
766
+ else:
767
+ raise ValueError("You have to specify either input_ids or inputs_embeds or encoder_embeds")
768
+
769
+ # past_key_values_length
770
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
771
+
772
+ if attention_mask is None:
773
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
774
+
775
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
776
+ # ourselves in which case we just need to make it broadcastable to all heads.
777
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape,
778
+ device, is_decoder)
779
+
780
+ # If a 2D or 3D attention mask is provided for the cross-attention
781
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
782
+ if encoder_hidden_states is not None:
783
+ if type(encoder_hidden_states) == list:
784
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size()
785
+ else:
786
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
787
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
788
+
789
+ if type(encoder_attention_mask) == list:
790
+ encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask]
791
+ elif encoder_attention_mask is None:
792
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
793
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
794
+ else:
795
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
796
+ else:
797
+ encoder_extended_attention_mask = None
798
+
799
+ # Prepare head mask if needed
800
+ # 1.0 in head_mask indicate we keep the head
801
+ # attention_probs has shape bsz x n_heads x N x N
802
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
803
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
804
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
805
+
806
+ if encoder_embeds is None:
807
+ embedding_output = self.embeddings(
808
+ input_ids=input_ids,
809
+ position_ids=position_ids,
810
+ inputs_embeds=inputs_embeds,
811
+ past_key_values_length=past_key_values_length,
812
+ )
813
+ else:
814
+ embedding_output = encoder_embeds
815
+
816
+ encoder_outputs = self.encoder(
817
+ embedding_output,
818
+ attention_mask=extended_attention_mask,
819
+ head_mask=head_mask,
820
+ encoder_hidden_states=encoder_hidden_states,
821
+ encoder_attention_mask=encoder_extended_attention_mask,
822
+ past_key_values=past_key_values,
823
+ use_cache=use_cache,
824
+ output_attentions=output_attentions,
825
+ output_hidden_states=output_hidden_states,
826
+ return_dict=return_dict,
827
+ mode=mode,
828
+ )
829
+ sequence_output = encoder_outputs[0]
830
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
831
+
832
+ if not return_dict:
833
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
834
+
835
+ return BaseModelOutputWithPoolingAndCrossAttentions(
836
+ last_hidden_state=sequence_output,
837
+ pooler_output=pooled_output,
838
+ past_key_values=encoder_outputs.past_key_values,
839
+ hidden_states=encoder_outputs.hidden_states,
840
+ attentions=encoder_outputs.attentions,
841
+ cross_attentions=encoder_outputs.cross_attentions,
842
+ )
843
+
extras/BLIP/models/vit.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ * Copyright (c) 2022, salesforce.com, inc.
3
+ * All rights reserved.
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6
+ * By Junnan Li
7
+ * Based on timm code base
8
+ * https://github.com/rwightman/pytorch-image-models/tree/master/timm
9
+ '''
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+ from functools import partial
15
+
16
+ from timm.models.vision_transformer import _cfg, PatchEmbed
17
+ from timm.models.registry import register_model
18
+ from timm.models.layers import trunc_normal_, DropPath
19
+ from timm.models.helpers import named_apply, adapt_input_conv
20
+
21
+
22
+ def checkpoint_wrapper(x):
23
+ return x
24
+
25
+
26
+ class Mlp(nn.Module):
27
+ """ MLP as used in Vision Transformer, MLP-Mixer and related networks
28
+ """
29
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
30
+ super().__init__()
31
+ out_features = out_features or in_features
32
+ hidden_features = hidden_features or in_features
33
+ self.fc1 = nn.Linear(in_features, hidden_features)
34
+ self.act = act_layer()
35
+ self.fc2 = nn.Linear(hidden_features, out_features)
36
+ self.drop = nn.Dropout(drop)
37
+
38
+ def forward(self, x):
39
+ x = self.fc1(x)
40
+ x = self.act(x)
41
+ x = self.drop(x)
42
+ x = self.fc2(x)
43
+ x = self.drop(x)
44
+ return x
45
+
46
+
47
+ class Attention(nn.Module):
48
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
49
+ super().__init__()
50
+ self.num_heads = num_heads
51
+ head_dim = dim // num_heads
52
+ # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
53
+ self.scale = qk_scale or head_dim ** -0.5
54
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
55
+ self.attn_drop = nn.Dropout(attn_drop)
56
+ self.proj = nn.Linear(dim, dim)
57
+ self.proj_drop = nn.Dropout(proj_drop)
58
+ self.attn_gradients = None
59
+ self.attention_map = None
60
+
61
+ def save_attn_gradients(self, attn_gradients):
62
+ self.attn_gradients = attn_gradients
63
+
64
+ def get_attn_gradients(self):
65
+ return self.attn_gradients
66
+
67
+ def save_attention_map(self, attention_map):
68
+ self.attention_map = attention_map
69
+
70
+ def get_attention_map(self):
71
+ return self.attention_map
72
+
73
+ def forward(self, x, register_hook=False):
74
+ B, N, C = x.shape
75
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
76
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
77
+
78
+ attn = (q @ k.transpose(-2, -1)) * self.scale
79
+ attn = attn.softmax(dim=-1)
80
+ attn = self.attn_drop(attn)
81
+
82
+ if register_hook:
83
+ self.save_attention_map(attn)
84
+ attn.register_hook(self.save_attn_gradients)
85
+
86
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
87
+ x = self.proj(x)
88
+ x = self.proj_drop(x)
89
+ return x
90
+
91
+
92
+ class Block(nn.Module):
93
+
94
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
95
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, use_grad_checkpointing=False):
96
+ super().__init__()
97
+ self.norm1 = norm_layer(dim)
98
+ self.attn = Attention(
99
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
100
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
101
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
102
+ self.norm2 = norm_layer(dim)
103
+ mlp_hidden_dim = int(dim * mlp_ratio)
104
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
105
+
106
+ if use_grad_checkpointing:
107
+ self.attn = checkpoint_wrapper(self.attn)
108
+ self.mlp = checkpoint_wrapper(self.mlp)
109
+
110
+ def forward(self, x, register_hook=False):
111
+ x = x + self.drop_path(self.attn(self.norm1(x), register_hook=register_hook))
112
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
113
+ return x
114
+
115
+
116
+ class VisionTransformer(nn.Module):
117
+ """ Vision Transformer
118
+ A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` -
119
+ https://arxiv.org/abs/2010.11929
120
+ """
121
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12,
122
+ num_heads=12, mlp_ratio=4., qkv_bias=True, qk_scale=None, representation_size=None,
123
+ drop_rate=0., attn_drop_rate=0., drop_path_rate=0., norm_layer=None,
124
+ use_grad_checkpointing=False, ckpt_layer=0):
125
+ """
126
+ Args:
127
+ img_size (int, tuple): input image size
128
+ patch_size (int, tuple): patch size
129
+ in_chans (int): number of input channels
130
+ num_classes (int): number of classes for classification head
131
+ embed_dim (int): embedding dimension
132
+ depth (int): depth of transformer
133
+ num_heads (int): number of attention heads
134
+ mlp_ratio (int): ratio of mlp hidden dim to embedding dim
135
+ qkv_bias (bool): enable bias for qkv if True
136
+ qk_scale (float): override default qk scale of head_dim ** -0.5 if set
137
+ representation_size (Optional[int]): enable and set representation layer (pre-logits) to this value if set
138
+ drop_rate (float): dropout rate
139
+ attn_drop_rate (float): attention dropout rate
140
+ drop_path_rate (float): stochastic depth rate
141
+ norm_layer: (nn.Module): normalization layer
142
+ """
143
+ super().__init__()
144
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
145
+ norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6)
146
+
147
+ self.patch_embed = PatchEmbed(
148
+ img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
149
+
150
+ num_patches = self.patch_embed.num_patches
151
+
152
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
153
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
154
+ self.pos_drop = nn.Dropout(p=drop_rate)
155
+
156
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
157
+ self.blocks = nn.ModuleList([
158
+ Block(
159
+ dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
160
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer,
161
+ use_grad_checkpointing=(use_grad_checkpointing and i>=depth-ckpt_layer)
162
+ )
163
+ for i in range(depth)])
164
+ self.norm = norm_layer(embed_dim)
165
+
166
+ trunc_normal_(self.pos_embed, std=.02)
167
+ trunc_normal_(self.cls_token, std=.02)
168
+ self.apply(self._init_weights)
169
+
170
+ def _init_weights(self, m):
171
+ if isinstance(m, nn.Linear):
172
+ trunc_normal_(m.weight, std=.02)
173
+ if isinstance(m, nn.Linear) and m.bias is not None:
174
+ nn.init.constant_(m.bias, 0)
175
+ elif isinstance(m, nn.LayerNorm):
176
+ nn.init.constant_(m.bias, 0)
177
+ nn.init.constant_(m.weight, 1.0)
178
+
179
+ @torch.jit.ignore
180
+ def no_weight_decay(self):
181
+ return {'pos_embed', 'cls_token'}
182
+
183
+ def forward(self, x, register_blk=-1):
184
+ B = x.shape[0]
185
+ x = self.patch_embed(x)
186
+
187
+ cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
188
+ x = torch.cat((cls_tokens, x), dim=1)
189
+
190
+ x = x + self.pos_embed[:,:x.size(1),:]
191
+ x = self.pos_drop(x)
192
+
193
+ for i,blk in enumerate(self.blocks):
194
+ x = blk(x, register_blk==i)
195
+ x = self.norm(x)
196
+
197
+ return x
198
+
199
+ @torch.jit.ignore()
200
+ def load_pretrained(self, checkpoint_path, prefix=''):
201
+ _load_weights(self, checkpoint_path, prefix)
202
+
203
+
204
+ @torch.no_grad()
205
+ def _load_weights(model: VisionTransformer, checkpoint_path: str, prefix: str = ''):
206
+ """ Load weights from .npz checkpoints for official Google Brain Flax implementation
207
+ """
208
+ import numpy as np
209
+
210
+ def _n2p(w, t=True):
211
+ if w.ndim == 4 and w.shape[0] == w.shape[1] == w.shape[2] == 1:
212
+ w = w.flatten()
213
+ if t:
214
+ if w.ndim == 4:
215
+ w = w.transpose([3, 2, 0, 1])
216
+ elif w.ndim == 3:
217
+ w = w.transpose([2, 0, 1])
218
+ elif w.ndim == 2:
219
+ w = w.transpose([1, 0])
220
+ return torch.from_numpy(w)
221
+
222
+ w = np.load(checkpoint_path)
223
+ if not prefix and 'opt/target/embedding/kernel' in w:
224
+ prefix = 'opt/target/'
225
+
226
+ if hasattr(model.patch_embed, 'backbone'):
227
+ # hybrid
228
+ backbone = model.patch_embed.backbone
229
+ stem_only = not hasattr(backbone, 'stem')
230
+ stem = backbone if stem_only else backbone.stem
231
+ stem.conv.weight.copy_(adapt_input_conv(stem.conv.weight.shape[1], _n2p(w[f'{prefix}conv_root/kernel'])))
232
+ stem.norm.weight.copy_(_n2p(w[f'{prefix}gn_root/scale']))
233
+ stem.norm.bias.copy_(_n2p(w[f'{prefix}gn_root/bias']))
234
+ if not stem_only:
235
+ for i, stage in enumerate(backbone.stages):
236
+ for j, block in enumerate(stage.blocks):
237
+ bp = f'{prefix}block{i + 1}/unit{j + 1}/'
238
+ for r in range(3):
239
+ getattr(block, f'conv{r + 1}').weight.copy_(_n2p(w[f'{bp}conv{r + 1}/kernel']))
240
+ getattr(block, f'norm{r + 1}').weight.copy_(_n2p(w[f'{bp}gn{r + 1}/scale']))
241
+ getattr(block, f'norm{r + 1}').bias.copy_(_n2p(w[f'{bp}gn{r + 1}/bias']))
242
+ if block.downsample is not None:
243
+ block.downsample.conv.weight.copy_(_n2p(w[f'{bp}conv_proj/kernel']))
244
+ block.downsample.norm.weight.copy_(_n2p(w[f'{bp}gn_proj/scale']))
245
+ block.downsample.norm.bias.copy_(_n2p(w[f'{bp}gn_proj/bias']))
246
+ embed_conv_w = _n2p(w[f'{prefix}embedding/kernel'])
247
+ else:
248
+ embed_conv_w = adapt_input_conv(
249
+ model.patch_embed.proj.weight.shape[1], _n2p(w[f'{prefix}embedding/kernel']))
250
+ model.patch_embed.proj.weight.copy_(embed_conv_w)
251
+ model.patch_embed.proj.bias.copy_(_n2p(w[f'{prefix}embedding/bias']))
252
+ model.cls_token.copy_(_n2p(w[f'{prefix}cls'], t=False))
253
+ pos_embed_w = _n2p(w[f'{prefix}Transformer/posembed_input/pos_embedding'], t=False)
254
+ if pos_embed_w.shape != model.pos_embed.shape:
255
+ pos_embed_w = resize_pos_embed( # resize pos embedding when different size from pretrained weights
256
+ pos_embed_w, model.pos_embed, getattr(model, 'num_tokens', 1), model.patch_embed.grid_size)
257
+ model.pos_embed.copy_(pos_embed_w)
258
+ model.norm.weight.copy_(_n2p(w[f'{prefix}Transformer/encoder_norm/scale']))
259
+ model.norm.bias.copy_(_n2p(w[f'{prefix}Transformer/encoder_norm/bias']))
260
+ # if isinstance(model.head, nn.Linear) and model.head.bias.shape[0] == w[f'{prefix}head/bias'].shape[-1]:
261
+ # model.head.weight.copy_(_n2p(w[f'{prefix}head/kernel']))
262
+ # model.head.bias.copy_(_n2p(w[f'{prefix}head/bias']))
263
+ # if isinstance(getattr(model.pre_logits, 'fc', None), nn.Linear) and f'{prefix}pre_logits/bias' in w:
264
+ # model.pre_logits.fc.weight.copy_(_n2p(w[f'{prefix}pre_logits/kernel']))
265
+ # model.pre_logits.fc.bias.copy_(_n2p(w[f'{prefix}pre_logits/bias']))
266
+ for i, block in enumerate(model.blocks.children()):
267
+ block_prefix = f'{prefix}Transformer/encoderblock_{i}/'
268
+ mha_prefix = block_prefix + 'MultiHeadDotProductAttention_1/'
269
+ block.norm1.weight.copy_(_n2p(w[f'{block_prefix}LayerNorm_0/scale']))
270
+ block.norm1.bias.copy_(_n2p(w[f'{block_prefix}LayerNorm_0/bias']))
271
+ block.attn.qkv.weight.copy_(torch.cat([
272
+ _n2p(w[f'{mha_prefix}{n}/kernel'], t=False).flatten(1).T for n in ('query', 'key', 'value')]))
273
+ block.attn.qkv.bias.copy_(torch.cat([
274
+ _n2p(w[f'{mha_prefix}{n}/bias'], t=False).reshape(-1) for n in ('query', 'key', 'value')]))
275
+ block.attn.proj.weight.copy_(_n2p(w[f'{mha_prefix}out/kernel']).flatten(1))
276
+ block.attn.proj.bias.copy_(_n2p(w[f'{mha_prefix}out/bias']))
277
+ for r in range(2):
278
+ getattr(block.mlp, f'fc{r + 1}').weight.copy_(_n2p(w[f'{block_prefix}MlpBlock_3/Dense_{r}/kernel']))
279
+ getattr(block.mlp, f'fc{r + 1}').bias.copy_(_n2p(w[f'{block_prefix}MlpBlock_3/Dense_{r}/bias']))
280
+ block.norm2.weight.copy_(_n2p(w[f'{block_prefix}LayerNorm_2/scale']))
281
+ block.norm2.bias.copy_(_n2p(w[f'{block_prefix}LayerNorm_2/bias']))
282
+
283
+
284
+ def interpolate_pos_embed(pos_embed_checkpoint, visual_encoder):
285
+ # interpolate position embedding
286
+ embedding_size = pos_embed_checkpoint.shape[-1]
287
+ num_patches = visual_encoder.patch_embed.num_patches
288
+ num_extra_tokens = visual_encoder.pos_embed.shape[-2] - num_patches
289
+ # height (== width) for the checkpoint position embedding
290
+ orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
291
+ # height (== width) for the new position embedding
292
+ new_size = int(num_patches ** 0.5)
293
+
294
+ if orig_size!=new_size:
295
+ # class_token and dist_token are kept unchanged
296
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
297
+ # only the position tokens are interpolated
298
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
299
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
300
+ pos_tokens = torch.nn.functional.interpolate(
301
+ pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)
302
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
303
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
304
+ print('reshape position embedding from %d to %d'%(orig_size ** 2,new_size ** 2))
305
+
306
+ return new_pos_embed
307
+ else:
308
+ return pos_embed_checkpoint
extras/GroundingDINO/config/GroundingDINO_SwinT_OGC.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ batch_size = 1
2
+ modelname = "groundingdino"
3
+ backbone = "swin_T_224_1k"
4
+ position_embedding = "sine"
5
+ pe_temperatureH = 20
6
+ pe_temperatureW = 20
7
+ return_interm_indices = [1, 2, 3]
8
+ backbone_freeze_keywords = None
9
+ enc_layers = 6
10
+ dec_layers = 6
11
+ pre_norm = False
12
+ dim_feedforward = 2048
13
+ hidden_dim = 256
14
+ dropout = 0.0
15
+ nheads = 8
16
+ num_queries = 900
17
+ query_dim = 4
18
+ num_patterns = 0
19
+ num_feature_levels = 4
20
+ enc_n_points = 4
21
+ dec_n_points = 4
22
+ two_stage_type = "standard"
23
+ two_stage_bbox_embed_share = False
24
+ two_stage_class_embed_share = False
25
+ transformer_activation = "relu"
26
+ dec_pred_bbox_embed_share = True
27
+ dn_box_noise_scale = 1.0
28
+ dn_label_noise_ratio = 0.5
29
+ dn_label_coef = 1.0
30
+ dn_bbox_coef = 1.0
31
+ embed_init_tgt = True
32
+ dn_labelbook_size = 2000
33
+ max_text_len = 256
34
+ text_encoder_type = "bert-base-uncased"
35
+ use_text_enhancer = True
36
+ use_fusion_layer = True
37
+ use_checkpoint = True
38
+ use_transformer_ckpt = True
39
+ use_text_cross_attention = True
40
+ text_dropout = 0.0
41
+ fusion_dropout = 0.0
42
+ fusion_droppath = 0.1
43
+ sub_sentence_present = True
extras/GroundingDINO/util/inference.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple, List
2
+
3
+ import ldm_patched.modules.model_management as model_management
4
+ from ldm_patched.modules.model_patcher import ModelPatcher
5
+ from modules.config import path_inpaint
6
+ from modules.model_loader import load_file_from_url
7
+
8
+ import numpy as np
9
+ import supervision as sv
10
+ import torch
11
+ from groundingdino.util.inference import Model
12
+ from groundingdino.util.inference import load_model, preprocess_caption, get_phrases_from_posmap
13
+
14
+
15
+ class GroundingDinoModel(Model):
16
+ def __init__(self):
17
+ self.config_file = 'extras/GroundingDINO/config/GroundingDINO_SwinT_OGC.py'
18
+ self.model = None
19
+ self.load_device = torch.device('cpu')
20
+ self.offload_device = torch.device('cpu')
21
+
22
+ @torch.no_grad()
23
+ @torch.inference_mode()
24
+ def predict_with_caption(
25
+ self,
26
+ image: np.ndarray,
27
+ caption: str,
28
+ box_threshold: float = 0.35,
29
+ text_threshold: float = 0.25
30
+ ) -> Tuple[sv.Detections, torch.Tensor, torch.Tensor, List[str]]:
31
+ if self.model is None:
32
+ filename = load_file_from_url(
33
+ url="https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth",
34
+ file_name='groundingdino_swint_ogc.pth',
35
+ model_dir=path_inpaint)
36
+ model = load_model(model_config_path=self.config_file, model_checkpoint_path=filename)
37
+
38
+ self.load_device = model_management.text_encoder_device()
39
+ self.offload_device = model_management.text_encoder_offload_device()
40
+
41
+ model.to(self.offload_device)
42
+
43
+ self.model = ModelPatcher(model, load_device=self.load_device, offload_device=self.offload_device)
44
+
45
+ model_management.load_model_gpu(self.model)
46
+
47
+ processed_image = GroundingDinoModel.preprocess_image(image_bgr=image).to(self.load_device)
48
+ boxes, logits, phrases = predict(
49
+ model=self.model,
50
+ image=processed_image,
51
+ caption=caption,
52
+ box_threshold=box_threshold,
53
+ text_threshold=text_threshold,
54
+ device=self.load_device)
55
+ source_h, source_w, _ = image.shape
56
+ detections = GroundingDinoModel.post_process_result(
57
+ source_h=source_h,
58
+ source_w=source_w,
59
+ boxes=boxes,
60
+ logits=logits)
61
+ return detections, boxes, logits, phrases
62
+
63
+
64
+ def predict(
65
+ model,
66
+ image: torch.Tensor,
67
+ caption: str,
68
+ box_threshold: float,
69
+ text_threshold: float,
70
+ device: str = "cuda"
71
+ ) -> Tuple[torch.Tensor, torch.Tensor, List[str]]:
72
+ caption = preprocess_caption(caption=caption)
73
+
74
+ # override to use model wrapped by patcher
75
+ model = model.model.to(device)
76
+ image = image.to(device)
77
+
78
+ with torch.no_grad():
79
+ outputs = model(image[None], captions=[caption])
80
+
81
+ prediction_logits = outputs["pred_logits"].cpu().sigmoid()[0] # prediction_logits.shape = (nq, 256)
82
+ prediction_boxes = outputs["pred_boxes"].cpu()[0] # prediction_boxes.shape = (nq, 4)
83
+
84
+ mask = prediction_logits.max(dim=1)[0] > box_threshold
85
+ logits = prediction_logits[mask] # logits.shape = (n, 256)
86
+ boxes = prediction_boxes[mask] # boxes.shape = (n, 4)
87
+
88
+ tokenizer = model.tokenizer
89
+ tokenized = tokenizer(caption)
90
+
91
+ phrases = [
92
+ get_phrases_from_posmap(logit > text_threshold, tokenized, tokenizer).replace('.', '')
93
+ for logit
94
+ in logits
95
+ ]
96
+
97
+ return boxes, logits.max(dim=1)[0], phrases
98
+
99
+
100
+ default_groundingdino = GroundingDinoModel().predict_with_caption
extras/censor.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import numpy as np
4
+ import torch
5
+ from transformers import CLIPConfig, CLIPImageProcessor
6
+
7
+ import ldm_patched.modules.model_management as model_management
8
+ import modules.config
9
+ from extras.safety_checker.models.safety_checker import StableDiffusionSafetyChecker
10
+ from ldm_patched.modules.model_patcher import ModelPatcher
11
+
12
+ safety_checker_repo_root = os.path.join(os.path.dirname(__file__), 'safety_checker')
13
+ config_path = os.path.join(safety_checker_repo_root, "configs", "config.json")
14
+ preprocessor_config_path = os.path.join(safety_checker_repo_root, "configs", "preprocessor_config.json")
15
+
16
+
17
+ class Censor:
18
+ def __init__(self):
19
+ self.safety_checker_model: ModelPatcher | None = None
20
+ self.clip_image_processor: CLIPImageProcessor | None = None
21
+ self.load_device = torch.device('cpu')
22
+ self.offload_device = torch.device('cpu')
23
+
24
+ def init(self):
25
+ if self.safety_checker_model is None and self.clip_image_processor is None:
26
+ safety_checker_model = modules.config.downloading_safety_checker_model()
27
+ self.clip_image_processor = CLIPImageProcessor.from_json_file(preprocessor_config_path)
28
+ clip_config = CLIPConfig.from_json_file(config_path)
29
+ model = StableDiffusionSafetyChecker.from_pretrained(safety_checker_model, config=clip_config)
30
+ model.eval()
31
+
32
+ self.load_device = model_management.text_encoder_device()
33
+ self.offload_device = model_management.text_encoder_offload_device()
34
+
35
+ model.to(self.offload_device)
36
+
37
+ self.safety_checker_model = ModelPatcher(model, load_device=self.load_device, offload_device=self.offload_device)
38
+
39
+ def censor(self, images: list | np.ndarray) -> list | np.ndarray:
40
+ self.init()
41
+ model_management.load_model_gpu(self.safety_checker_model)
42
+
43
+ single = False
44
+ if not isinstance(images, (list, np.ndarray)):
45
+ images = [images]
46
+ single = True
47
+
48
+ safety_checker_input = self.clip_image_processor(images, return_tensors="pt")
49
+ safety_checker_input.to(device=self.load_device)
50
+ checked_images, has_nsfw_concept = self.safety_checker_model.model(images=images,
51
+ clip_input=safety_checker_input.pixel_values)
52
+ checked_images = [image.astype(np.uint8) for image in checked_images]
53
+
54
+ if single:
55
+ checked_images = checked_images[0]
56
+
57
+ return checked_images
58
+
59
+
60
+ default_censor = Censor().censor
extras/expansion.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Fooocus GPT2 Expansion
2
+ # Algorithm created by Lvmin Zhang at 2023, Stanford
3
+ # If used inside Fooocus, any use is permitted.
4
+ # If used outside Fooocus, only non-commercial use is permitted (CC-By NC 4.0).
5
+ # This applies to the word list, vocab, model, and algorithm.
6
+
7
+
8
+ import os
9
+ import torch
10
+ import math
11
+ import ldm_patched.modules.model_management as model_management
12
+
13
+ from transformers.generation.logits_process import LogitsProcessorList
14
+ from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
15
+ from modules.config import path_fooocus_expansion
16
+ from ldm_patched.modules.model_patcher import ModelPatcher
17
+
18
+
19
+ # limitation of np.random.seed(), called from transformers.set_seed()
20
+ SEED_LIMIT_NUMPY = 2**32
21
+ neg_inf = - 8192.0
22
+
23
+
24
+ def safe_str(x):
25
+ x = str(x)
26
+ for _ in range(16):
27
+ x = x.replace(' ', ' ')
28
+ return x.strip(",. \r\n")
29
+
30
+
31
+ def remove_pattern(x, pattern):
32
+ for p in pattern:
33
+ x = x.replace(p, '')
34
+ return x
35
+
36
+
37
+ class FooocusExpansion:
38
+ def __init__(self):
39
+ self.tokenizer = AutoTokenizer.from_pretrained(path_fooocus_expansion)
40
+
41
+ positive_words = open(os.path.join(path_fooocus_expansion, 'positive.txt'),
42
+ encoding='utf-8').read().splitlines()
43
+ positive_words = ['Ġ' + x.lower() for x in positive_words if x != '']
44
+
45
+ self.logits_bias = torch.zeros((1, len(self.tokenizer.vocab)), dtype=torch.float32) + neg_inf
46
+
47
+ debug_list = []
48
+ for k, v in self.tokenizer.vocab.items():
49
+ if k in positive_words:
50
+ self.logits_bias[0, v] = 0
51
+ debug_list.append(k[1:])
52
+
53
+ print(f'Fooocus V2 Expansion: Vocab with {len(debug_list)} words.')
54
+
55
+ # debug_list = '\n'.join(sorted(debug_list))
56
+ # print(debug_list)
57
+
58
+ # t11 = self.tokenizer(',', return_tensors="np")
59
+ # t198 = self.tokenizer('\n', return_tensors="np")
60
+ # eos = self.tokenizer.eos_token_id
61
+
62
+ self.model = AutoModelForCausalLM.from_pretrained(path_fooocus_expansion)
63
+ self.model.eval()
64
+
65
+ load_device = model_management.text_encoder_device()
66
+ offload_device = model_management.text_encoder_offload_device()
67
+
68
+ # MPS hack
69
+ if model_management.is_device_mps(load_device):
70
+ load_device = torch.device('cpu')
71
+ offload_device = torch.device('cpu')
72
+
73
+ use_fp16 = model_management.should_use_fp16(device=load_device)
74
+
75
+ if use_fp16:
76
+ self.model.half()
77
+
78
+ self.patcher = ModelPatcher(self.model, load_device=load_device, offload_device=offload_device)
79
+ print(f'Fooocus Expansion engine loaded for {load_device}, use_fp16 = {use_fp16}.')
80
+
81
+ @torch.no_grad()
82
+ @torch.inference_mode()
83
+ def logits_processor(self, input_ids, scores):
84
+ assert scores.ndim == 2 and scores.shape[0] == 1
85
+ self.logits_bias = self.logits_bias.to(scores)
86
+
87
+ bias = self.logits_bias.clone()
88
+ bias[0, input_ids[0].to(bias.device).long()] = neg_inf
89
+ bias[0, 11] = 0
90
+
91
+ return scores + bias
92
+
93
+ @torch.no_grad()
94
+ @torch.inference_mode()
95
+ def __call__(self, prompt, seed):
96
+ if prompt == '':
97
+ return ''
98
+
99
+ if self.patcher.current_device != self.patcher.load_device:
100
+ print('Fooocus Expansion loaded by itself.')
101
+ model_management.load_model_gpu(self.patcher)
102
+
103
+ seed = int(seed) % SEED_LIMIT_NUMPY
104
+ set_seed(seed)
105
+ prompt = safe_str(prompt) + ','
106
+
107
+ tokenized_kwargs = self.tokenizer(prompt, return_tensors="pt")
108
+ tokenized_kwargs.data['input_ids'] = tokenized_kwargs.data['input_ids'].to(self.patcher.load_device)
109
+ tokenized_kwargs.data['attention_mask'] = tokenized_kwargs.data['attention_mask'].to(self.patcher.load_device)
110
+
111
+ current_token_length = int(tokenized_kwargs.data['input_ids'].shape[1])
112
+ max_token_length = 75 * int(math.ceil(float(current_token_length) / 75.0))
113
+ max_new_tokens = max_token_length - current_token_length
114
+
115
+ if max_new_tokens == 0:
116
+ return prompt[:-1]
117
+
118
+ # https://huggingface.co/blog/introducing-csearch
119
+ # https://huggingface.co/docs/transformers/generation_strategies
120
+ features = self.model.generate(**tokenized_kwargs,
121
+ top_k=100,
122
+ max_new_tokens=max_new_tokens,
123
+ do_sample=True,
124
+ logits_processor=LogitsProcessorList([self.logits_processor]))
125
+
126
+ response = self.tokenizer.batch_decode(features, skip_special_tokens=True)
127
+ result = safe_str(response[0])
128
+
129
+ return result
extras/face_crop.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import modules.config
4
+
5
+
6
+ faceRestoreHelper = None
7
+
8
+
9
+ def align_warp_face(self, landmark, border_mode='constant'):
10
+ affine_matrix = cv2.estimateAffinePartial2D(landmark, self.face_template, method=cv2.LMEDS)[0]
11
+ self.affine_matrices.append(affine_matrix)
12
+ if border_mode == 'constant':
13
+ border_mode = cv2.BORDER_CONSTANT
14
+ elif border_mode == 'reflect101':
15
+ border_mode = cv2.BORDER_REFLECT101
16
+ elif border_mode == 'reflect':
17
+ border_mode = cv2.BORDER_REFLECT
18
+ input_img = self.input_img
19
+ cropped_face = cv2.warpAffine(input_img, affine_matrix, self.face_size,
20
+ borderMode=border_mode, borderValue=(135, 133, 132))
21
+ return cropped_face
22
+
23
+
24
+ def crop_image(img_rgb):
25
+ global faceRestoreHelper
26
+
27
+ if faceRestoreHelper is None:
28
+ from extras.facexlib.utils.face_restoration_helper import FaceRestoreHelper
29
+ faceRestoreHelper = FaceRestoreHelper(
30
+ upscale_factor=1,
31
+ model_rootpath=modules.config.path_controlnet,
32
+ device='cpu' # use cpu is safer since we are out of memory management
33
+ )
34
+
35
+ faceRestoreHelper.clean_all()
36
+ faceRestoreHelper.read_image(np.ascontiguousarray(img_rgb[:, :, ::-1].copy()))
37
+ faceRestoreHelper.get_face_landmarks_5()
38
+
39
+ landmarks = faceRestoreHelper.all_landmarks_5
40
+ # landmarks are already sorted with confidence.
41
+
42
+ if len(landmarks) == 0:
43
+ print('No face detected')
44
+ return img_rgb
45
+ else:
46
+ print(f'Detected {len(landmarks)} faces')
47
+
48
+ result = align_warp_face(faceRestoreHelper, landmarks[0])
49
+
50
+ return np.ascontiguousarray(result[:, :, ::-1].copy())