forked from chenhaoxing/DiffUTE
-
Notifications
You must be signed in to change notification settings - Fork 0
feat: attempted a rewrite #2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
pgryko
wants to merge
2
commits into
main
Choose a base branch
from
attempt_rewrite
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,12 @@ | ||
| accelerate>=0.16.0 | ||
| torchvision | ||
| transformers>=4.25.1 | ||
| datasets | ||
| ftfy | ||
| tensorboard | ||
| Jinja2 | ||
| torch>=2.0.0 | ||
| accelerate>=0.20.0 | ||
| transformers>=4.30.0 | ||
| diffusers>=0.15.0 | ||
| albumentations>=1.3.0 | ||
| opencv-python>=4.7.0 | ||
| pandas>=2.0.0 | ||
| numpy>=1.24.0 | ||
| Pillow>=9.5.0 | ||
| tqdm>=4.65.0 | ||
| minio>=7.1.0 | ||
| scikit-image>=0.20.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,168 @@ | ||
| # Using Stable Diffusion for Text Inpainting | ||
|
|
||
| This guide explains how to use Stable Diffusion's inpainting capability to add text to specific regions in an image. While not as specialized as DiffUTE for text editing, this approach can still achieve decent results. | ||
|
|
||
| ## Requirements | ||
|
|
||
| ```python | ||
| pip install diffusers transformers torch | ||
| ``` | ||
|
|
||
| ## Basic Implementation | ||
|
|
||
| ```python | ||
| import torch | ||
| from diffusers import StableDiffusionInpaintPipeline | ||
| from PIL import Image, ImageDraw | ||
| import numpy as np | ||
|
|
||
| def create_text_mask(image, text_box): | ||
| """Create a binary mask for the text region | ||
|
|
||
| Args: | ||
| image: PIL Image | ||
| text_box: tuple of (x1, y1, x2, y2) coordinates | ||
| """ | ||
| mask = Image.new("RGB", image.size, "black") | ||
| draw = ImageDraw.Draw(mask) | ||
| draw.rectangle(text_box, fill="white") | ||
| return mask | ||
|
|
||
| # Load the model | ||
| model_id = "stabilityai/stable-diffusion-2-inpainting" | ||
| pipe = StableDiffusionInpaintPipeline.from_pretrained( | ||
| model_id, | ||
| torch_dtype=torch.float16, | ||
| ) | ||
| pipe = pipe.to("cuda") | ||
|
|
||
| # Load your image | ||
| image = Image.open("your_image.png") | ||
|
|
||
| # Define the text region (x1, y1, x2, y2) | ||
| text_box = (100, 100, 300, 150) # Example coordinates | ||
|
|
||
| # Create the mask | ||
| mask = create_text_mask(image, text_box) | ||
|
|
||
| # Generate the inpainting | ||
| prompt = "Clear black text saying 'Hello World' on a white background" | ||
| negative_prompt = "blurry, unclear text, multiple texts, watermark" | ||
|
|
||
| result = pipe( | ||
| prompt=prompt, | ||
| negative_prompt=negative_prompt, | ||
| image=image, | ||
| mask_image=mask, | ||
| num_inference_steps=50, | ||
| guidance_scale=7.5, | ||
| ).images[0] | ||
| ``` | ||
|
|
||
| ## Tips for Better Results | ||
|
|
||
| 1. **Mask Preparation**: | ||
| - Make the mask slightly larger than the text area | ||
| - Use anti-aliasing on mask edges for smoother blending | ||
| - Consider the text baseline and x-height in mask creation | ||
|
|
||
| 2. **Prompt Engineering**: | ||
| - Be specific about text style: "sharp, clear black text" | ||
| - Mention text properties: "centered, serif font" | ||
| - Include context: "text on a white background" | ||
|
|
||
| 3. **Negative Prompts**: | ||
| - "blurry, unclear text" | ||
| - "multiple texts, overlapping text" | ||
| - "watermark, artifacts" | ||
| - "distorted, warped text" | ||
|
|
||
| 4. **Parameter Tuning**: | ||
| ```python | ||
| # For clearer text | ||
| result = pipe( | ||
| prompt=prompt, | ||
| negative_prompt=negative_prompt, | ||
| image=image, | ||
| mask_image=mask, | ||
| num_inference_steps=50, # More steps for better quality | ||
| guidance_scale=7.5, # Higher for more prompt adherence | ||
| strength=0.8, # Control how much to change | ||
| ).images[0] | ||
| ``` | ||
|
|
||
| ## Advanced Usage | ||
|
|
||
| ### 1. Style Matching | ||
|
|
||
| To match existing text styles in the image: | ||
|
|
||
| ```python | ||
| def match_text_style(image, text_region): | ||
| """Analyze existing text style in the image""" | ||
| # Add OCR or style analysis here | ||
| return "style_description" | ||
|
|
||
| style = match_text_style(image, text_region) | ||
| prompt = f"Text saying 'Hello World' in style: {style}" | ||
| ``` | ||
|
|
||
| ### 2. Context-Aware Masking | ||
|
|
||
| ```python | ||
| def create_context_mask(image, text_box, padding=10): | ||
| """Create a mask with context awareness""" | ||
| x1, y1, x2, y2 = text_box | ||
| padded_box = (x1-padding, y1-padding, x2+padding, y2+padding) | ||
| mask = create_text_mask(image, padded_box) | ||
| return mask | ||
| ``` | ||
|
|
||
| ### 3. Multiple Attempts | ||
|
|
||
| ```python | ||
| def generate_multiple_attempts(pipe, image, mask, prompt, num_attempts=3): | ||
| """Generate multiple versions and pick the best""" | ||
| results = [] | ||
| for _ in range(num_attempts): | ||
| result = pipe( | ||
| prompt=prompt, | ||
| image=image, | ||
| mask_image=mask, | ||
| num_inference_steps=50, | ||
| ).images[0] | ||
| results.append(result) | ||
| return results | ||
| ``` | ||
|
|
||
| ## Limitations | ||
|
|
||
| 1. Less precise text control compared to DiffUTE | ||
| 2. May require multiple attempts to get desired results | ||
| 3. Text style matching is less reliable | ||
| 4. May introduce artifacts around text regions | ||
|
|
||
| ## Best Practices | ||
|
|
||
| 1. **Preparation**: | ||
| - Clean the text region thoroughly | ||
| - Create precise masks | ||
| - Use high-resolution images | ||
|
|
||
| 2. **Generation**: | ||
| - Start with lower strength values | ||
| - Generate multiple variations | ||
| - Use detailed prompts | ||
|
|
||
| 3. **Post-processing**: | ||
| - Check text clarity and alignment | ||
| - Verify style consistency | ||
| - Touch up edges if needed | ||
|
|
||
| ## When to Use DiffUTE Instead | ||
|
|
||
| Consider using DiffUTE when: | ||
| - Precise text style matching is crucial | ||
| - Multiple text regions need editing | ||
| - Text needs to perfectly match surrounding context | ||
| - Working with complex backgrounds | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| """Text inpainting package using Stable Diffusion.""" | ||
|
|
||
| from .text_inpainter import TextInpainter | ||
| from .utils.mask_utils import ( | ||
| create_text_mask, | ||
| create_context_mask, | ||
| create_antialiased_mask, | ||
| ) | ||
| from .utils.style_utils import TextStyleAnalyzer, generate_style_prompt | ||
|
|
||
| __version__ = "0.1.0" | ||
| __all__ = [ | ||
| "TextInpainter", | ||
| "create_text_mask", | ||
| "create_context_mask", | ||
| "create_antialiased_mask", | ||
| "TextStyleAnalyzer", | ||
| "generate_style_prompt", | ||
| ] |
Binary file added
BIN
+5.05 KB
stable_diffusion_text_inpaint/__pycache__/text_inpainter.cpython-311.pyc
Binary file not shown.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Replace placeholder function with actual implementation.
The
match_text_stylefunction is defined but only contains a placeholder comment. Consider implementing this function with a concrete example that uses theTextStyleAnalyzerfrom the relatedutils.style_utilsmodule, as referenced in the relevant code snippets.def match_text_style(image, text_region): """Analyze existing text style in the image""" - # Add OCR or style analysis here - return "style_description" + from stable_diffusion_text_inpaint.utils.style_utils import TextStyleAnalyzer, generate_style_prompt + + # Initialize style analyzer + analyzer = TextStyleAnalyzer() + + # Analyze the region + style_props = analyzer.analyze_text_region(image, text_region) + + # Generate a descriptive prompt + return generate_style_prompt(style_props)📝 Committable suggestion