File size: 12,911 Bytes
522bf24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Batch image evaluation tool with YAML configuration."""

import requests
import pickle
from PIL import Image
from typing import List, Dict, Any, Union, Optional, Tuple
import sys
import os
import json
import yaml
from io import BytesIO
from tqdm import tqdm
from datetime import datetime


PAIR_SCORERS = {"editreward"}
CAPTION_SUFFIXES = ["_caption.txt", "_prompt.txt"]


class RewardEvaluatorClient:
    def __init__(self, scorer_urls: Dict[str, str]):
        self.scorer_urls = scorer_urls

    def evaluate(self, 
                 model_name: str, 
                 images: Union[List[Image.Image], Dict[str, List[Image.Image]]], 
                 prompts: List[str], 
                 metadata: Dict[str, Any] = None) -> Union[List[float], Dict[str, Any]]:
        url = self.scorer_urls.get(model_name)
        if not url:
            raise ValueError(f"Reward model '{model_name}' URL not configured.")

        payload_bytes = create_payload(images, prompts, metadata)

        try:
            response = requests.post(url, data=payload_bytes, timeout=600)
            response.raise_for_status()
            result = parse_response(response.content)
            
            if isinstance(result, dict) and "error" in result:
                raise RuntimeError(f"Scorer '{model_name}' returned error: {result['error']}")
            
            return result

        except requests.exceptions.RequestException as e:
            raise RuntimeError(f"HTTP request to '{model_name}' failed: {e}")
        except Exception as e:
            raise RuntimeError(f"Failed to process response from '{model_name}': {e}")


def serialize_images(images: List[Image.Image]) -> List[bytes]:
    images_bytes = []
    for img in images:
        img_byte_arr = BytesIO()
        if img.mode != 'RGB':
            img = img.convert('RGB')
        img.save(img_byte_arr, format="JPEG")
        images_bytes.append(img_byte_arr.getvalue())
    return images_bytes


def create_payload(images: Union[List[Image.Image], Dict[str, List[Image.Image]]], 
                   prompts: List[str], 
                   metadata: Dict[str, Any] = None) -> bytes:
    if isinstance(images, dict):
        serialized_images = {key: serialize_images(value) for key, value in images.items()}
    else:
        serialized_images = serialize_images(images)
    
    return pickle.dumps({
        "images": serialized_images,
        "prompts": prompts,
        "metadata": metadata or {}
    })


def parse_response(response_content: bytes) -> Union[List[float], Dict[str, Any]]:
    return pickle.loads(response_content)


def find_caption_file(base_path: str, base_name: str) -> Optional[str]:
    for suffix in CAPTION_SUFFIXES:
        caption_path = os.path.join(base_path, f"{base_name}{suffix}")
        if os.path.exists(caption_path):
            return caption_path
    return None


def collect_standard_samples(folder_path: str) -> Tuple[List[Image.Image], List[str], List[str]]:
    images, prompts, filenames = [], [], []
    
    for file in sorted(os.listdir(folder_path)):
        if not file.lower().endswith(('.png', '.jpg', '.jpeg')):
            continue
        if any(suffix in file for suffix in ['_edited', '_reference', '_source']):
            continue
            
        base_name = os.path.splitext(file)[0]
        img_path = os.path.join(folder_path, file)
        caption_path = find_caption_file(folder_path, base_name)
        
        if not caption_path:
            continue
        
        try:
            img = Image.open(img_path)
            with open(caption_path, 'r', encoding='utf-8') as f:
                prompt = f.read().strip()
            images.append(img)
            prompts.append(prompt)
            filenames.append(file)
        except Exception as e:
            print(f"  Warning: Failed to process {file}: {e}")
    
    return images, prompts, filenames


def collect_edit_samples(folder_path: str) -> Tuple[Dict[str, List[Image.Image]], List[str], List[str]]:
    source_images, edited_images, prompts, filenames = [], [], [], []
    
    edited_files = [f for f in os.listdir(folder_path) if f.endswith('_edited.png')]
    
    for edited_file in sorted(edited_files):
        base_name = edited_file.replace('_edited.png', '')
        source_file = f"{base_name}_reference.png"
        
        if not os.path.exists(os.path.join(folder_path, source_file)):
            source_file = f"{base_name}_source.png"
        
        source_path = os.path.join(folder_path, source_file)
        edited_path = os.path.join(folder_path, edited_file)
        caption_path = find_caption_file(folder_path, base_name)
        
        if not os.path.exists(source_path) or not caption_path:
            continue
        
        try:
            source_img = Image.open(source_path)
            edited_img = Image.open(edited_path)
            with open(caption_path, 'r', encoding='utf-8') as f:
                prompt = f.read().strip()
            
            source_images.append(source_img)
            edited_images.append(edited_img)
            prompts.append(prompt)
            filenames.append(base_name)
        except Exception as e:
            print(f"  Warning: Failed to process {base_name}: {e}")
    
    return {'source': source_images, 'edited': edited_images}, prompts, filenames


def evaluate_folder(folder_path: str, 
                    model_name: str, 
                    batch_size: int,
                    scorer_urls: Dict[str, str],
                    verbose: bool = True) -> Optional[Dict[str, Any]]:
    if not os.path.isdir(folder_path):
        return None
    
    evaluator = RewardEvaluatorClient(scorer_urls)
    is_pair_scorer = model_name in PAIR_SCORERS
    
    if is_pair_scorer:
        images, prompts, filenames = collect_edit_samples(folder_path)
        sample_count = len(prompts)
    else:
        images, prompts, filenames = collect_standard_samples(folder_path)
        sample_count = len(images)
    
    if sample_count == 0:
        if verbose:
            print(f"  Skipped (no valid samples): {folder_path}")
        return None
    
    if verbose:
        print(f"  Evaluating {sample_count} samples: {folder_path}")
    
    all_scores = []
    
    if is_pair_scorer:
        source_images = images['source']
        edited_images = images['edited']
        
        for start_idx in tqdm(range(0, sample_count, batch_size), disable=not verbose):
            end_idx = min(start_idx + batch_size, sample_count)
            batch_images = {
                'source': source_images[start_idx:end_idx],
                'edited': edited_images[start_idx:end_idx]
            }
            batch_prompts = prompts[start_idx:end_idx]
            
            try:
                batch_results = evaluator.evaluate(model_name, batch_images, batch_prompts)
                scores = batch_results.get('scores', batch_results) if isinstance(batch_results, dict) else batch_results
                all_scores.extend(scores)
            except Exception as e:
                print(f"    Batch evaluation failed [{start_idx}:{end_idx}]: {e}")
                return None
    else:
        for start_idx in tqdm(range(0, sample_count, batch_size), disable=not verbose):
            end_idx = min(start_idx + batch_size, sample_count)
            batch_images = images[start_idx:end_idx]
            batch_prompts = prompts[start_idx:end_idx]
            
            try:
                batch_results = evaluator.evaluate(model_name, batch_images, batch_prompts)
                scores = batch_results.get('scores', batch_results) if isinstance(batch_results, dict) else batch_results
                all_scores.extend(scores)
            except Exception as e:
                print(f"    Batch evaluation failed [{start_idx}:{end_idx}]: {e}")
                continue
    
    if not all_scores:
        return None
    
    return {
        'folder': folder_path,
        'model': model_name,
        'average': sum(all_scores) / len(all_scores),
        'scores': all_scores,
        'count': len(all_scores)
    }


def find_leaf_folders(root_path: str, min_depth: int = 0, max_depth: int = -1) -> List[str]:
    result = []
    root_path = os.path.abspath(root_path)
    
    def has_images(folder: str) -> bool:
        for f in os.listdir(folder):
            if f.lower().endswith(('.png', '.jpg', '.jpeg')):
                return True
        return False
    
    def recurse(current_path: str, depth: int):
        if max_depth >= 0 and depth > max_depth:
            return
        
        try:
            entries = os.listdir(current_path)
        except PermissionError:
            return
        
        subdirs = [e for e in entries if os.path.isdir(os.path.join(current_path, e))]
        
        if not subdirs or (max_depth >= 0 and depth == max_depth):
            if depth >= min_depth and has_images(current_path):
                result.append(current_path)
        else:
            for subdir in subdirs:
                recurse(os.path.join(current_path, subdir), depth + 1)
            if depth >= min_depth and has_images(current_path):
                result.append(current_path)
    
    recurse(root_path, 0)
    return sorted(result)


def run(config: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
    scorer_urls = config['scorer_urls']
    defaults = config.get('defaults', {})
    evaluations = config['evaluations']
    output_file = config.get('output')
    verbose = config.get('verbose', True)
    
    default_batch_size = defaults.get('batch_size', 64)
    default_recursive = defaults.get('recursive', False)
    default_min_depth = defaults.get('min_depth', 0)
    default_max_depth = defaults.get('max_depth', -1)
    
    all_results = {}
    
    for eval_item in evaluations:
        path = eval_item.get('path')
        if not path:
            print("Warning: Evaluation item missing 'path', skipping")
            continue
        
        models = eval_item.get('models', [])
        if not models:
            print(f"Warning: No models specified for {path}, skipping")
            continue
        
        batch_size = eval_item.get('batch_size', default_batch_size)
        recursive = eval_item.get('recursive', default_recursive)
        min_depth = eval_item.get('min_depth', default_min_depth)
        max_depth = eval_item.get('max_depth', default_max_depth)
        
        if not recursive:
            max_depth = 0
        
        folders = find_leaf_folders(path, min_depth, max_depth)
        
        if not folders:
            print(f"No image folders found in: {path}")
            continue
        
        print(f"\nProcessing {len(folders)} folder(s) from: {path}")
        print(f"Models: {', '.join(models)}")
        print("-" * 60)
        
        for folder in tqdm(folders, desc="Folders", disable=not verbose):
            folder_results = {}
            
            for model in models:
                if verbose:
                    print(f"\n[{model}] ", end="")
                
                result = evaluate_folder(folder, model, batch_size, scorer_urls, verbose)
                
                if result:
                    folder_results[model] = result
                    if verbose:
                        print(f"    -> Average: {result['average']:.4f} (n={result['count']})")
            
            if folder_results:
                rel_path = os.path.relpath(folder, path)
                key = f"{path}:{rel_path}" if rel_path != "." else path
                all_results[key] = folder_results
    
    # Print summary
    print("\n" + "=" * 60)
    print("Evaluation Summary")
    print("=" * 60)
    for folder, results in all_results.items():
        print(f"\n{folder}")
        for model, data in results.items():
            print(f"   [{model}] avg={data['average']:.4f}, n={data['count']}")
    
    # Save results
    if output_file:
        serializable = {
            folder: {
                model: {'average': data['average'], 'count': data['count']}
                for model, data in results.items()
            }
            for folder, results in all_results.items()
        }
        
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump({
                'timestamp': datetime.now().isoformat(),
                'results': serializable
            }, f, indent=2, ensure_ascii=False)
        
        print(f"\nResults saved to: {output_file}")
    
    return all_results


def main():
    if len(sys.argv) != 2:
        print(f"Usage: python {sys.argv[0]} <config.yaml>")
        sys.exit(1)
    
    config_path = sys.argv[1]
    with open(config_path, 'r', encoding='utf-8') as f:
        config = yaml.safe_load(f)
    
    results = run(config)
    sys.exit(0 if results else 1)


if __name__ == "__main__":
    main()