File size: 12,319 Bytes
338d95d |
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 |
#!/usr/bin/env python3
"""
CompI Phase 1.D: Command-Line Quality Evaluation Tool
Command-line interface for batch evaluation and analysis of generated images.
Usage:
python src/generators/compi_phase1d_cli_evaluation.py --help
python src/generators/compi_phase1d_cli_evaluation.py --analyze
python src/generators/compi_phase1d_cli_evaluation.py --batch-score 4 3 4 4 3
"""
import os
import argparse
import json
from datetime import datetime
from pathlib import Path
from typing import Dict, List
import pandas as pd
from PIL import Image
# Import functions from the main evaluation module
from compi_phase1d_evaluate_quality import (
parse_filename, get_image_metrics, load_existing_evaluations,
save_evaluation, EVALUATION_CRITERIA, OUTPUT_DIR, EVAL_CSV
)
def setup_args():
"""Setup command line arguments."""
parser = argparse.ArgumentParser(
description="CompI Phase 1.D: Command-Line Quality Evaluation",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Analyze existing evaluations
python %(prog)s --analyze
# Batch score all unevaluated images (prompt_match, style, mood, quality, appeal)
python %(prog)s --batch-score 4 3 4 4 3 --notes "Batch evaluation - good quality"
# Generate detailed report
python %(prog)s --report --output evaluation_report.txt
# List unevaluated images
python %(prog)s --list-unevaluated
"""
)
parser.add_argument("--output-dir", default=OUTPUT_DIR,
help="Directory containing generated images")
# Analysis commands
parser.add_argument("--analyze", action="store_true",
help="Display evaluation summary and statistics")
parser.add_argument("--report", action="store_true",
help="Generate detailed evaluation report")
parser.add_argument("--output", "-o",
help="Output file for report (default: stdout)")
# Batch evaluation
parser.add_argument("--batch-score", nargs=5, type=int, metavar=("PROMPT", "STYLE", "MOOD", "QUALITY", "APPEAL"),
help="Batch score all unevaluated images (1-5 for each criteria)")
parser.add_argument("--notes", default="CLI batch evaluation",
help="Notes for batch evaluation")
# Listing commands
parser.add_argument("--list-all", action="store_true",
help="List all images with evaluation status")
parser.add_argument("--list-evaluated", action="store_true",
help="List only evaluated images")
parser.add_argument("--list-unevaluated", action="store_true",
help="List only unevaluated images")
# Filtering
parser.add_argument("--style", help="Filter by style")
parser.add_argument("--mood", help="Filter by mood")
return parser.parse_args()
def load_images(output_dir: str) -> List[Dict]:
"""Load and parse all images from output directory."""
if not os.path.exists(output_dir):
print(f"β Output directory '{output_dir}' not found!")
return []
image_files = [f for f in os.listdir(output_dir) if f.lower().endswith('.png')]
parsed_images = []
for fname in image_files:
metadata = parse_filename(fname)
if metadata:
parsed_images.append(metadata)
return parsed_images
def filter_images(images: List[Dict], style: str = None, mood: str = None) -> List[Dict]:
"""Filter images by style and/or mood."""
filtered = images
if style:
filtered = [img for img in filtered if img.get('style', '').lower() == style.lower()]
if mood:
filtered = [img for img in filtered if img.get('mood', '').lower() == mood.lower()]
return filtered
def analyze_evaluations(existing_evals: Dict):
"""Display evaluation analysis."""
if not existing_evals:
print("β No evaluations found.")
return
df = pd.DataFrame.from_dict(existing_evals, orient='index')
print("π CompI Phase 1.D - Evaluation Analysis")
print("=" * 50)
print(f"Total Evaluated Images: {len(df)}")
print()
# Score statistics
print("π Score Statistics:")
for criterion_key, criterion_info in EVALUATION_CRITERIA.items():
if criterion_key in df.columns:
mean_score = df[criterion_key].mean()
std_score = df[criterion_key].std()
min_score = df[criterion_key].min()
max_score = df[criterion_key].max()
print(f" {criterion_info['name']:20}: {mean_score:.2f} Β± {std_score:.2f} (range: {min_score}-{max_score})")
print()
# Style analysis
if 'style' in df.columns and 'prompt_match' in df.columns:
print("π¨ Top Performing Styles (by Prompt Match):")
style_scores = df.groupby('style')['prompt_match'].mean().sort_values(ascending=False)
for style, score in style_scores.head(5).items():
print(f" {style:15}: {score:.2f}")
print()
# Mood analysis
if 'mood' in df.columns and 'creative_appeal' in df.columns:
print("π Top Performing Moods (by Creative Appeal):")
mood_scores = df.groupby('mood')['creative_appeal'].mean().sort_values(ascending=False)
for mood, score in mood_scores.head(5).items():
print(f" {mood:15}: {score:.2f}")
print()
def generate_detailed_report(existing_evals: Dict) -> str:
"""Generate detailed evaluation report."""
if not existing_evals:
return "No evaluations found."
df = pd.DataFrame.from_dict(existing_evals, orient='index')
report_lines = [
"# CompI Phase 1.D - Detailed Evaluation Report",
f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
f"Total Images Evaluated: {len(df)}",
"",
"## Overall Performance Summary"
]
# Overall statistics
for criterion_key, criterion_info in EVALUATION_CRITERIA.items():
if criterion_key in df.columns:
mean_score = df[criterion_key].mean()
std_score = df[criterion_key].std()
report_lines.append(f"- **{criterion_info['name']}**: {mean_score:.2f} Β± {std_score:.2f}")
# Distribution analysis
report_lines.extend([
"",
"## Score Distribution Analysis"
])
for criterion_key, criterion_info in EVALUATION_CRITERIA.items():
if criterion_key in df.columns:
scores = df[criterion_key]
report_lines.extend([
f"",
f"### {criterion_info['name']}",
f"- Mean: {scores.mean():.2f}",
f"- Median: {scores.median():.2f}",
f"- Mode: {scores.mode().iloc[0] if not scores.mode().empty else 'N/A'}",
f"- Range: {scores.min()}-{scores.max()}",
f"- Distribution: " + " | ".join([f"{i}β
: {(scores == i).sum()}" for i in range(1, 6)])
])
# Style/Mood performance
if 'style' in df.columns:
report_lines.extend([
"",
"## Style Performance Analysis"
])
for criterion_key in EVALUATION_CRITERIA.keys():
if criterion_key in df.columns:
style_performance = df.groupby('style')[criterion_key].agg(['mean', 'count']).sort_values('mean', ascending=False)
report_lines.extend([
f"",
f"### {EVALUATION_CRITERIA[criterion_key]['name']} by Style",
])
for style, (mean_score, count) in style_performance.iterrows():
report_lines.append(f"- {style}: {mean_score:.2f} (n={count})")
# Recommendations
report_lines.extend([
"",
"## Recommendations",
"",
"### Areas for Improvement"
])
# Find lowest scoring criteria
criterion_means = {}
for criterion_key, criterion_info in EVALUATION_CRITERIA.items():
if criterion_key in df.columns:
criterion_means[criterion_info['name']] = df[criterion_key].mean()
if criterion_means:
lowest_criteria = sorted(criterion_means.items(), key=lambda x: x[1])[:2]
for criterion_name, score in lowest_criteria:
report_lines.append(f"- Focus on improving **{criterion_name}** (current: {score:.2f}/5)")
report_lines.extend([
"",
"### Best Practices",
"- Continue systematic evaluation for trend analysis",
"- Experiment with parameter adjustments for low-scoring areas",
"- Consider A/B testing different generation approaches",
"- Document successful style/mood combinations for reuse"
])
return "\n".join(report_lines)
def batch_evaluate_images(images: List[Dict], scores: List[int], notes: str, output_dir: str):
"""Batch evaluate unevaluated images."""
existing_evals = load_existing_evaluations()
unevaluated = [img for img in images if img['filename'] not in existing_evals]
if not unevaluated:
print("β
All images are already evaluated!")
return
print(f"π¦ Batch evaluating {len(unevaluated)} images...")
# Map scores to criteria
criteria_keys = list(EVALUATION_CRITERIA.keys())
score_dict = dict(zip(criteria_keys, scores))
for i, img_data in enumerate(unevaluated):
fname = img_data["filename"]
img_path = os.path.join(output_dir, fname)
try:
metrics = get_image_metrics(img_path)
save_evaluation(fname, img_data, score_dict, notes, metrics)
print(f" β
Evaluated: {fname}")
except Exception as e:
print(f" β Error evaluating {fname}: {e}")
print(f"π Batch evaluation completed!")
def list_images(images: List[Dict], existing_evals: Dict, show_evaluated: bool = True, show_unevaluated: bool = True):
"""List images with evaluation status."""
print(f"π Image List ({len(images)} total)")
print("-" * 80)
for img_data in images:
fname = img_data["filename"]
is_evaluated = fname in existing_evals
if (show_evaluated and is_evaluated) or (show_unevaluated and not is_evaluated):
status = "β
" if is_evaluated else "β"
prompt = img_data.get('prompt', 'unknown')[:30]
style = img_data.get('style', 'unknown')[:15]
mood = img_data.get('mood', 'unknown')[:15]
print(f"{status} {fname}")
print(f" Prompt: {prompt}... | Style: {style} | Mood: {mood}")
if is_evaluated:
eval_data = existing_evals[fname]
scores = [f"{k}:{eval_data.get(k, 'N/A')}" for k in EVALUATION_CRITERIA.keys() if k in eval_data]
print(f" Scores: {' | '.join(scores[:3])}...")
print()
def main():
"""Main CLI function."""
args = setup_args()
# Load images
images = load_images(args.output_dir)
if not images:
return
# Apply filters
images = filter_images(images, args.style, args.mood)
# Load existing evaluations
existing_evals = load_existing_evaluations()
# Execute commands
if args.analyze:
analyze_evaluations(existing_evals)
elif args.report:
report = generate_detailed_report(existing_evals)
if args.output:
with open(args.output, 'w', encoding='utf-8') as f:
f.write(report)
print(f"π Report saved to: {args.output}")
else:
print(report)
elif args.batch_score:
batch_evaluate_images(images, args.batch_score, args.notes, args.output_dir)
elif args.list_all:
list_images(images, existing_evals, True, True)
elif args.list_evaluated:
list_images(images, existing_evals, True, False)
elif args.list_unevaluated:
list_images(images, existing_evals, False, True)
else:
print("β No command specified. Use --help for usage information.")
if __name__ == "__main__":
main()
|