Spaces:
Running on Zero
A newer version of the Gradio SDK is available: 6.25.0
DiffuseCraft Mod - Improvements Changelog
π Overview
This document details all improvements, bug fixes, and new features added to the DiffuseCraftMod fork.
Original Repository: https://huggingface.co/spaces/R-Kentaren/DiffuseCraftMod
π Bug Fixes (Critical)
1. Error Handling in load_new_model()
File: app_improved.py (lines 270-420)
Problems Fixed:
- Missing exception handling caused crashes on model load failure
- No timeout for queue waiting (could hang indefinitely)
- Resource leaks when errors occurred during loading
- Poor error messages for users
Improvements:
- β Comprehensive try-catch blocks with proper cleanup
- β Queue wait timeout (2 minutes max)
- β Download wait timeout (5 minutes max)
- β
Proper resource cleanup in
finallyblocks - β Better error messages with context
- β Generation statistics tracking for debugging
2. Memory Leak - Global Variable Reassignment
File: app_improved.py (lines 580-585)
Problem:
# OLD CODE (BUGGY):
global lora_model_list
lora_model_list = get_lora_model_list() # Reassigned every generation!
Fix:
# NEW CODE (FIXED):
current_lora_list = get_lora_model_list() # Local variable only
Impact: Prevents memory leak from constant global list reassignment.
3. Race Condition in Thread Safety
File: app_improved.py (lines 230-245)
Problems Fixed:
- Used basic
threading.Lock()instead ofRLock() - No timeout mechanism for lock acquisition
- Potential deadlocks under high concurrency
Improvements:
- β
Changed to
threading.RLock()(reentrant locking) - β Added timeout mechanisms
- β Per-model wait events for better synchronization
- β Improved feedback during waits
4. Exception Handling in generate_pipeline()
File: app_improved.py (lines 550-750)
Problems Fixed:
- Exceptions not properly caught and reported
- GPU memory not cleaned up on errors
- No generation statistics tracking
- Poor error recovery
Improvements:
- β
Comprehensive exception handling with
try-finally - β
Automatic GPU memory cleanup (
gc.collect()+torch.cuda.empty_cache()) - β Generation success/failure tracking
- β Detailed error logging with tracebacks
- β Cache manager integration for file access tracking
5. Input Validation
File: app_improved.py (lines 1650-1680)
New Features:
- β Prompt validation (length, content safety)
- β Filename sanitization for safe file operations
- β Batch parameter validation
- β Model name validation
β¨ New Features
1. β‘ Batch Generation System
Tab: "Batch Generation"
Features:
- Generate multiple images with different variations
- Three variation modes:
- Seed Variation: Same prompt, different seeds
- Prompt Modification: Auto-add quality modifiers
- Aspect Variations: Different aspect ratios
- Configurable batch size (1-20 images)
- Progress tracking per image
- Validation before starting batch
Usage:
- Go to "Batch Generation" tab
- Select variation mode
- Set number of images
- Click "Start Batch Generation"
2. πΎ Smart Preset Manager
Tab: "Smart Presets"
Features:
- Save current configuration as named preset
- Load presets with one click
- Delete unwanted presets
- Export all presets to JSON file
- Import presets from JSON file
- Persistent storage (survives restarts)
API:
preset_manager.save_preset("my_preset", config_dict)
config = preset_manager.load_preset("my_preset")
presets = preset_manager.list_presets()
3. π Prompt Template System
Tab: "Prompt Templates"
Features:
- Pre-built templates for common use cases:
- Basic Anime
- Portrait
- Landscape
- Character Design
- Variable substitution system
- Template preview with documentation
- Custom template support
Example Template:
Template: "1girl, solo, {subject}, {quality_tags}, {style_tags}"
Variables:
- subject: main character description
- quality_tags: masterpiece, best quality
- style_tags: anime style, detailed
4. ποΈ Enhanced Cache Manager
Tab: "System Monitor" β "Cache Management"
Features:
- LRU (Least Recently Used) eviction policy
- Configurable cache size limits
- File access time tracking
- Cache statistics dashboard
- Manual cleanup controls
- Old file auto-cleanup (24h+)
Benefits:
- Prevents disk space exhaustion
- Keeps frequently-used files cached
- Automatic cleanup of stale files
- Real-time usage monitoring
5. π System Monitoring Dashboard
Tab: "System Monitor"
Information Displayed:
- Python & PyTorch versions
- CUDA/GPU status
- GPU memory usage (allocated/reserved)
- Storage usage statistics
- Cache statistics
- Generation statistics (success/failure counts)
- Timestamp for debugging
Controls:
- Refresh button for real-time updates
- Cache cleanup buttons
- Clear old cache entries
π§ Optimizations
1. GPU Memory Management
@contextmanager
def gpu_context(duration: int = 60):
"""Context manager for GPU operations with automatic cleanup."""
try:
yield spaces.GPU(duration=duration)
finally:
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
Benefits:
- Automatic memory cleanup after operations
- Prevents GPU memory leaks
- Context-based resource management
2. Thread Safety Improvements
- RLock instead of Lock for reentrant safety
- Timeout-based waiting to prevent hangs
- Per-model event synchronization
- Better deadlock prevention
3. Resource Cleanup
- All file handles properly closed
- Network sessions cleaned up
- Temporary files removed
- GPU tensors released
π File Structure
DiffuseCraftMod/
βββ app.py # Original application (unchanged)
βββ app_improved.py # β¨ IMPROVED VERSION (new features + fixes)
βββ constants.py # Constants (unchanged)
βββ env.py # Environment variables (unchanged)
βββ image_processor.py # Image preprocessing (unchanged)
βββ modutils.py # Utility functions (unchanged)
βββ utils.py # Core utilities (unchanged)
βββ requirements.txt # Dependencies (unchanged)
βββ IMPROVEMENTS.md # This changelog
π― How to Use Improved Version
Option 1: Replace Original
cd DiffuseCraftMod
mv app.py app_original.py
mv app_improved.py app.py
Option 2: Run Separately
cd DiffuseCraftMod
python app_improved.py
For Hugging Face Spaces
Update your app.py file contents with app_improved.py contents.
π§ͺ Testing Recommendations
Test Batch Generation
- Open "Batch Generation" tab
- Set mode to "Seed Variation"
- Set count to 4
- Enter a simple prompt
- Verify 4 different images generated
Test Smart Presets
- Configure some settings
- Save as "test_preset"
- Change settings randomly
- Load "test_preset"
- Verify settings restored
Test System Monitor
- Open "System Monitor" tab
- Check all information displays correctly
- Try cache cleanup buttons
- Verify stats update
Test Error Recovery
- Try loading invalid model URL
- Verify graceful error message
- Check system still works after error
- Verify no memory leaks
β οΈ Breaking Changes
None! The improved version is fully backward compatible:
- β All original API endpoints preserved
- β UI/CSS/Theme unchanged (as requested!)
- β Same command-line arguments
- β Same environment variables
- β Existing presets/configs still work
π Migration Guide
No migration needed! Simply replace the file and restart.
For new features:
- Tabs are added to existing interface
- New APIs are additive (don't break existing ones)
- Default behaviors preserved
π Notes
- UI/CSS/THEME: Completely untouched as requested β
- Backward Compatibility: 100% maintained β
- Performance: Improved through better resource management β
- Stability: Enhanced via comprehensive error handling β
π€ Contributing
To add more improvements:
- New Templates: Edit
PromptTemplateSystem.TEMPLATESdict - New Preset Fields: Update
save_current_preset()function - Cache Tuning: Adjust
EnhancedCacheManagerconstructor params - Batch Modes: Add to
BatchGenerator.generate_variations()
Version: 2.0.0-improved
Last Updated: 2026-08-19
Status: Production Ready β