Spaces:
Running on Zero
Running on Zero
Publicar IGNIS Image Lab com ZeroGPU, estúdio, edição, comparação e documentação
Browse files- .gitattributes +6 -0
- BASE_LICENSE.upstream.txt +82 -0
- MODEL_CARD.md +148 -0
- README.md +49 -7
- app.py +227 -0
- assets/config.json +17 -0
- assets/evaluation.json +38 -0
- assets/samples/pair-1.png +3 -0
- assets/samples/pair-2.png +3 -0
- assets/samples/pair-3.png +3 -0
- assets/samples/pair-4.png +3 -0
- assets/samples/pair-5.png +3 -0
- assets/samples/pair-6.png +3 -0
- assets/training.json +34 -0
- base_model.json +28 -0
- release.json +5 -0
- requirements.txt +9 -0
- runtime.py +114 -0
- settings.py +64 -0
- styles.css +1 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,9 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
assets/samples/pair-1.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
assets/samples/pair-2.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
assets/samples/pair-3.png filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
assets/samples/pair-4.png filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
assets/samples/pair-5.png filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
assets/samples/pair-6.png filter=lfs diff=lfs merge=lfs -text
|
BASE_LICENSE.upstream.txt
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).
|
MODEL_CARD.md
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- en
|
| 4 |
+
- pt
|
| 5 |
+
license: creativeml-openrail-m
|
| 6 |
+
library_name: diffusers
|
| 7 |
+
pipeline_tag: text-to-image
|
| 8 |
+
base_model: stable-diffusion-v1-5/stable-diffusion-v1-5
|
| 9 |
+
base_model_relation: adapter
|
| 10 |
+
tags:
|
| 11 |
+
- lora
|
| 12 |
+
- stable-diffusion
|
| 13 |
+
- ignis
|
| 14 |
+
- experimental
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
# IGNIS Image LoRA v1
|
| 18 |
+
|
| 19 |
+
**Versão experimental com adaptador treinado e evidências de execução anexas.**
|
| 20 |
+
|
| 21 |
+
IGNIS Image LoRA v1 é o primeiro adaptador de geração de imagens previsto para o projeto IGNIS Multimodal, desenvolvido por Vinicius de Souza Santos. A proposta é especializar o UNet do Stable Diffusion 1.5 por Low-Rank Adaptation (LoRA), mantendo os parâmetros originais congelados.
|
| 22 |
+
|
| 23 |
+
Este repositório se destina ao adaptador, não a um modelo-base treinado do zero. Ele não contém os componentes de compreensão visual SmolVLM2 ou Qwen3-VL. Esses modelos são integrações independentes da plataforma IGNIS Multimodal.
|
| 24 |
+
|
| 25 |
+
## Identificação e autoria
|
| 26 |
+
|
| 27 |
+
| Item | Descrição |
|
| 28 |
+
|---|---|
|
| 29 |
+
| Nome previsto | IGNIS Image LoRA v1 |
|
| 30 |
+
| Repositório proposto | `ViniciusKhan/ignis-image-lora-v1` |
|
| 31 |
+
| Base | `stable-diffusion-v1-5/stable-diffusion-v1-5` |
|
| 32 |
+
| Tipo de contribuição | Adaptador LoRA, treinamento, integração e avaliação |
|
| 33 |
+
| Autor do projeto IGNIS | Vinicius de Souza Santos |
|
| 34 |
+
| Estado atual deste documento | Versão experimental preparada para publicação |
|
| 35 |
+
|
| 36 |
+
A autoria do projeto IGNIS e dos adaptadores não transfere a autoria dos pesos-base nem das obras utilizadas no experimento. As referências e condições da base devem acompanhar a distribuição.
|
| 37 |
+
|
| 38 |
+
## Objetivo e uso pretendido
|
| 39 |
+
|
| 40 |
+
Investigar adaptação eficiente de geração de imagens em hardware de consumo, com memória de GPU limitada. O coletor suporta obras em domínio público e, quando a instituição estiver indisponível, um recorte sintético do DiffusionDB, com licença CC0 declarada pelos mantenedores. A fonte realmente utilizada será identificada no manifesto da execução. Não foi demonstrada uma melhoria geral sobre o modelo-base, nem uma especialização artística consistente.
|
| 41 |
+
|
| 42 |
+
Os usos previstos são pesquisa, demonstração e experimentação criativa dentro das condições de uso da base. Não utilizar as imagens como prova factual, reprodução documental exata, diagnóstico ou evidência científica sem verificação independente.
|
| 43 |
+
|
| 44 |
+
## Arquitetura e método
|
| 45 |
+
|
| 46 |
+
Stable Diffusion 1.5 é uma base de difusão latente condicionada por texto. O pipeline IGNIS congela VAE, codificador de texto e parâmetros-base do UNet. As atualizações LoRA são aplicadas às projeções `to_q`, `to_k`, `to_v` e `to_out.0` do UNet.
|
| 47 |
+
|
| 48 |
+
O pré-cálculo de latentes e embeddings ocorre em sequência para reduzir a coexistência dos componentes na GPU. O treinamento utiliza precisão mista, acumulação de gradientes e gradient checkpointing. Os pesos treináveis permanecem em FP32 para compatibilidade com o scaler FP16.
|
| 49 |
+
|
| 50 |
+
## Dados e proveniência
|
| 51 |
+
|
| 52 |
+
O manifesto desta execução registra **82 imagens de treino** e **14 de validação**. Origem: `{"name": "DiffusionDB — recorte experimental de imagens sintéticas", "repo": "poloclub/diffusiondb", "revision": "fb620fbe49fa4420e0734bd9c0df11f51176b61f", "license": "cc0-1.0", "terms": "https://huggingface.co/datasets/poloclub/diffusiondb/blob/fb620fbe49fa4420e0734bd9c0df11f51176b61f/README.md", "synthetic": true, "source_file": "images/part-000001.zip", "scope": "Um exemplar por prompt normalizado; deduplicação por pixels; exclusão textual heurística. Não há certificação de segurança visual.", "limitation": "Imagens geradas por Stable Diffusion. Não são fotografias reais nem demonstram melhoria geral da base."}`. Fingerprint do dataset: `90c1f9c61a6dfa9716dd866880f90b9973131bced5e87872f37bfd30bdf6f999`. A proveniência individual acompanha a versão em `data_provenance.json`.
|
| 53 |
+
|
| 54 |
+
As legendas são construídas com metadados de catálogo na fonte museológica, ou recuperadas dos prompts originais no DiffusionDB. No segundo caso, as imagens são sintéticas e geradas com Stable Diffusion; os prompts não garantem correspondência exata ao conteúdo visual. Não se deve apresentar esse recorte como fotografias reais, coleção de obras museológicas ou evidência de generalização superior. O coletor limita repetições de prompts e aplica exclusão textual heurística, que não substitui inspeção visual.
|
| 55 |
+
|
| 56 |
+
As imagens são deduplicadas pelo hash dos pixels decodificados. Aproximadamente 15% das imagens únicas são reservadas para validação, com no mínimo duas imagens. O manifesto registra arquivo, legenda, hash, origem e licença. A publicação inicial não deve redistribuir o dataset por padrão.
|
| 57 |
+
|
| 58 |
+
Fontes: [API e política de imagens](https://api.artic.edu/docs/#copyright), [DiffusionDB — dados e licença](https://huggingface.co/datasets/poloclub/diffusiondb) e [modelo-base](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5).
|
| 59 |
+
|
| 60 |
+
## Configuração efetivamente executada
|
| 61 |
+
|
| 62 |
+
```json
|
| 63 |
+
{
|
| 64 |
+
"name": "ignis-image-lora-v1",
|
| 65 |
+
"rank": 8,
|
| 66 |
+
"resolution": 512,
|
| 67 |
+
"batch_size": 1,
|
| 68 |
+
"gradient_accumulation": 4,
|
| 69 |
+
"learning_rate": 0.0001,
|
| 70 |
+
"max_steps": 800,
|
| 71 |
+
"warmup_steps": 50,
|
| 72 |
+
"checkpoint_every": 50,
|
| 73 |
+
"validation_every": 50,
|
| 74 |
+
"patience": 5,
|
| 75 |
+
"min_steps": 300,
|
| 76 |
+
"seed": 42,
|
| 77 |
+
"dataset_fingerprint": "90c1f9c61a6dfa9716dd866880f90b9973131bced5e87872f37bfd30bdf6f999",
|
| 78 |
+
"base_revision": "451f4fe16113bff5a5d2269ed5ad43b0592e9a14"
|
| 79 |
+
}
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
## Resultados e avaliação
|
| 83 |
+
|
| 84 |
+
Execução concluída com **550 atualizações do otimizador**. Motivo de parada: `early_stopping_validation`.
|
| 85 |
+
|
| 86 |
+
Loss inicial de validação: `0.19390892872719892`. Melhor loss de validação observada durante o treinamento: `0.19316272154849554`. A melhor loss pode corresponder a um checkpoint anterior ao adaptador final publicado.
|
| 87 |
+
|
| 88 |
+
As imagens em `samples/` comparam base e adaptador final com prompts e sementes idênticos. Consulte `evaluation_report.json` para os pares e `training_report.json` para a execução. Não foram calculados FID ou CLIP score. A comparação não demonstra superioridade geral sobre a base.
|
| 89 |
+
|
| 90 |
+

|
| 91 |
+
|
| 92 |
+
## Como carregar os pesos após a publicação
|
| 93 |
+
|
| 94 |
+
Após o envio desta versão ao Hub, carregue a base e o adaptador em uma GPU CUDA compatível:
|
| 95 |
+
|
| 96 |
+
```python
|
| 97 |
+
import torch
|
| 98 |
+
from diffusers import StableDiffusionPipeline
|
| 99 |
+
|
| 100 |
+
# Os pesos-base e o adaptador são carregados separadamente.
|
| 101 |
+
pipeline = StableDiffusionPipeline.from_pretrained(
|
| 102 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5",
|
| 103 |
+
torch_dtype=torch.float16,
|
| 104 |
+
use_safetensors=True,
|
| 105 |
+
)
|
| 106 |
+
pipeline.load_lora_weights("ViniciusKhan/ignis-image-lora-v1")
|
| 107 |
+
pipeline.enable_model_cpu_offload()
|
| 108 |
+
pipeline.enable_vae_slicing()
|
| 109 |
+
|
| 110 |
+
# Prompts em inglês são recomendados para esta base.
|
| 111 |
+
imagem = pipeline(
|
| 112 |
+
"A detailed oil painting of a quiet garden, soft morning light",
|
| 113 |
+
generator=torch.Generator(device="cpu").manual_seed(42),
|
| 114 |
+
num_inference_steps=25,
|
| 115 |
+
width=512,
|
| 116 |
+
height=512,
|
| 117 |
+
).images[0]
|
| 118 |
+
imagem.save("ignis-exemplo.png")
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
O filtro de segurança da base permanece habilitado. A existência de instruções de carregamento não implica que os pesos já estejam disponíveis.
|
| 122 |
+
|
| 123 |
+
## Limitações e riscos
|
| 124 |
+
|
| 125 |
+
- Dataset pequeno, heterogêneo e com legendas derivadas de catálogo ou prompts de geração; risco de sobreajuste e associação espúria entre texto e conteúdo visual.
|
| 126 |
+
- Quando a fonte for DiffusionDB, treinar sobre imagens sintéticas da mesma família de modelos pode reforçar artefatos e vieses existentes, sem adicionar conhecimento visual novo.
|
| 127 |
+
- Vieses e limitações herdados da base e da seleção museológica.
|
| 128 |
+
- Textos, mãos, anatomia, contagem de objetos e relações espaciais podem apresentar erros.
|
| 129 |
+
- Não há comprovação de geração confiável de texto em português ou de domínio geral multimodal neste adaptador.
|
| 130 |
+
- Imagens geradas não comprovam a existência das cenas retratadas.
|
| 131 |
+
- O adaptador pode aumentar a semelhança com exemplos de treinamento; inspecionar memorizações antes de ampliar a distribuição.
|
| 132 |
+
|
| 133 |
+
## Licença e distribuição
|
| 134 |
+
|
| 135 |
+
Preserve as condições da CreativeML Open RAIL-M e as atribuições aplicáveis ao modelo-base. A versão de publicação inclui a licença original e os metadados de origem recuperados do Hub. O estado de domínio público de uma obra não implica automaticamente ausência de restrições sobre marcas, pessoas retratadas ou todos os usos em todas as jurisdições.
|
| 136 |
+
|
| 137 |
+
## Reprodutibilidade e arquivos da versão
|
| 138 |
+
|
| 139 |
+
Esta versão contém `pytorch_lora_weights.safetensors`, `training_config.json`, `training_report.json`, `data_provenance.json`, `base_model.json`, `evaluation_report.json` e amostras pareadas. Checkpoints internos, estados do otimizador, caches, tokens e imagens originais não são publicados por padrão.
|
| 140 |
+
|
| 141 |
+
## Referências e citação
|
| 142 |
+
|
| 143 |
+
- [Stable Diffusion 1.5 — model card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)
|
| 144 |
+
- [Diffusers — treinamento LoRA](https://huggingface.co/docs/diffusers/training/lora)
|
| 145 |
+
- [LoRA: Low-Rank Adaptation of Large Language Models](https://arxiv.org/abs/2106.09685)
|
| 146 |
+
- [Art Institute of Chicago — API](https://api.artic.edu/docs/)
|
| 147 |
+
|
| 148 |
+
Após a primeira versão, cite o repositório IGNIS, sua revisão exata e a data de acesso. Este projeto não declara artigo revisado por pares ou DOI próprio.
|
README.md
CHANGED
|
@@ -1,13 +1,55 @@
|
|
| 1 |
---
|
| 2 |
title: IGNIS Image Lab
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
python_version:
|
| 9 |
app_file: app.py
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: IGNIS Image Lab
|
| 3 |
+
emoji: 🔬
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.49.1
|
| 8 |
+
python_version: "3.10"
|
| 9 |
app_file: app.py
|
| 10 |
+
suggested_hardware: zero-a10g
|
| 11 |
+
models:
|
| 12 |
+
- ViniciusKhan/ignis-image-lora-v1
|
| 13 |
+
- stable-diffusion-v1-5/stable-diffusion-v1-5
|
| 14 |
---
|
| 15 |
|
| 16 |
+
# IGNIS Image Lab
|
| 17 |
+
|
| 18 |
+
Demonstração de geração de imagens e comparação entre Stable Diffusion 1.5 e o adaptador IGNIS Image LoRA v1. A aplicação identifica qual componente gerou cada saída e utiliza a mesma seed na comparação.
|
| 19 |
+
|
| 20 |
+
**Pré-requisito:** o adaptador precisa existir no repositório indicado em `IGNIS_MODEL_ID`. A interface pode abrir antes disso, mas gerações com IGNIS informarão explicitamente a ausência dos pesos. A base pode ser testada de forma independente.
|
| 21 |
+
|
| 22 |
+
## Recursos
|
| 23 |
+
|
| 24 |
+
- Estúdio com estilos, exemplos, seed fixa ou aleatória, enquadramento, intensidade LoRA, orientação, passos e amostrador.
|
| 25 |
+
- Comparação com parâmetros idênticos e controle deslizante base × IGNIS.
|
| 26 |
+
- Edição image-to-image e inpainting com máscara enviada pelo usuário.
|
| 27 |
+
- Downloads PNG, JSON e ZIP; receita incorporada ao PNG e importação de receitas.
|
| 28 |
+
- Histórico temporário de até 24 imagens por sessão.
|
| 29 |
+
- Documentação, registros de treinamento e seis comparações reais da versão publicada.
|
| 30 |
+
- Sem treinamento público, acesso ao sistema de arquivos do usuário ou download arbitrário de modelos pela interface.
|
| 31 |
+
|
| 32 |
+
Este Space demonstra apenas o componente de imagens. A plataforma local IGNIS Multimodal inclui visão, documentos, edição e laboratório de treinamento, que não são automaticamente disponibilizados por esta demonstração.
|
| 33 |
+
|
| 34 |
+
## Configuração
|
| 35 |
+
|
| 36 |
+
Variável `IGNIS_MODEL_ID`: repositório do adaptador. O empacotador gera também `release.json` com a revisão exata da versão do modelo. Token opcional de leitura para repositórios privados deve ser configurado como segredo `HF_TOKEN` nas configurações do Space.
|
| 37 |
+
|
| 38 |
+
O destino é ZeroGPU (`zero-a10g` na API), com `IGNIS_ZERO_GPU=1`. O runtime inicializa os pesos em CUDA fora das funções decoradas com `spaces.GPU`. Contas pessoais elegíveis podem hospedar ZeroGPU gratuito com quotas e filas; a disponibilidade é decidida pelo Hugging Face. Gradio em CPU Basic exige plano pago na política atual. O publicador não tenta hardware pago.
|
| 39 |
+
|
| 40 |
+
As imagens e receitas ficam temporariamente no servidor. Baixe os arquivos que desejar guardar. O tempo registrado mede a inferência, não necessariamente a espera na fila. Presets adicionam termos ao prompt; não são adaptadores adicionais. A comparação visual não comprova superioridade do modelo.
|
| 41 |
+
|
| 42 |
+
Use `scripts/deploy-space.ps1` do projeto para publicar somente esta demonstração, sem reenviar ou retreinar o modelo.
|
| 43 |
+
|
| 44 |
+
## Execução local
|
| 45 |
+
|
| 46 |
+
```powershell
|
| 47 |
+
python -m pip install -r requirements.txt
|
| 48 |
+
python app.py
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
## Autoria e limites
|
| 52 |
+
|
| 53 |
+
Projeto IGNIS: Vinicius de Souza Santos. Modelo-base: Stable Diffusion 1.5; especialização: adaptador LoRA IGNIS. O adaptador não representa treinamento integral da base do zero. Preservam-se os filtros e as condições de uso da base.
|
| 54 |
+
|
| 55 |
+
Referências de experiência: [FLUX.1 schnell](https://huggingface.co/spaces/black-forest-labs/FLUX.1-schnell) e [Stable Diffusion 3.5 Large](https://huggingface.co/spaces/stabilityai/stable-diffusion-3.5-large). O design e a implementação IGNIS são próprios.
|
app.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Interface pública IGNIS: criação, edição, comparação e receitas de imagens."""
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
import uuid
|
| 6 |
+
import zipfile
|
| 7 |
+
from datetime import datetime, timezone
|
| 8 |
+
|
| 9 |
+
os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")
|
| 10 |
+
import gradio as gr
|
| 11 |
+
from PIL import Image
|
| 12 |
+
from PIL.PngImagePlugin import PngInfo
|
| 13 |
+
from settings import ROOT, RELEASE, MODEL_ID, TRAINING, CONFIG, EVALUATION, PRESETS, SIZES, SAMPLERS, EXAMPLES, recipe, restore_recipe
|
| 14 |
+
|
| 15 |
+
OUT = ROOT / ".outputs"
|
| 16 |
+
OUT.mkdir(exist_ok=True)
|
| 17 |
+
if os.environ.get("IGNIS_ZERO_GPU") == "1":
|
| 18 |
+
import runtime
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def persist(results, seconds, previous):
|
| 22 |
+
# Remove somente saídas geradas antigas; os fontes e pesos não são tocados.
|
| 23 |
+
for old in OUT.iterdir():
|
| 24 |
+
if old.is_file() and old.suffix in (".png", ".json", ".zip") and time.time() - old.stat().st_mtime > 86400:
|
| 25 |
+
old.unlink(missing_ok=True)
|
| 26 |
+
history, records, paths = list(previous or []), [], []
|
| 27 |
+
for image, metadata in results:
|
| 28 |
+
identifier = uuid.uuid4().hex
|
| 29 |
+
metadata = {**metadata, "created_at": datetime.now(timezone.utc).isoformat(), "request_inference_seconds": seconds}
|
| 30 |
+
png, info = OUT / f"{identifier}.png", OUT / f"{identifier}.json"
|
| 31 |
+
embedded = PngInfo()
|
| 32 |
+
embedded.add_text("ignis", json.dumps(metadata, ensure_ascii=False))
|
| 33 |
+
image.save(png, pnginfo=embedded)
|
| 34 |
+
info.write_text(json.dumps(metadata, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 35 |
+
row = {"image": str(png), "json": str(info), "metadata": metadata}
|
| 36 |
+
records.append(row); history.append(row); paths.extend([png, info])
|
| 37 |
+
bundle = OUT / f"{uuid.uuid4().hex}.zip"
|
| 38 |
+
with zipfile.ZipFile(bundle, "w", zipfile.ZIP_DEFLATED) as archive:
|
| 39 |
+
for path in paths:
|
| 40 |
+
archive.write(path, path.name)
|
| 41 |
+
history = history[-24:]
|
| 42 |
+
gallery = [(row["image"], f"{row['metadata']['model']} · seed {row['metadata']['seed']}") for row in reversed(history)]
|
| 43 |
+
return records, history, gallery, str(bundle)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def create_images(prompt, negative, seed, randomize, size, steps, guidance, scale, model, sampler, preset, count, history,
|
| 47 |
+
progress=gr.Progress(track_tqdm=True)):
|
| 48 |
+
try:
|
| 49 |
+
options = recipe(prompt, negative, seed, randomize, size, steps, guidance, scale, model, sampler, preset, count)
|
| 50 |
+
progress(0, desc="Executando a geração")
|
| 51 |
+
from runtime import generate
|
| 52 |
+
results, seconds = generate(options)
|
| 53 |
+
records, history, gallery, bundle = persist(results, seconds, history)
|
| 54 |
+
progress(1, desc="Imagens e receitas salvas")
|
| 55 |
+
return ([(r["image"], f"Seed {r['metadata']['seed']}") for r in records], options["seed"],
|
| 56 |
+
f"{len(records)} imagem(ns) · {seconds}s de inferência · seed {options['seed']}",
|
| 57 |
+
bundle, records[0]["image"], records[0]["json"], history, gallery, records[0]["metadata"])
|
| 58 |
+
except Exception as exc:
|
| 59 |
+
raise gr.Error(str(exc)) from exc
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def compare_images(prompt, negative, seed, size, steps, guidance, scale, sampler, history, progress=gr.Progress(track_tqdm=True)):
|
| 63 |
+
try:
|
| 64 |
+
options = recipe(prompt, negative, seed, False, size, steps, guidance, scale, "IGNIS LoRA", sampler, "Sem estilo adicional")
|
| 65 |
+
progress(0, desc="Gerando o par com a mesma semente")
|
| 66 |
+
from runtime import compare
|
| 67 |
+
results, seconds = compare(options)
|
| 68 |
+
records, history, gallery, bundle = persist(results, seconds, history)
|
| 69 |
+
return (results[0][0], results[1][0], (results[0][0], results[1][0]),
|
| 70 |
+
f"Base à esquerda · IGNIS à direita · seed {options['seed']} · {seconds}s de inferência", bundle, history, gallery)
|
| 71 |
+
except Exception as exc:
|
| 72 |
+
raise gr.Error(str(exc)) from exc
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def edit_image(prompt, image, mask, mode, strength, seed, steps, scale, history, progress=gr.Progress(track_tqdm=True)):
|
| 76 |
+
try:
|
| 77 |
+
options = recipe(prompt, "", seed, False, next(iter(SIZES)), steps, 7.5, scale, "IGNIS LoRA", SAMPLERS[0], "Sem estilo adicional")
|
| 78 |
+
progress(0, desc="Aplicando a edição")
|
| 79 |
+
from runtime import edit
|
| 80 |
+
results, seconds = edit(options, image, mask, mode, strength)
|
| 81 |
+
records, history, gallery, bundle = persist(results, seconds, history)
|
| 82 |
+
return results[0][0], f"{mode} · seed {int(seed)} · {seconds}s de inferência", bundle, history, gallery
|
| 83 |
+
except Exception as exc:
|
| 84 |
+
raise gr.Error(str(exc)) from exc
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def import_recipe(raw):
|
| 88 |
+
try:
|
| 89 |
+
options, size = restore_recipe(raw)
|
| 90 |
+
return (options["prompt"], options["negative_prompt"], options["seed"], False, size, options["steps"],
|
| 91 |
+
options["guidance_scale"], options["lora_scale"], options["model"], options["sampler"], "Sem estilo adicional")
|
| 92 |
+
except Exception as exc:
|
| 93 |
+
raise gr.Error(f"Receita inválida: {exc}") from exc
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def last_image(history):
|
| 97 |
+
if not history:
|
| 98 |
+
raise gr.Error("Gere uma imagem no Estúdio ou envie um arquivo para editar.")
|
| 99 |
+
with Image.open(history[-1]["image"]) as image:
|
| 100 |
+
return image.copy()
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def gallery_selection(history, event: gr.SelectData):
|
| 104 |
+
index = event.index if isinstance(event.index, int) else event.index[0]
|
| 105 |
+
row = list(reversed(history))[index]
|
| 106 |
+
return row["metadata"], row["image"], row["json"]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def training_summary():
|
| 110 |
+
if not TRAINING:
|
| 111 |
+
return "Os registros do treinamento serão apresentados após o empacotamento."
|
| 112 |
+
rows = {"Atualizações": TRAINING.get("step"), "Resolução": CONFIG.get("resolution"), "Rank LoRA": CONFIG.get("rank"),
|
| 113 |
+
"Parada": TRAINING.get("stop_reason"), "Loss inicial": TRAINING.get("initial_validation_loss"),
|
| 114 |
+
"Melhor loss observada": TRAINING.get("best_validation_loss")}
|
| 115 |
+
return "### Um experimento, com evidências\n\n| Registro | Valor |\n|---|---|\n" + "\n".join(f"| {k} | {v} |" for k, v in rows.items()) + "\n\nA melhor loss pode pertencer a um checkpoint anterior ao adaptador final. A loss não comprova superioridade visual."
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def build_app():
|
| 119 |
+
theme = gr.themes.Soft(primary_hue="cyan", secondary_hue="blue", neutral_hue="slate", font=["Segoe UI", "Arial", "sans-serif"])
|
| 120 |
+
with gr.Blocks(title="IGNIS Image Lab", analytics_enabled=False, delete_cache=(3600, 86400),
|
| 121 |
+
theme=theme, css=(ROOT / "styles.css").read_text(encoding="utf-8")) as application:
|
| 122 |
+
state = gr.State([], time_to_live=3600)
|
| 123 |
+
gr.HTML(f'''<div class="ignis-header"><a class="ignis-brand" href="https://huggingface.co/{MODEL_ID}" target="_blank" rel="noopener"><span class="brand-symbol">i</span><span>IGNIS <small>Image Lab</small></span></a><span class="release-label">LoRA experimental · v1</span></div><div class="ignis-hero"><div><h1>Seu próximo<br>experimento visual.</h1><p>Crie imagens, explore variações e descubra o que muda com o adaptador IGNIS.</p><div class="hero-links"><a href="https://huggingface.co/{MODEL_ID}" target="_blank" rel="noopener">Conhecer o modelo</a><a href="https://huggingface.co/{MODEL_ID}/tree/main" target="_blank" rel="noopener">Pesos e arquivos</a></div></div><div class="hero-art" aria-hidden="true"><div class="art-square one"></div><div class="art-square two"></div><div class="art-square three"></div><span>Texto. Forma. Possibilidade.</span></div></div>''')
|
| 124 |
+
gr.Markdown("**Base:** Stable Diffusion 1.5 · **Especialização:** IGNIS LoRA · **ZeroGPU:** filas e quotas quando disponível.", elem_classes="context-bar")
|
| 125 |
+
with gr.Tabs():
|
| 126 |
+
with gr.Tab("Estúdio"):
|
| 127 |
+
with gr.Row(equal_height=False):
|
| 128 |
+
with gr.Column(scale=5, min_width=300, elem_classes="control-panel"):
|
| 129 |
+
gr.Markdown("### Descreva sua ideia\nPrompts em inglês costumam funcionar melhor nesta base.")
|
| 130 |
+
prompt = gr.Textbox(label="Prompt", placeholder="A quiet botanical garden at sunrise, delicate watercolor…", lines=4)
|
| 131 |
+
with gr.Row():
|
| 132 |
+
preset = gr.Dropdown(list(PRESETS), value="Sem estilo adicional", label="Direção visual")
|
| 133 |
+
model = gr.Dropdown(["IGNIS LoRA", "Stable Diffusion 1.5"], value="IGNIS LoRA", label="Modelo")
|
| 134 |
+
generate = gr.Button("Gerar imagem", variant="primary", size="lg", elem_id="generate-button")
|
| 135 |
+
with gr.Accordion("Ajustar a geração", open=False):
|
| 136 |
+
negative = gr.Textbox(label="Prompt negativo")
|
| 137 |
+
with gr.Row():
|
| 138 |
+
seed = gr.Number(label="Seed", value=42, precision=0, minimum=0, maximum=2**32 - 1)
|
| 139 |
+
randomize = gr.Checkbox(value=True, label="Sortear seed")
|
| 140 |
+
size = gr.Dropdown(list(SIZES), value=next(iter(SIZES)), label="Enquadramento")
|
| 141 |
+
with gr.Row():
|
| 142 |
+
steps = gr.Slider(5, 40, value=25, step=1, label="Passos")
|
| 143 |
+
guidance = gr.Slider(1, 15, value=7.5, step=.5, label="Orientação do prompt")
|
| 144 |
+
scale = gr.Slider(0, 1.5, value=1, step=.05, label="Intensidade LoRA")
|
| 145 |
+
sampler = gr.Dropdown(SAMPLERS, value=SAMPLERS[0], label="Amostrador")
|
| 146 |
+
count = gr.Radio([1, 2], value=1, label="Imagens por solicitação")
|
| 147 |
+
gr.Markdown("#### Um ponto de partida")
|
| 148 |
+
gr.Examples(EXAMPLES, inputs=[prompt, preset], cache_examples=False)
|
| 149 |
+
with gr.Accordion("Importar uma receita", open=False):
|
| 150 |
+
recipe_file = gr.File(label="Receita JSON", file_types=[".json"], type="binary")
|
| 151 |
+
with gr.Column(scale=7, min_width=320, elem_classes="result-panel"):
|
| 152 |
+
output = gr.Gallery(label="Suas imagens", columns=1, rows=1, height=520, object_fit="contain", interactive=False)
|
| 153 |
+
status = gr.Markdown("Sua imagem aparecerá aqui. Escolha um exemplo ou escreva um prompt.")
|
| 154 |
+
with gr.Row():
|
| 155 |
+
png_download = gr.File(label="PNG com receita incorporada", interactive=False)
|
| 156 |
+
json_download = gr.File(label="Receita JSON", interactive=False)
|
| 157 |
+
bundle = gr.File(label="Pacote completo · ZIP", interactive=False)
|
| 158 |
+
with gr.Accordion("Parâmetros usados", open=False):
|
| 159 |
+
metadata = gr.JSON(label="Receita reproduzível")
|
| 160 |
+
with gr.Tab("Comparar"):
|
| 161 |
+
gr.Markdown("### A mesma ideia. Dois resultados.\nCompare base e adaptador com prompt, seed, amostrador e resolução idênticos.")
|
| 162 |
+
compare_prompt = gr.Textbox(label="Prompt", value="A watercolor landscape with mountains and a lake", lines=2)
|
| 163 |
+
with gr.Row():
|
| 164 |
+
compare_seed = gr.Number(value=42, precision=0, label="Seed", minimum=0, maximum=2**32 - 1)
|
| 165 |
+
compare_size = gr.Dropdown(list(SIZES), value=next(iter(SIZES)), label="Enquadramento")
|
| 166 |
+
compare_steps = gr.Slider(5, 40, value=25, step=1, label="Passos")
|
| 167 |
+
with gr.Accordion("Ajustes da comparação", open=False):
|
| 168 |
+
compare_negative = gr.Textbox(label="Prompt negativo")
|
| 169 |
+
compare_guidance = gr.Slider(1, 15, value=7.5, step=.5, label="Orientação")
|
| 170 |
+
compare_scale = gr.Slider(0, 1.5, value=1, step=.05, label="Intensidade LoRA")
|
| 171 |
+
compare_sampler = gr.Dropdown(SAMPLERS, value=SAMPLERS[0], label="Amostrador")
|
| 172 |
+
compare_button = gr.Button("Gerar comparação", variant="primary")
|
| 173 |
+
slider = gr.ImageSlider(label="Deslize para comparar · base / IGNIS", type="pil")
|
| 174 |
+
with gr.Accordion("Ver as duas imagens", open=False):
|
| 175 |
+
with gr.Row():
|
| 176 |
+
base_output = gr.Image(label="Stable Diffusion 1.5", type="pil", interactive=False)
|
| 177 |
+
tuned_output = gr.Image(label="IGNIS LoRA", type="pil", interactive=False)
|
| 178 |
+
compare_status = gr.Markdown("A comparação visual não representa uma pontuação automática de qualidade.")
|
| 179 |
+
compare_bundle = gr.File(label="Comparação e receitas", interactive=False)
|
| 180 |
+
with gr.Tab("Editar"):
|
| 181 |
+
gr.Markdown("### Explore uma nova versão\nAltere a imagem inteira ou envie uma máscara: branco para editar. O inpainting usa o UNet de quatro canais do SD 1.5.")
|
| 182 |
+
with gr.Row():
|
| 183 |
+
edit_input = gr.Image(label="Imagem inicial", type="pil", sources=["upload", "clipboard"])
|
| 184 |
+
edit_mask = gr.Image(label="Máscara opcional", type="pil", sources=["upload", "clipboard"])
|
| 185 |
+
edit_output = gr.Image(label="Resultado", type="pil", interactive=False)
|
| 186 |
+
use_last = gr.Button("Usar minha última imagem")
|
| 187 |
+
edit_prompt = gr.Textbox(label="Descreva o resultado desejado", lines=2)
|
| 188 |
+
with gr.Row():
|
| 189 |
+
edit_mode = gr.Dropdown([("Imagem inteira", "image-to-image"), ("Região com máscara", "inpainting")], value="image-to-image", label="Operação")
|
| 190 |
+
strength = gr.Slider(.1, .95, value=.65, step=.05, label="Intensidade da mudança")
|
| 191 |
+
edit_seed = gr.Number(value=42, precision=0, minimum=0, maximum=2**32 - 1, label="Seed")
|
| 192 |
+
with gr.Row():
|
| 193 |
+
edit_steps = gr.Slider(5, 40, value=25, step=1, label="Passos")
|
| 194 |
+
edit_scale = gr.Slider(0, 1.5, value=1, step=.05, label="Intensidade LoRA")
|
| 195 |
+
edit_button = gr.Button("Aplicar edição", variant="primary")
|
| 196 |
+
edit_status = gr.Markdown("O resultado depende da imagem, do prompt e da intensidade.")
|
| 197 |
+
edit_bundle = gr.File(label="PNG e receita da edição", interactive=False)
|
| 198 |
+
with gr.Tab("Minha sessão"):
|
| 199 |
+
gr.Markdown("### Seu caderno de experimentos\nAté 24 imagens desta sessão. Selecione uma para consultar parâmetros e baixar arquivos. O histórico é temporário.")
|
| 200 |
+
session_gallery = gr.Gallery(label="Experimentos", columns=4, height=430, interactive=False)
|
| 201 |
+
selected_metadata = gr.JSON(label="Parâmetros")
|
| 202 |
+
with gr.Row():
|
| 203 |
+
selected_png = gr.File(label="PNG", interactive=False)
|
| 204 |
+
selected_json = gr.File(label="JSON", interactive=False)
|
| 205 |
+
with gr.Tab("Pesquisa e documentação"):
|
| 206 |
+
gr.Markdown(training_summary())
|
| 207 |
+
samples = [(str(ROOT / "assets" / p["sample"]), f"Seed {p['seed']} · {p['prompt']}") for p in EVALUATION.get("pairs", []) if (ROOT / "assets" / p["sample"]).is_file()]
|
| 208 |
+
gr.Gallery(value=samples, label="Avaliação publicada · base à esquerda / IGNIS à direita", columns=2, height=500, interactive=False)
|
| 209 |
+
with gr.Accordion("Ler a documentação completa", open=True):
|
| 210 |
+
card = ROOT / "MODEL_CARD.md"
|
| 211 |
+
gr.Markdown(card.read_text(encoding="utf-8") if card.exists() else f"[Model card no Hugging Face](https://huggingface.co/{MODEL_ID})")
|
| 212 |
+
gr.Markdown("Referências de experiência: [FLUX.1 schnell](https://huggingface.co/spaces/black-forest-labs/FLUX.1-schnell) e [Stable Diffusion 3.5 Large](https://huggingface.co/spaces/stabilityai/stable-diffusion-3.5-large). Interface IGNIS própria.")
|
| 213 |
+
controls = [prompt, negative, seed, randomize, size, steps, guidance, scale, model, sampler, preset]
|
| 214 |
+
generate.click(create_images, controls + [count, state], [output, seed, status, bundle, png_download, json_download, state, session_gallery, metadata], concurrency_id="inference", concurrency_limit=1)
|
| 215 |
+
recipe_file.upload(import_recipe, [recipe_file], controls)
|
| 216 |
+
compare_button.click(compare_images, [compare_prompt, compare_negative, compare_seed, compare_size, compare_steps, compare_guidance, compare_scale, compare_sampler, state], [base_output, tuned_output, slider, compare_status, compare_bundle, state, session_gallery], concurrency_id="inference", concurrency_limit=1)
|
| 217 |
+
edit_button.click(edit_image, [edit_prompt, edit_input, edit_mask, edit_mode, strength, edit_seed, edit_steps, edit_scale, state], [edit_output, edit_status, edit_bundle, state, session_gallery], concurrency_id="inference", concurrency_limit=1)
|
| 218 |
+
use_last.click(last_image, [state], [edit_input], queue=False)
|
| 219 |
+
session_gallery.select(gallery_selection, [state], [selected_metadata, selected_png, selected_json], queue=False)
|
| 220 |
+
gr.HTML(f'<div class="ignis-footer"><span>IGNIS · Vinicius de Souza Santos</span><span>Stable Diffusion 1.5 + LoRA · versão {str(RELEASE.get("model_revision", "a configurar"))[:8]}</span></div>')
|
| 221 |
+
return application
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
if __name__ == "__main__":
|
| 225 |
+
demo = build_app()
|
| 226 |
+
demo.queue(default_concurrency_limit=1, max_size=12).launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", "7860")),
|
| 227 |
+
max_file_size="15mb", allowed_paths=[str(OUT), str(ROOT / "assets")])
|
assets/config.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "ignis-image-lora-v1",
|
| 3 |
+
"rank": 8,
|
| 4 |
+
"resolution": 512,
|
| 5 |
+
"batch_size": 1,
|
| 6 |
+
"gradient_accumulation": 4,
|
| 7 |
+
"learning_rate": 0.0001,
|
| 8 |
+
"max_steps": 800,
|
| 9 |
+
"warmup_steps": 50,
|
| 10 |
+
"checkpoint_every": 50,
|
| 11 |
+
"validation_every": 50,
|
| 12 |
+
"patience": 5,
|
| 13 |
+
"min_steps": 300,
|
| 14 |
+
"seed": 42,
|
| 15 |
+
"dataset_fingerprint": "90c1f9c61a6dfa9716dd866880f90b9973131bced5e87872f37bfd30bdf6f999",
|
| 16 |
+
"base_revision": "451f4fe16113bff5a5d2269ed5ad43b0592e9a14"
|
| 17 |
+
}
|
assets/evaluation.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"adapter": "ignis-image-lora-v1/final",
|
| 3 |
+
"adapter_sha256": "f1a2811fbc685bb3059fb43c43c32d44d6ffab51fc5d492e7ff80ec4825f77e5",
|
| 4 |
+
"base_revision": "451f4fe16113bff5a5d2269ed5ad43b0592e9a14",
|
| 5 |
+
"pairs": [
|
| 6 |
+
{
|
| 7 |
+
"prompt": "A detailed oil painting of a quiet garden, soft morning light",
|
| 8 |
+
"seed": 42,
|
| 9 |
+
"sample": "samples/pair-1.png"
|
| 10 |
+
},
|
| 11 |
+
{
|
| 12 |
+
"prompt": "A detailed oil painting of a quiet garden, soft morning light",
|
| 13 |
+
"seed": 2026,
|
| 14 |
+
"sample": "samples/pair-2.png"
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"prompt": "A watercolor landscape with mountains and a lake",
|
| 18 |
+
"seed": 42,
|
| 19 |
+
"sample": "samples/pair-3.png"
|
| 20 |
+
},
|
| 21 |
+
{
|
| 22 |
+
"prompt": "A watercolor landscape with mountains and a lake",
|
| 23 |
+
"seed": 2026,
|
| 24 |
+
"sample": "samples/pair-4.png"
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"prompt": "A still life painting of flowers in a ceramic vase",
|
| 28 |
+
"seed": 42,
|
| 29 |
+
"sample": "samples/pair-5.png"
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"prompt": "A still life painting of flowers in a ceramic vase",
|
| 33 |
+
"seed": 2026,
|
| 34 |
+
"sample": "samples/pair-6.png"
|
| 35 |
+
}
|
| 36 |
+
],
|
| 37 |
+
"note": "Comparação visual pareada. FID/CLIP não calculados; não inferir qualidade apenas pela loss."
|
| 38 |
+
}
|
assets/samples/pair-1.png
ADDED
|
Git LFS Details
|
assets/samples/pair-2.png
ADDED
|
Git LFS Details
|
assets/samples/pair-3.png
ADDED
|
Git LFS Details
|
assets/samples/pair-4.png
ADDED
|
Git LFS Details
|
assets/samples/pair-5.png
ADDED
|
Git LFS Details
|
assets/samples/pair-6.png
ADDED
|
Git LFS Details
|
assets/training.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"step": 550,
|
| 3 |
+
"best_validation_loss": 0.19316272154849554,
|
| 4 |
+
"bad_validations": 5,
|
| 5 |
+
"status": "completed",
|
| 6 |
+
"initial_validation_loss": 0.19390892872719892,
|
| 7 |
+
"last_metrics": {
|
| 8 |
+
"step": 550,
|
| 9 |
+
"train_loss": 0.14198050647974014,
|
| 10 |
+
"lr": 2.500000000000001e-05,
|
| 11 |
+
"validation_loss": 0.19317844051069447
|
| 12 |
+
},
|
| 13 |
+
"elapsed_seconds": 842.06,
|
| 14 |
+
"best_step": 300,
|
| 15 |
+
"stop_reason": "early_stopping_validation",
|
| 16 |
+
"config": {
|
| 17 |
+
"name": "ignis-image-lora-v1",
|
| 18 |
+
"rank": 8,
|
| 19 |
+
"resolution": 512,
|
| 20 |
+
"batch_size": 1,
|
| 21 |
+
"gradient_accumulation": 4,
|
| 22 |
+
"learning_rate": 0.0001,
|
| 23 |
+
"max_steps": 800,
|
| 24 |
+
"warmup_steps": 50,
|
| 25 |
+
"checkpoint_every": 50,
|
| 26 |
+
"validation_every": 50,
|
| 27 |
+
"patience": 5,
|
| 28 |
+
"min_steps": 300,
|
| 29 |
+
"seed": 42,
|
| 30 |
+
"dataset_fingerprint": "90c1f9c61a6dfa9716dd866880f90b9973131bced5e87872f37bfd30bdf6f999",
|
| 31 |
+
"base_revision": "451f4fe16113bff5a5d2269ed5ad43b0592e9a14"
|
| 32 |
+
},
|
| 33 |
+
"interpretation": "Experimento LoRA executado; qualidade visual requer comparação base/adaptador."
|
| 34 |
+
}
|
base_model.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"repo": "stable-diffusion-v1-5/stable-diffusion-v1-5",
|
| 3 |
+
"license": "creativeml-openrail-m",
|
| 4 |
+
"kind": "image",
|
| 5 |
+
"revision": "451f4fe16113bff5a5d2269ed5ad43b0592e9a14",
|
| 6 |
+
"status": "installed",
|
| 7 |
+
"files": [
|
| 8 |
+
"README.md",
|
| 9 |
+
"feature_extractor/preprocessor_config.json",
|
| 10 |
+
"model_index.json",
|
| 11 |
+
"safety_checker/config.json",
|
| 12 |
+
"safety_checker/model.fp16.safetensors",
|
| 13 |
+
"scheduler/scheduler_config.json",
|
| 14 |
+
"text_encoder/config.json",
|
| 15 |
+
"text_encoder/model.fp16.safetensors",
|
| 16 |
+
"tokenizer/merges.txt",
|
| 17 |
+
"tokenizer/special_tokens_map.json",
|
| 18 |
+
"tokenizer/tokenizer_config.json",
|
| 19 |
+
"tokenizer/vocab.json",
|
| 20 |
+
"unet/config.json",
|
| 21 |
+
"unet/diffusion_pytorch_model.fp16.safetensors",
|
| 22 |
+
"vae/config.json",
|
| 23 |
+
"vae/diffusion_pytorch_model.fp16.safetensors"
|
| 24 |
+
],
|
| 25 |
+
"bytes": 2742232091,
|
| 26 |
+
"origin": "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5",
|
| 27 |
+
"installed_at": "2026-10-29T04:24:09.743366+00:00"
|
| 28 |
+
}
|
release.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_id": "ViniciusKhan/ignis-image-lora-v1",
|
| 3 |
+
"base_revision": "451f4fe16113bff5a5d2269ed5ad43b0592e9a14",
|
| 4 |
+
"model_revision": "bdcba88b1d095e95ccbaa6066b48d9d0ca987e59"
|
| 5 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==5.49.1
|
| 2 |
+
spaces
|
| 3 |
+
torch==2.11.0
|
| 4 |
+
diffusers==0.35.1
|
| 5 |
+
transformers==4.57.1
|
| 6 |
+
peft==0.17.1
|
| 7 |
+
accelerate==1.10.1
|
| 8 |
+
huggingface-hub>=0.34,<1
|
| 9 |
+
safetensors>=0.6.2,<1
|
runtime.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Inferência real com pesos publicados e suporte explícito a ZeroGPU."""
|
| 2 |
+
import os
|
| 3 |
+
import threading
|
| 4 |
+
import time
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
ZERO_GPU = os.environ.get("IGNIS_ZERO_GPU") == "1"
|
| 8 |
+
if ZERO_GPU:
|
| 9 |
+
import spaces
|
| 10 |
+
else:
|
| 11 |
+
spaces = None
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
from PIL import ImageOps
|
| 15 |
+
from diffusers import (StableDiffusionPipeline, StableDiffusionImg2ImgPipeline, StableDiffusionInpaintPipeline,
|
| 16 |
+
DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler)
|
| 17 |
+
from settings import BASE_ID, MODEL_ID, RELEASE
|
| 18 |
+
|
| 19 |
+
LOCK = threading.Lock()
|
| 20 |
+
PIPE = EDIT_PIPE = INPAINT_PIPE = SCHEDULER_CONFIG = None
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def gpu(function):
|
| 24 |
+
return spaces.GPU(duration=60)(function) if spaces is not None else function
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def initialize():
|
| 28 |
+
global PIPE, EDIT_PIPE, INPAINT_PIPE, SCHEDULER_CONFIG
|
| 29 |
+
if PIPE is not None:
|
| 30 |
+
return
|
| 31 |
+
if not RELEASE.get("model_revision"):
|
| 32 |
+
raise RuntimeError("Versão do adaptador não configurada. Republique pelo script do projeto.")
|
| 33 |
+
cuda = ZERO_GPU or torch.cuda.is_available()
|
| 34 |
+
local_base = os.environ.get("IGNIS_LOCAL_BASE_PATH") if not ZERO_GPU else None
|
| 35 |
+
local_adapter = os.environ.get("IGNIS_LOCAL_ADAPTER_PATH") if not ZERO_GPU else None
|
| 36 |
+
PIPE = StableDiffusionPipeline.from_pretrained(local_base or BASE_ID,
|
| 37 |
+
revision=None if local_base else RELEASE.get("base_revision"), variant="fp16",
|
| 38 |
+
torch_dtype=torch.float16 if cuda else torch.float32, use_safetensors=True,
|
| 39 |
+
local_files_only=bool(local_base))
|
| 40 |
+
PIPE.load_lora_weights(local_adapter or MODEL_ID, revision=None if local_adapter else RELEASE["model_revision"],
|
| 41 |
+
adapter_name="ignis", weight_name="pytorch_lora_weights.safetensors", local_files_only=bool(local_adapter))
|
| 42 |
+
PIPE.to("cuda" if cuda else "cpu")
|
| 43 |
+
PIPE.enable_vae_slicing()
|
| 44 |
+
SCHEDULER_CONFIG = dict(PIPE.scheduler.config)
|
| 45 |
+
EDIT_PIPE = StableDiffusionImg2ImgPipeline(**PIPE.components)
|
| 46 |
+
INPAINT_PIPE = StableDiffusionInpaintPipeline(**PIPE.components)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def sample(options, mode="text-to-image", image=None, mask=None, strength=.65):
|
| 50 |
+
initialize()
|
| 51 |
+
pipe = PIPE if mode == "text-to-image" else INPAINT_PIPE if mode == "inpainting" else EDIT_PIPE
|
| 52 |
+
scheduler = DPMSolverMultistepScheduler if options["sampler"] == "DPM++ Karras" else EulerAncestralDiscreteScheduler
|
| 53 |
+
pipe.scheduler = scheduler.from_config(SCHEDULER_CONFIG, **({"use_karras_sigmas": True} if scheduler is DPMSolverMultistepScheduler else {}))
|
| 54 |
+
if options["model"] == "IGNIS LoRA":
|
| 55 |
+
pipe.enable_lora()
|
| 56 |
+
pipe.set_adapters("ignis", adapter_weights=options["lora_scale"])
|
| 57 |
+
else:
|
| 58 |
+
pipe.disable_lora()
|
| 59 |
+
args = dict(prompt=options["prompt"], negative_prompt=options["negative_prompt"],
|
| 60 |
+
num_inference_steps=options["steps"], guidance_scale=options["guidance_scale"],
|
| 61 |
+
generator=torch.Generator(device="cpu").manual_seed(options["seed"]),
|
| 62 |
+
width=options["width"], height=options["height"])
|
| 63 |
+
if mode != "text-to-image":
|
| 64 |
+
if image is None or image.width * image.height > 20_000_000:
|
| 65 |
+
raise ValueError("Envie uma imagem inicial de até 20 megapixels.")
|
| 66 |
+
args.update(image=ImageOps.fit(ImageOps.exif_transpose(image).convert("RGB"), (options["width"], options["height"])), strength=float(strength))
|
| 67 |
+
if mode == "image-to-image":
|
| 68 |
+
args.pop("width"); args.pop("height")
|
| 69 |
+
if mode == "inpainting":
|
| 70 |
+
if mask is None:
|
| 71 |
+
raise ValueError("Envie a máscara: branco para editar, preto para preservar.")
|
| 72 |
+
args["mask_image"] = ImageOps.fit(mask.convert("L"), (options["width"], options["height"]))
|
| 73 |
+
with torch.inference_mode():
|
| 74 |
+
result = pipe(**args)
|
| 75 |
+
if result.nsfw_content_detected and any(result.nsfw_content_detected):
|
| 76 |
+
raise ValueError("O filtro de segurança bloqueou a saída. Ajuste o prompt.")
|
| 77 |
+
return result.images[0]
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@gpu
|
| 81 |
+
def generate(options):
|
| 82 |
+
with LOCK:
|
| 83 |
+
start = time.monotonic()
|
| 84 |
+
results = []
|
| 85 |
+
for index in range(options["count"]):
|
| 86 |
+
current = {**options, "seed": (options["seed"] + index) % 2**32}
|
| 87 |
+
results.append((sample(current), {**current, "operation": "text-to-image"}))
|
| 88 |
+
return results, round(time.monotonic() - start, 2)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@gpu
|
| 92 |
+
def compare(options):
|
| 93 |
+
with LOCK:
|
| 94 |
+
start = time.monotonic()
|
| 95 |
+
results = []
|
| 96 |
+
for name in ("Stable Diffusion 1.5", "IGNIS LoRA"):
|
| 97 |
+
current = {**options, "model": name, "operation": "comparison"}
|
| 98 |
+
results.append((sample(current), current))
|
| 99 |
+
return results, round(time.monotonic() - start, 2)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@gpu
|
| 103 |
+
def edit(options, image, mask, mode, strength):
|
| 104 |
+
if mode not in ("image-to-image", "inpainting") or not .1 <= float(strength) <= .95:
|
| 105 |
+
raise ValueError("Modo ou intensidade de edição inválidos.")
|
| 106 |
+
with LOCK:
|
| 107 |
+
start = time.monotonic()
|
| 108 |
+
result = sample(options, mode, image, mask, strength)
|
| 109 |
+
return [(result, {**options, "operation": mode, "edit_strength": float(strength)})], round(time.monotonic() - start, 2)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
if ZERO_GPU:
|
| 113 |
+
# O ZeroGPU prepara os tensores CUDA na inicialização, fora das funções decoradas.
|
| 114 |
+
initialize()
|
settings.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configuração pública e receitas reproduzíveis do IGNIS Image Lab."""
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
ROOT = Path(__file__).resolve().parent
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def document(relative, default=None):
|
| 9 |
+
path = ROOT / relative
|
| 10 |
+
return json.loads(path.read_text(encoding="utf-8")) if path.is_file() else default
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
RELEASE = document("release.json", {})
|
| 14 |
+
MODEL_ID = RELEASE.get("model_id", "ViniciusKhan/ignis-image-lora-v1")
|
| 15 |
+
BASE_ID = "stable-diffusion-v1-5/stable-diffusion-v1-5"
|
| 16 |
+
TRAINING = document("assets/training.json", {})
|
| 17 |
+
CONFIG = document("assets/config.json", {})
|
| 18 |
+
EVALUATION = document("assets/evaluation.json", {})
|
| 19 |
+
SIZES = {"Quadrado · 512 × 512": (512, 512), "Paisagem · 640 × 512": (640, 512), "Retrato · 512 × 640": (512, 640)}
|
| 20 |
+
SAMPLERS = ["DPM++ Karras", "Euler ancestral"]
|
| 21 |
+
PRESETS = {"Sem estilo adicional": "", "Aquarela": "watercolor painting, translucent washes, textured paper, delicate brushwork",
|
| 22 |
+
"Pintura a óleo": "oil painting, expressive brush strokes, detailed composition, natural light",
|
| 23 |
+
"Fotografia": "photograph, natural lighting, realistic materials, detailed composition",
|
| 24 |
+
"Ilustração científica": "scientific illustration, precise shapes, clean composition, white background",
|
| 25 |
+
"Arte conceitual": "concept art, cinematic composition, atmospheric perspective, detailed environment"}
|
| 26 |
+
EXAMPLES = [["A quiet botanical garden at sunrise, a stone path between flowers", "Aquarela"],
|
| 27 |
+
["A mountain lake reflecting the sky, pine trees in the foreground", "Pintura a óleo"],
|
| 28 |
+
["A small observatory on a rocky island under a starry sky", "Arte conceitual"],
|
| 29 |
+
["A detailed botanical study of a fern and its leaves", "Ilustração científica"]]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def recipe(prompt, negative, seed, randomize, size, steps, guidance, lora_scale, model, sampler, preset, count=1):
|
| 33 |
+
import secrets
|
| 34 |
+
if not isinstance(prompt, str) or not prompt.strip():
|
| 35 |
+
raise ValueError("Descreva a imagem antes de gerar.")
|
| 36 |
+
if len(prompt) > 2000 or len(negative or "") > 2000:
|
| 37 |
+
raise ValueError("Use até 2.000 caracteres em cada prompt.")
|
| 38 |
+
if size not in SIZES or sampler not in SAMPLERS or preset not in PRESETS:
|
| 39 |
+
raise ValueError("Selecione resolução, estilo e amostrador válidos.")
|
| 40 |
+
if model not in ("IGNIS LoRA", "Stable Diffusion 1.5"):
|
| 41 |
+
raise ValueError("Modelo desconhecido.")
|
| 42 |
+
seed = secrets.randbelow(2**31) if randomize else int(seed)
|
| 43 |
+
if not 0 <= seed < 2**32 or not 5 <= int(steps) <= 40 or not 1 <= float(guidance) <= 15:
|
| 44 |
+
raise ValueError("Seed, passos ou orientação fora dos limites.")
|
| 45 |
+
if not 0 <= float(lora_scale) <= 1.5 or int(count) not in (1, 2):
|
| 46 |
+
raise ValueError("Use LoRA de 0 a 1,5 e uma ou duas imagens.")
|
| 47 |
+
width, height = SIZES[size]
|
| 48 |
+
effective = prompt.strip() + (", " + PRESETS[preset] if PRESETS[preset] else "")
|
| 49 |
+
return {"prompt": effective, "original_prompt": prompt.strip(), "negative_prompt": negative or "", "seed": seed,
|
| 50 |
+
"width": width, "height": height, "steps": int(steps), "guidance_scale": float(guidance),
|
| 51 |
+
"lora_scale": float(lora_scale), "model": model, "sampler": sampler, "preset": preset, "count": int(count),
|
| 52 |
+
"model_id": MODEL_ID, "model_revision": RELEASE.get("model_revision"),
|
| 53 |
+
"base_model": BASE_ID, "base_revision": RELEASE.get("base_revision")}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def restore_recipe(raw):
|
| 57 |
+
if not raw or len(raw) > 100000:
|
| 58 |
+
raise ValueError("Envie um JSON de receita com até 100 KB.")
|
| 59 |
+
data = json.loads(raw)
|
| 60 |
+
size = next((name for name, dims in SIZES.items() if list(dims) == [data.get("width"), data.get("height")]), None)
|
| 61 |
+
restored = recipe(data.get("prompt", ""), data.get("negative_prompt", ""), data.get("seed", 42), False,
|
| 62 |
+
size, data.get("steps", 25), data.get("guidance_scale", 7.5), data.get("lora_scale", 1),
|
| 63 |
+
data.get("model", "IGNIS LoRA"), data.get("sampler", SAMPLERS[0]), "Sem estilo adicional")
|
| 64 |
+
return restored, size
|
styles.css
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
:root{--ink:#102c49;--blue:#174f73;--cyan:#00a9bd;--line:#dce6ed;--paper:#f5f8fb}body{background:var(--paper)!important}.gradio-container{max-width:1320px!important;margin:auto!important;color:var(--ink)!important;padding:24px!important}.ignis-header{display:flex;align-items:center;justify-content:space-between;padding:12px 0 26px;border-bottom:1px solid var(--line)}.ignis-brand{display:flex;align-items:center;gap:12px;text-decoration:none!important;color:var(--ink)!important;font-family:"Trebuchet MS",sans-serif;font-weight:750;font-size:25px;letter-spacing:1px}.ignis-brand small{font-family:"Segoe UI",sans-serif;font-size:12px;font-weight:400;letter-spacing:.2px;margin-left:8px;color:#647d91}.brand-symbol{background:var(--ink);color:#64dfeb;border-radius:13px;width:43px;height:43px;text-align:center;font-family:Georgia,serif;font-size:39px;font-style:italic;line-height:40px}.release-label{font-size:11px;color:#627e93;padding:8px 12px;border:1px solid var(--line);border-radius:20px}.ignis-hero{display:grid;grid-template-columns:1.4fr 1fr;gap:25px;align-items:center;min-height:290px;padding:35px 0 30px}.ignis-hero h1{font-family:"Trebuchet MS","Segoe UI",sans-serif!important;font-size:clamp(34px,4vw,55px)!important;font-weight:700!important;letter-spacing:-1.9px!important;line-height:1.08!important;margin:0 0 19px!important;color:var(--ink)!important}.ignis-hero p{max-width:410px;font-size:15px;line-height:1.8;color:#71879a}.hero-links{display:flex;gap:23px;margin-top:23px}.hero-links a{font-size:12px;font-weight:650;color:var(--blue)!important;text-decoration:none!important;border-bottom:1px solid #89cdd7;padding-bottom:4px}.hero-art{position:relative;height:235px;border-radius:22px;overflow:hidden;background:#eaf3f8;border:1px solid #dcebf2}.art-square{position:absolute;width:130px;height:130px;border-radius:27px;border:1px solid #91cdd8;transform:rotate(-23deg)}.art-square.one{left:34%;top:37px;background:#c7edf2;box-shadow:16px 18px 0 #ffffff85}.art-square.two{left:20%;top:17px;background:#f7fcfd;transform:rotate(17deg)}.art-square.three{left:48%;top:70px;background:#185878;transform:rotate(13deg);border-color:#1a5d7c;box-shadow:7px 7px 18px #174f7315}.hero-art>span{position:absolute;bottom:19px;left:22px;font-size:10px;color:#577d91;letter-spacing:.5px}.context-bar{font-size:11px!important;color:#698297;margin:0 0 24px!important;padding:12px 16px!important;background:#fff!important;border:1px solid var(--line)!important;border-radius:9px!important}.tabs{border:0!important}.tab-nav{border-bottom:1px solid var(--line)!important;margin-bottom:24px!important;gap:8px!important}.tab-nav button{padding:13px 17px!important;font-size:13px!important;border-radius:9px 9px 0 0!important;color:#667f93!important}.tab-nav button.selected{background:#e8f5f8!important;color:#006e85!important;border-color:#b7e4ec!important;font-weight:650!important}.tabitem{padding:0!important;border:0!important;background:transparent!important}.control-panel{background:#fff!important;padding:24px!important;border:1px solid var(--line)!important;border-radius:14px!important}.result-panel{background:#fff!important;padding:20px!important;border:1px solid var(--line)!important;border-radius:14px!important}.prose h3{color:var(--ink)!important;font-family:"Trebuchet MS","Segoe UI",sans-serif!important;letter-spacing:-.3px!important}.prose p{line-height:1.8!important}.primary{background:var(--ink)!important;border:1px solid var(--ink)!important;box-shadow:none!important;color:white!important}.primary:hover{background:var(--blue)!important}#generate-button{min-height:49px!important;font-size:14px!important;border-radius:9px!important}.block{box-shadow:none!important}textarea,input{border-radius:8px!important}.ignis-footer{display:flex;justify-content:space-between;gap:20px;border-top:1px solid var(--line);margin-top:28px;padding:22px 0 8px;font-size:10px;color:#8396a7}a:focus-visible,button:focus-visible{outline:3px solid #00a9bd66!important;outline-offset:3px}.dark .ignis-hero h1,.dark .ignis-brand{color:#d6edf8!important}.dark body,.dark .gradio-container{background:#0d2032!important}.dark .control-panel,.dark .result-panel,.dark .context-bar{background:#132b40!important;border-color:#294458!important}.dark .prose h3{color:#d6edf8!important}.dark .hero-art{opacity:.85}.dark .primary{background:#14627c!important}.dark .tab-nav button.selected{background:#194459!important;color:#b4f4ff!important}@media(max-width:760px){.gradio-container{padding:14px!important}.ignis-hero{grid-template-columns:1fr;min-height:0;padding:28px 0}.hero-art{display:none}.ignis-header{padding-top:4px}.ignis-brand{font-size:22px}.release-label{font-size:9px}.ignis-hero h1{font-size:37px!important}.ignis-hero p{font-size:13px}.tab-nav{gap:0!important}.tab-nav button{padding:10px!important;font-size:11px!important}.control-panel,.result-panel{padding:16px!important}.ignis-footer{flex-direction:column;gap:7px}}@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;transition:none!important;animation:none!important}}
|