Spaces:
Running
Running
File size: 12,780 Bytes
5f3e9f5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 | # Additional Features Documentation
This document describes five additional features implemented in Screenshot Studio.
## 1. HTML Beautifier
Auto-format messy HTML code with proper indentation and structure.
### Features:
- **Beautify**: Format HTML with proper indentation
- **Minify**: Remove unnecessary whitespace
- **Validate**: Check for common HTML issues
### Usage:
**Via API:**
```bash
# Beautify HTML
POST /beautify
Body: { "html": "<div><p>Hello</p></div>" }
# Minify HTML
POST /minify
Body: { "html": "<div> <p> Hello </p> </div>" }
```
**Programmatic:**
```python
from utils.html_beautifier import HTMLBeautifier
beautifier = HTMLBeautifier(indent_size=2)
# Beautify
formatted = beautifier.beautify(messy_html)
# Minify
minified = beautifier.minify(html_content)
# Validate
validation = beautifier.validate(html_content)
print(validation['valid']) # True/False
print(validation['issues']) # List of issues
```
### API Response:
```json
{
"success": true,
"html": "formatted HTML",
"validation": {
"valid": true,
"issues": [],
"tag_count": 15
}
}
```
### Features:
- Proper indentation (configurable)
- Handles inline vs block elements
- Preserves self-closing tags
- Validates tag balance
- Checks for required HTML structure
## 2. Performance Metrics
Track and display load time, render time, and other performance metrics.
### Tracked Metrics:
- **Total Duration**: Complete operation time
- **AI Processing Time**: Time for AI response
- **Screenshot Generation Time**: Time to create screenshots
- **Tokens Per Second**: AI processing speed
- **File Sizes**: Individual and total screenshot sizes
- **Screenshots Per Second**: Generation rate
### Usage:
**Automatic Tracking:**
All `/generate` requests automatically track performance metrics.
**API Endpoints:**
```bash
# Get metrics for specific operation
GET /metrics/{operation_id}
# Response includes:
{
"operation_id": "generate_1234567890",
"duration": "5.2s",
"duration_ms": 5234.56,
"status": "success",
"start_time": "2024-03-04T10:30:00",
"end_time": "2024-03-04T10:30:05",
"metadata": {
"screenshot_count": 3,
"total_size_kb": 1024.5,
"avg_time_per_screenshot": 1.2
}
}
```
**Programmatic:**
```python
from utils.performance_metrics import metrics_tracker
# Start tracking
metrics_tracker.start('my_operation')
# ... do work ...
# End tracking
metrics_tracker.end('my_operation', success=True, metadata={
'custom_data': 'value'
})
# Get metrics
metrics = metrics_tracker.get_metrics('my_operation')
summary = metrics_tracker.get_summary('my_operation')
```
### Display in UI:
Performance metrics are automatically displayed after screenshot generation:
- Total Time
- AI Processing Time
- Screenshot Generation Time
## 3. Progress Indicators
Real-time progress bars with ETA for long-running operations.
### Features:
- **Visual Progress Bar**: Animated progress indicator
- **Percentage Display**: Current progress percentage
- **ETA Calculation**: Estimated time remaining
- **Stage Messages**: Current operation stage
- **Smooth Animations**: Professional transitions
### Usage:
**JavaScript:**
```javascript
// Start progress tracking
progressTracker.start([
'Sending request to AI...',
'Generating HTML...',
'Creating screenshots...',
'Finalizing...'
]);
// Update progress
progressTracker.updateProgress(50, 'Processing...');
// Move to next stage
progressTracker.nextStage();
// Complete
progressTracker.complete('Done!');
// Reset
progressTracker.reset();
```
### UI Elements:
- Progress bar with smooth fill animation
- Percentage text (0-100%)
- ETA display (e.g., "ETA: 15s" or "ETA: 2m 30s")
- Stage message (e.g., "Creating screenshots...")
### Automatic Integration:
Progress tracking is automatically integrated into the text-to-image generation workflow.
## 4. Notification System
Desktop notifications when jobs complete, with in-app toast notifications.
### Features:
- **Desktop Notifications**: Native OS notifications
- **Toast Notifications**: In-app notification toasts
- **Multiple Types**: Success, error, info
- **Auto-dismiss**: Configurable duration
- **Manual Close**: Click to dismiss
- **Permission Request**: Automatic permission handling
### Usage:
**JavaScript:**
```javascript
// Success notification
notificationManager.success(
'Generation Complete!',
'Created 5 screenshots in 3.2s'
);
// Error notification
notificationManager.error(
'Generation Failed',
'API request timed out'
);
// Info notification
notificationManager.info(
'Processing',
'Your request is being processed'
);
// Custom notification
notificationManager.show(
'Custom Title',
'Custom message',
'success', // type: success, error, info
5000 // duration in ms (0 = no auto-close)
);
// Close notification
notificationManager.close(notificationId);
```
### Notification Types:
**Success:**
- Green accent color
- Checkmark icon
- Default duration: 5 seconds
**Error:**
- Red accent color
- X icon
- Default duration: 7 seconds
**Info:**
- Blue accent color
- Info icon
- Default duration: 5 seconds
### Desktop Notifications:
- Requires user permission (requested automatically)
- Shows even when browser is minimized
- Native OS notification style
- Includes app icon
### Toast Notifications:
- Bottom-right corner
- Slide-in animation
- Click to dismiss
- Auto-dismiss after duration
- Multiple notifications stack
## 5. Automatic Cleanup
Delete old files after 7 days to save disk space.
### Features:
- **Scheduled Cleanup**: Daily at 2:00 AM
- **Configurable Age**: Default 7 days
- **Dry Run Mode**: Preview before deleting
- **Statistics**: Track deleted files and space freed
- **Multiple Directories**: Clean screenshots and HTML
- **Error Handling**: Graceful failure handling
### Usage:
**Run Cleanup Scheduler:**
```bash
python cleanup_scheduler.py
```
This starts a background process that:
- Runs cleanup daily at 2:00 AM
- Deletes files older than 7 days
- Logs all operations
- Continues running until stopped (Ctrl+C)
**API Endpoints:**
```bash
# Preview cleanup (dry run)
POST /cleanup/preview
Body: { "max_age_days": 7 }
# Execute cleanup
POST /cleanup/execute
Body: { "max_age_days": 7 }
# Get directory statistics
GET /cleanup/stats
```
**Programmatic:**
```python
from utils.file_cleanup import file_cleanup
# Preview cleanup
result = file_cleanup.schedule_cleanup(
['output/screenshots', 'output/html'],
max_age_days=7
)
# Execute cleanup
result = file_cleanup.cleanup_multiple_directories(
['output/screenshots', 'output/html'],
max_age_days=7,
dry_run=False
)
# Get directory stats
stats = file_cleanup.get_directory_stats('output/screenshots')
print(f"Total files: {stats['file_count']}")
print(f"Total size: {stats['total_size_mb']} MB")
```
### Cleanup Response:
```json
{
"results": {
"output/screenshots": {
"success": true,
"deleted_count": 15,
"deleted_size_mb": 12.5,
"kept_count": 5,
"errors": []
}
},
"total_deleted": 15,
"total_size_mb": 12.5
}
```
### Configuration:
**Change Cleanup Age:**
```python
# In cleanup_scheduler.py
run_cleanup(max_age_days=14) # Keep files for 14 days
```
**Change Schedule:**
```python
# In cleanup_scheduler.py
schedule.every().day.at("03:00").do(run_cleanup) # Run at 3 AM
schedule.every().week.do(run_cleanup) # Run weekly
```
**Add More Directories:**
```python
directories = [
'output/screenshots',
'output/html',
'output/cache' # Add cache cleanup
]
```
## Integration Examples
### Example 1: Complete Workflow with All Features
```javascript
// Start progress
progressTracker.start([
'Preparing request...',
'Processing with AI...',
'Generating screenshots...',
'Applying watermarks...',
'Complete!'
]);
try {
// Generate with beautified HTML
const response = await fetch('/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: "My content",
beautify_html: true,
watermark_text: "© 2024",
resolution_preset: "desktop-fhd"
})
});
const data = await response.json();
// Complete progress
progressTracker.complete('Done!');
// Show success notification
notificationManager.success(
'Screenshots Generated!',
`Created ${data.screenshot_count} files in ${data.performance.total_time}`
);
// Display performance metrics
console.log('Performance:', data.performance);
} catch (error) {
progressTracker.reset();
notificationManager.error('Error', error.message);
}
```
### Example 2: Scheduled Cleanup with Notifications
```python
import schedule
from utils.file_cleanup import file_cleanup
def cleanup_with_notification():
result = file_cleanup.cleanup_multiple_directories(
['output/screenshots', 'output/html'],
max_age_days=7
)
print(f"Cleaned up {result['total_deleted']} files")
print(f"Freed {result['total_size_mb']:.2f} MB")
# Schedule daily cleanup
schedule.every().day.at("02:00").do(cleanup_with_notification)
while True:
schedule.run_pending()
time.sleep(60)
```
### Example 3: Beautify Before Preview
```javascript
async function previewWithBeautify() {
const html = document.getElementById('htmlInput').value;
// Beautify first
const beautifyResponse = await fetch('/beautify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ html })
});
const beautified = await beautifyResponse.json();
if (beautified.validation.valid) {
// Show preview
showPreview(beautified.html);
notificationManager.success('HTML Valid', 'No issues found');
} else {
notificationManager.error(
'HTML Issues',
beautified.validation.issues.join(', ')
);
}
}
```
## Configuration
### HTML Beautifier Settings:
```python
# src/utils/html_beautifier.py
beautifier = HTMLBeautifier(indent_size=4) # Change indentation
```
### Performance Metrics Settings:
```python
# src/utils/performance_metrics.py
# Metrics are automatically tracked, no configuration needed
```
### Progress Tracker Settings:
```javascript
// static/js/notifications.js
// Customize stages in your code
progressTracker.start([
'Custom stage 1',
'Custom stage 2',
'Custom stage 3'
]);
```
### Notification Settings:
```javascript
// static/js/notifications.js
// Customize durations
notificationManager.success('Title', 'Message', 10000); // 10 seconds
```
### Cleanup Settings:
```python
# cleanup_scheduler.py
file_cleanup = FileCleanup(max_age_days=14) # Change default age
```
## Troubleshooting
### HTML Beautifier Issues:
- **Malformed HTML**: Beautifier may not fix severely broken HTML
- **Custom Tags**: May not recognize custom web components
- **Solution**: Validate HTML first, fix critical issues manually
### Performance Metrics Not Showing:
- **Check operation_id**: Ensure you're using the correct ID
- **Check response**: Verify metrics are in the response
- **Solution**: Check browser console for errors
### Progress Bar Not Updating:
- **Check element IDs**: Ensure HTML elements exist
- **Check JavaScript**: Verify notifications.js is loaded
- **Solution**: Check browser console for errors
### Notifications Not Appearing:
- **Desktop**: Check browser notification permissions
- **Toast**: Verify CSS is loaded correctly
- **Solution**: Grant notification permission in browser settings
### Cleanup Not Running:
- **Scheduler**: Ensure cleanup_scheduler.py is running
- **Permissions**: Check file write permissions
- **Solution**: Run manually first to test: `python cleanup_scheduler.py`
## Performance Impact
- **HTML Beautifier**: ~10-50ms per operation
- **Performance Metrics**: <1ms overhead
- **Progress Indicators**: Negligible (UI only)
- **Notifications**: <1ms per notification
- **Automatic Cleanup**: Runs in background, no impact on main app
## Best Practices
1. **HTML Beautifier**: Use for user-generated HTML, not AI-generated (already formatted)
2. **Performance Metrics**: Monitor for optimization opportunities
3. **Progress Indicators**: Use for operations >2 seconds
4. **Notifications**: Don't spam users with too many notifications
5. **Cleanup**: Adjust age based on your storage capacity
## Future Enhancements
- HTML beautifier presets (compact, expanded, etc.)
- Performance metrics dashboard
- Progress bar customization
- Notification sound effects
- Cleanup scheduling UI
- Cleanup by file size threshold
- Export performance reports
|