-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
335 lines (276 loc) · 11.9 KB
/
cli.py
File metadata and controls
335 lines (276 loc) · 11.9 KB
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
"""
Command Line Interface for Damaged Poster Detection
=================================================
Provides command-line interface for single image processing,
batch processing, and model training.
"""
import click
import os
import json
import logging
from pathlib import Path
from typing import Optional
import sys
from damaged_poster_detector import DamagedPosterDetector, DamageConfig
from train_model import DamageTrainer, TrainingConfig, create_sample_data_structure
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
@click.group()
@click.version_option(version="1.0.0")
def cli():
"""
Damaged Poster Detection System CLI
A production-ready system for detecting damage in poster images
using computer vision and deep learning techniques.
"""
pass
@cli.command()
@click.argument('image_path', type=click.Path(exists=True))
@click.option('--config', '-c', type=click.Path(exists=True),
help='Path to configuration file')
@click.option('--output', '-o', type=click.Path(),
help='Output JSON file for results')
@click.option('--verbose', '-v', is_flag=True,
help='Enable verbose output')
def detect(image_path: str, config: Optional[str],
output: Optional[str], verbose: bool):
"""
Detect damage in a single poster image.
IMAGE_PATH: Path to the poster image to analyze
"""
if verbose:
logging.getLogger().setLevel(logging.DEBUG)
try:
# Initialize detector
detector = DamagedPosterDetector(config_path=config)
click.echo(f"Analyzing image: {image_path}")
# Detect damage
result = detector.detect_damage(image_path)
if 'error' in result:
click.echo(f"Error: {result['error']}", err=True)
sys.exit(1)
# Display results
click.echo("\n" + "="*60)
click.echo("DAMAGE DETECTION RESULTS")
click.echo("="*60)
overall = result['overall_status']
click.echo(f"Overall Status: {'DAMAGED' if overall['damaged'] else 'UNDAMAGED'}")
click.echo(f"Severity: {overall['severity'].upper()}")
click.echo(f"Confidence: {overall['overall_confidence']:.2f}")
click.echo(f"Detected Damage Types: {', '.join(overall['detected_damage_types'])}")
click.echo("\nDetailed Analysis:")
for damage_type, details in result['damage_details'].items():
status = "✓" if details['detected'] else "✗"
click.echo(f" {status} {damage_type.replace('_', ' ').title()}: "
f"{details['confidence']:.3f}")
click.echo("\nRecommendations:")
for i, rec in enumerate(result['recommendations'], 1):
click.echo(f" {i}. {rec}")
# Save to file if requested
if output:
with open(output, 'w') as f:
json.dump(result, f, indent=2, default=str)
click.echo(f"\nResults saved to: {output}")
except Exception as e:
click.echo(f"Error: {str(e)}", err=True)
sys.exit(1)
@cli.command()
@click.argument('input_dir', type=click.Path(exists=True, file_okay=False))
@click.option('--output', '-o', type=click.Path(),
help='Output JSON file for batch results')
@click.option('--config', '-c', type=click.Path(exists=True),
help='Path to configuration file')
@click.option('--pattern', '-p', default='*',
help='File pattern to match (e.g., "*.jpg")')
@click.option('--verbose', '-v', is_flag=True,
help='Enable verbose output')
def batch(input_dir: str, output: Optional[str], config: Optional[str],
pattern: str, verbose: bool):
"""
Process multiple images in batch.
INPUT_DIR: Directory containing images to process
"""
if verbose:
logging.getLogger().setLevel(logging.DEBUG)
try:
# Initialize detector
detector = DamagedPosterDetector(config_path=config)
click.echo(f"Processing images in: {input_dir}")
click.echo(f"File pattern: {pattern}")
# Set default output file if not provided
if not output:
output = f"batch_results_{Path(input_dir).name}.json"
# Process batch
with click.progressbar(label='Processing images') as bar:
results = detector.batch_process(input_dir, output)
bar.update(len(results))
# Summary statistics
total_images = len(results)
damaged_images = sum(1 for r in results if r.get('overall_status', {}).get('damaged', False))
error_count = sum(1 for r in results if 'error' in r)
click.echo(f"\n" + "="*50)
click.echo("BATCH PROCESSING SUMMARY")
click.echo("="*50)
click.echo(f"Total images processed: {total_images}")
click.echo(f"Damaged images found: {damaged_images}")
click.echo(f"Undamaged images: {total_images - damaged_images - error_count}")
click.echo(f"Processing errors: {error_count}")
click.echo(f"Results saved to: {output}")
# Show damage type distribution
damage_counts = {}
for result in results:
if 'overall_status' in result:
for damage_type in result['overall_status'].get('detected_damage_types', []):
damage_counts[damage_type] = damage_counts.get(damage_type, 0) + 1
if damage_counts:
click.echo("\nDamage Type Distribution:")
for damage_type, count in sorted(damage_counts.items()):
click.echo(f" {damage_type.replace('_', ' ').title()}: {count}")
except Exception as e:
click.echo(f"Error: {str(e)}", err=True)
sys.exit(1)
@cli.command()
@click.argument('data_dir', type=click.Path())
@click.option('--config', '-c', type=click.Path(),
help='Path to training configuration file')
@click.option('--epochs', '-e', type=int, default=30,
help='Number of training epochs')
@click.option('--batch-size', '-b', type=int, default=16,
help='Batch size for training')
@click.option('--learning-rate', '-lr', type=float, default=1e-4,
help='Learning rate')
@click.option('--create-structure', is_flag=True,
help='Create sample data directory structure')
@click.option('--wandb', is_flag=True,
help='Use Weights & Biases for experiment tracking')
@click.option('--verbose', '-v', is_flag=True,
help='Enable verbose output')
def train(data_dir: str, config: Optional[str], epochs: int, batch_size: int,
learning_rate: float, create_structure: bool, wandb: bool, verbose: bool):
"""
Train the damage detection model.
DATA_DIR: Directory containing training data organized by damage type
"""
if verbose:
logging.getLogger().setLevel(logging.DEBUG)
try:
# Create data structure if requested
if create_structure:
create_sample_data_structure(data_dir)
click.echo(f"Created sample data structure in: {data_dir}")
click.echo("Please organize your training images and run training again.")
return
# Check if data directory exists and has proper structure
if not os.path.exists(data_dir):
click.echo(f"Data directory not found: {data_dir}")
click.echo("Use --create-structure to create the directory structure.")
sys.exit(1)
# Initialize training configuration
train_config = TrainingConfig(
data_dir=data_dir,
num_epochs=epochs,
batch_size=batch_size,
learning_rate=learning_rate
)
# Load custom config if provided
if config and os.path.exists(config):
import yaml
with open(config, 'r') as f:
config_dict = yaml.safe_load(f)
for key, value in config_dict.items():
if hasattr(train_config, key):
setattr(train_config, key, value)
click.echo("Training Configuration:")
click.echo(f" Data directory: {train_config.data_dir}")
click.echo(f" Epochs: {train_config.num_epochs}")
click.echo(f" Batch size: {train_config.batch_size}")
click.echo(f" Learning rate: {train_config.learning_rate}")
click.echo(f" Use WandB: {wandb}")
# Initialize trainer
trainer = DamageTrainer(train_config)
# Start training
click.echo("\nStarting training...")
trainer.train(data_dir, use_wandb=wandb)
# Plot training history
trainer.plot_training_history()
click.echo("Training completed successfully!")
click.echo(f"Model saved in: {train_config.model_save_path}")
click.echo(f"Logs saved in: {train_config.log_dir}")
except Exception as e:
click.echo(f"Error: {str(e)}", err=True)
sys.exit(1)
@cli.command()
@click.option('--host', default='0.0.0.0', help='Host to bind to')
@click.option('--port', default=8000, help='Port to bind to')
@click.option('--workers', default=1, help='Number of worker processes')
@click.option('--reload', is_flag=True, help='Enable auto-reload for development')
def serve(host: str, port: int, workers: int, reload: bool):
"""
Start the FastAPI web service.
"""
try:
import uvicorn
click.echo(f"Starting web service on {host}:{port}")
click.echo(f"Workers: {workers}")
click.echo(f"Reload: {reload}")
click.echo(f"API docs will be available at: http://{host}:{port}/docs")
uvicorn.run(
"api_service:app",
host=host,
port=port,
workers=workers if not reload else 1,
reload=reload
)
except ImportError:
click.echo("FastAPI and uvicorn are required to run the web service.", err=True)
click.echo("Install with: pip install fastapi uvicorn", err=True)
sys.exit(1)
except Exception as e:
click.echo(f"Error starting service: {str(e)}", err=True)
sys.exit(1)
@cli.command()
@click.option('--format', 'output_format', type=click.Choice(['json', 'table']),
default='table', help='Output format')
def info(output_format: str):
"""
Display system information and configuration.
"""
import torch
import cv2
import numpy as np
info_data = {
"system": {
"python_version": sys.version,
"opencv_version": cv2.__version__,
"numpy_version": np.__version__,
"pytorch_version": torch.__version__,
"cuda_available": torch.cuda.is_available(),
"cuda_version": torch.version.cuda if torch.cuda.is_available() else "N/A",
"gpu_count": torch.cuda.device_count() if torch.cuda.is_available() else 0
},
"damage_types": [
"tear", "crease", "stain", "fade", "burn", "water_damage"
],
"supported_formats": [
"jpg", "jpeg", "png", "bmp", "tiff", "tif"
]
}
if output_format == 'json':
click.echo(json.dumps(info_data, indent=2))
else:
click.echo("System Information:")
click.echo("=" * 50)
for key, value in info_data["system"].items():
click.echo(f" {key.replace('_', ' ').title()}: {value}")
click.echo(f"\nSupported Damage Types:")
for damage_type in info_data["damage_types"]:
click.echo(f" - {damage_type.replace('_', ' ').title()}")
click.echo(f"\nSupported Image Formats:")
for fmt in info_data["supported_formats"]:
click.echo(f" - {fmt.upper()}")
if __name__ == '__main__':
cli()