File size: 32,310 Bytes
489723f
 
 
 
5ac03e5
 
 
489723f
 
 
 
ea4fc2e
 
489723f
 
 
 
 
 
 
 
 
 
ea4fc2e
489723f
 
 
 
 
 
 
 
 
ea4fc2e
 
489723f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea4fc2e
489723f
 
 
 
 
ea4fc2e
489723f
 
 
 
 
 
 
 
ea4fc2e
 
 
 
 
 
 
489723f
 
ea4fc2e
 
 
489723f
 
 
 
 
 
 
 
 
 
ea4fc2e
489723f
 
 
 
 
 
ea4fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
489723f
 
 
ea4fc2e
489723f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea4fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
489723f
 
 
ea4fc2e
489723f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ac03e5
489723f
ea4fc2e
 
 
 
489723f
 
ea4fc2e
489723f
 
ea4fc2e
 
489723f
 
ea4fc2e
 
 
 
 
 
 
 
 
 
 
489723f
ea4fc2e
489723f
 
 
 
 
 
 
ea4fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
489723f
 
 
 
 
 
ea4fc2e
 
 
 
 
 
 
 
489723f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea4fc2e
489723f
 
 
 
 
 
ea4fc2e
489723f
 
 
 
 
 
 
 
 
ea4fc2e
 
 
 
 
 
 
 
 
 
 
 
 
489723f
 
 
 
 
 
 
 
 
ea4fc2e
 
 
 
 
 
 
 
 
489723f
ea4fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
489723f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea4fc2e
489723f
 
 
 
ea4fc2e
 
 
 
 
 
489723f
ea4fc2e
489723f
ea4fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
489723f
 
ea4fc2e
 
489723f
 
 
 
 
ea4fc2e
489723f
 
 
 
 
 
 
 
ea4fc2e
489723f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea4fc2e
489723f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea4fc2e
 
 
 
 
 
 
 
489723f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea4fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
489723f
 
ea4fc2e
 
 
 
 
 
 
 
 
489723f
ea4fc2e
 
489723f
ea4fc2e
 
489723f
 
 
8fc5921
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import gradio as gr
import os
import cv2
from deepface import DeepFace
from nudenet import NudeDetector
import io
import tempfile

# --- Constants for image generation ---
FONT_SIZE_TITLE = 36 # Increased from 28
FONT_SIZE_DESC = 24 # Increased from 20
PADDING = 30
ITEM_SPACING = 50
BORDER_COLOR = (255, 20, 147)
BORDER_WIDTH = 3
TEXT_COLOR = (255, 20, 147)
BACKGROUND_COLOR = (0, 0, 0)
ERROR_IMAGE_WIDTH = 800
ERROR_IMAGE_HEIGHT = 400
TARGET_MAX_DIMENSION = 400
PIXELS_PER_CM_ESTIMATE = 15
MAX_PROCESSING_DIMENSION = 1024 # New constant for initial image resizing

# Try to load a font, fall back to default if not available
try:
    FONT_TITLE = ImageFont.truetype("arial.ttf", FONT_SIZE_TITLE)
    try:
        FONT_DESC = ImageFont.truetype("arialbd.ttf", FONT_SIZE_DESC)
    except IOError:
        print("Could not load arialbd.ttf, falling back to arial.ttf for FONT_DESC.")
        FONT_DESC = ImageFont.truetype("arial.ttf", FONT_SIZE_DESC)
    FONT_ERROR = ImageFont.truetype("arial.ttf", 30) # Increased from 24
    FONT_LABEL_SIMPLE = ImageFont.truetype("arial.ttf", 18) # Increased from 14
except IOError:
    print("Could not load arial.ttf, using default font.")
    FONT_TITLE = ImageFont.load_default()
    FONT_DESC = ImageFont.load_default()
    FONT_ERROR = ImageFont.load_default()
    FONT_LABEL_SIMPLE = ImageFont.load_default()

def create_error_image(message):
    error_img = Image.new('RGB', (ERROR_IMAGE_WIDTH, ERROR_IMAGE_HEIGHT), color=BACKGROUND_COLOR)
    draw = ImageDraw.Draw(error_img)

    bbox = FONT_ERROR.getbbox(message)
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]

    x = (ERROR_IMAGE_WIDTH - text_width) / 2
    y = (ERROR_IMAGE_HEIGHT - text_height) / 2

    draw.text((x, y), message, font=FONT_ERROR, fill=TEXT_COLOR)
    return error_img

def resize_crop(crop_img, target_max_dim):
    if crop_img.width == 0 or crop_img.height == 0:
        return crop_img

    if crop_img.width > crop_img.height:
        new_width = target_max_dim
        new_height = int(crop_img.height * (target_max_dim / crop_img.width))
    else:
        new_height = target_max_dim
        new_width = int(crop_img.width * (target_max_dim / crop_img.height))

    return crop_img.resize((new_width, new_height), Image.Resampling.LANCZOS)

def estimate_breast_size_cm(crop_img):
    width_px, height_px = crop_img.size
    width_cm = round(width_px / PIXELS_PER_CM_ESTIMATE, 1)
    height_cm = round(height_px / PIXELS_PER_CM_ESTIMATE, 1)
    return f"Breite: {width_cm} cm · Höhe: {height_cm} cm (geschätzt)"

def estimate_vagina_size_cm(crop_img):
    width_px, height_px = crop_img.size
    width_cm = round(width_px / PIXELS_PER_CM_ESTIMATE, 1)
    height_cm = round(height_px / PIXELS_PER_CM_ESTIMATE, 1)
    return f"Breite: {width_cm} cm · Höhe: {height_cm} cm (geschätzt)"

def estimate_body_measurements(person_bbox, associated_nudenet_dets, analysis_mode):
    pb_x1, pb_y1, pb_x2, pb_y2 = person_bbox
    person_width_px = pb_x2 - pb_x1
    person_height_px = pb_y2 - pb_y1

    if person_width_px <= 0 or person_height_px <= 0:
        return "Körpermaße nicht schätzbar (ungültiger Personen-BBox)"

    person_width_cm = person_width_px / PIXELS_PER_CM_ESTIMATE
    person_height_cm = person_height_px / PIXELS_PER_CM_ESTIMATE

    bust_cm = "?"
    waist_cm = "?"
    hip_cm = "?"

    breast_detections = []
    vagina_detections = []

    if analysis_mode in ['Komplett (Brüste + Vagina + geschätztes Alter)', 'Brüste (Nur Brüste)']:
        breast_detections = [det for det in associated_nudenet_dets if 'FEMALE_BREAST_EXPOSED' in det['class']]
    if analysis_mode in ['Komplett (Brüste + Vagina + geschätztes Alter)', 'Vagina (Nur Vagina)']:
        vagina_detections = [det for det in associated_nudenet_dets if 'FEMALE_GENITALIA_EXPOSED' in det['class']]

    if breast_detections:
        # Simple estimate: average breast width
        b_width_px = sum([det['box'][2] for det in breast_detections]) / len(breast_detections)
        bust_cm = round(b_width_px * 2.5 / PIXELS_PER_CM_ESTIMATE, 1) # A rough multiplier for bust circumference

    if vagina_detections:
        vg_width_px = max([det['box'][2] for det in vagina_detections])
        hip_cm = round(vg_width_px * 2.0 / PIXELS_PER_CM_ESTIMATE, 1)
    elif person_height_px > 0:
        hip_cm = round(person_width_cm * 0.9, 1)

    if person_width_cm > 0:
        waist_cm = round(person_width_cm * 0.8, 1)

    return f"Maße (geschätzt, unsicher): Büste: {bust_cm} cm · Taille: {waist_cm} cm · Hüfte: {hip_cm} cm"

def describe_breast_precise(crop):
    w, h = crop.size
    crop_np = np.array(crop)
    gray = cv2.cvtColor(crop_np, cv2.COLOR_RGB2GRAY)

    # Calculate nipple area/prominence (very rough estimation)
    # This is a very rough estimation and needs more advanced computer vision
    # For now, let's just make a simple placeholder based on contrast/shape
    # Find contours, look for circular/elliptical shapes
    _, thresh = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    nipple_detected = False
    for contour in contours:
        area = cv2.contourArea(contour)
        if area > 50 and area < (w * h / 5): # Filter by reasonable size
            perimeter = cv2.arcLength(contour, True)
            if perimeter > 0:
                circularity = 4 * np.pi * area / (perimeter * perimeter)
                if circularity > 0.6: # Check for somewhat circular shapes
                    nipple_detected = True
                    break

    nipple_prominence = "Sichtbar" if nipple_detected else "Nicht hervorstehend"

    # Estimate shape (round, conical, bell, etc.)
    ratio_wh = w / h
    if ratio_wh > 1.1: shape = "Breit / Horizontal"
    elif ratio_wh < 0.9: shape = "Hoch / Vertikal"
    else: shape = "Rund / Ausgewogen"

    size = "klein" if w*h < 30000 else "mittel" if w*h < 80000 else "groß" if w*h < 150000 else "sehr groß"

    size_cm_estimate = estimate_breast_size_cm(crop)

    return f"Form: {shape} · Größe: {size} · Nippel: {nipple_prominence} · Maße: {size_cm_estimate}"

def describe_vagina_precise(crop):
    w, h = crop.size
    crop_np = np.array(crop)
    gray = cv2.cvtColor(crop_np, cv2.COLOR_RGB2GRAY)

    hair_mask = cv2.inRange(gray, 40, 140)
    hair_ratio = np.sum(hair_mask > 0) / (w*h)
    if hair_ratio < 0.03: shaved = "komplett glatt rasiert"
    elif hair_ratio < 0.12: shaved = "minimal (Landing Strip / Dreieck)"
    elif hair_ratio < 0.35: shaved = "teilrasiert / Brazilian"
    else: shaved = "voll behaart (Bush)"

    ratio_wh = w / h
    labia_area = w * h

    # More detailed form descriptions
    if labia_area < 20000: # Very small overall area
        if ratio_wh > 1.0: form = "Mini Outie (Schmetterlingsform)"
        else: form = "Sehr kleine Innie (Barbie-Form)"
    elif ratio_wh < 0.75: # Taller than wide
        form = "Lange Innie (Vertikale Form)"
    elif ratio_wh > 1.5: # Very wide
        if labia_area > 70000: form = "Extrem ausgeprägtes Outie (Puff-Form)"
        else: form = "Breites Outie (Offene Form)"
    elif ratio_wh > 1.1: # Moderately wide (more typical Outie)
        form = "Klassisches Outie (Labien sichtbar)"
    else: # Ratio between 0.75 and 1.1, and not tiny area (more typical Innie)
        form = "Klassische Innie (Geschlossene Form)"

    size = "winzig" if labia_area < 20000 else "klein" if labia_area < 40000 else "mittel" if labia_area < 70000 else "groß & voll"

    size_cm_estimate = estimate_vagina_size_cm(crop)

    return f"Form: {form} · Größe: {size} · Behaart: {shaved} · Maße: {size_cm_estimate}"

def estimate_age(crop_img):
    try:
        img_array = np.array(crop_img)
        face = DeepFace.extract_faces(img_array, detector_backend='retinaface', enforce_detection=False)
        if len(face) > 0:
            age = DeepFace.analyze(img_array, actions=['age'], enforce_detection=False, silent=True)[0]['age']
            return f"ca. {int(age)} Jahre (±3)"
        else:
            gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)
            smoothness = cv2.Laplacian(gray, cv2.CV_64F).var()
            if smoothness > 1800: return "jung (18–25)"
            elif smoothness > 1000: return "jung-mittel (25–35)"
            else: return "reif (35–45+)"
    except Exception as e:
        print(f"Error estimating age: {e}")
        return "Alter nicht bestimmbar"

# Initialize NudeDetector
detector = NudeDetector()

def _analyze_single_image_and_generate_outputs(analysis_mode, input_image_path):
    print(f"[INFO] _analyze_single_image_and_generate_outputs called with mode: {analysis_mode}, path: {input_image_path}")

    temp_img_path = None
    try:
        if input_image_path is None:
            print("[WARNING] No input image path provided to single analyzer.")
            return create_error_image('Kein Bild ausgewählt.'), None

        processing_img_for_detection_path = input_image_path

        try:
            original_img = Image.open(input_image_path).convert("RGB")
            if max(original_img.width, original_img.height) > MAX_PROCESSING_DIMENSION:
                original_img = resize_crop(original_img, MAX_PROCESSING_DIMENSION)
                print(f"[INFO] Image resized to {original_img.width}x{original_img.height} for faster processing.")

                with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp_file:
                    original_img.save(tmp_file.name, "JPEG")
                    temp_img_path = tmp_file.name
                processing_img_for_detection_path = temp_img_path
            else:
                processing_img_for_detection_path = input_image_path

            original_img_np = np.array(original_img)
            print(f"[INFO] Image opened and potentially resized successfully: {input_image_path}")
        except Exception as e:
            print(f"[ERROR] Failed to open image {input_image_path}: {e}")
            return create_error_image(f'Fehler beim Öffnen des Bildes: {e}'), None

        current_filename = os.path.basename(input_image_path)

        try:
            nudenet_detections = detector.detect(processing_img_for_detection_path)

            # Filter NudeNet detections based on analysis_mode
            allowed_classes = []
            if analysis_mode == 'Komplett (Brüste + Vagina + geschätztes Alter)':
                allowed_classes = ['FEMALE_GENITALIA_EXPOSED', 'ANUS_EXPOSED', 'FEMALE_BREAST_EXPOSED', 'BUTTOCKS_EXPOSED']
            elif analysis_mode == 'Brüste (Nur Brüste)':
                allowed_classes = ['FEMALE_BREAST_EXPOSED', 'ANUS_EXPOSED', 'BUTTOCKS_EXPOSED'] # Include other body parts for general detection context
            elif analysis_mode == 'Vagina (Nur Vagina)':
                allowed_classes = ['FEMALE_GENITALIA_EXPOSED', 'ANUS_EXPOSED', 'BUTTOCKS_EXPOSED'] # Include other body parts for general detection context

            if allowed_classes:
                nudenet_detections = [det for det in nudenet_detections if det['class'] in allowed_classes]

            print(f"[INFO] NudeNet detected {len(nudenet_detections)} objects for mode '{analysis_mode}'.")
        except Exception as e:
            print(f"[ERROR] Error during NudeNet detection for {input_image_path}: {e}")
            return create_error_image(f'Fehler bei der NudeNet-Erkennung: {e}'), None

        persons_data = []
        face_detections = []
        # Face detection for age estimation is always attempted if mode includes age
        if analysis_mode == 'Komplett (Brüste + Vagina + geschätztes Alter)':
            try:
                face_results = DeepFace.extract_faces(original_img_np, detector_backend='retinaface', enforce_detection=False)
                face_detections = [f for f in face_results if f['confidence'] > 0.9]
                print(f"[INFO] DeepFace detected {len(face_detections)} faces.")
            except Exception as e:
                print(f"[WARNING] Error during DeepFace face detection: {e}. Proceeding without person association or age estimation.")

        if face_detections:
            for face_det in face_detections:
                x, y, w, h = face_det['facial_area']['x'], face_det['facial_area']['y'], face_det['facial_area']['w'], face_det['facial_area']['h']
                expand_factor_y = 2.0
                expand_factor_x = 1.2

                person_center_x = x + w / 2
                person_center_y = y + h / 2

                new_h = int(h * expand_factor_y)
                new_w = int(w * expand_factor_x)

                person_x1 = max(0, int(person_center_x - new_w / 2))
                person_y1 = max(0, int(person_center_y - new_h / 2))
                person_x2 = min(original_img.width, int(person_center_x + new_w / 2))
                person_y2 = min(original_img.height, int(person_center_y + new_h / 2))

                person_bbox = (person_x1, person_y1, person_x2, person_y2)

                associated_nudenet_dets = []
                for nude_det in nudenet_detections:
                    nx1, ny1, nx2, ny2 = nude_det['box'][0], nude_det['box'][1], nude_det['box'][0] + nude_det['box'][2], nude_det['box'][1] + nude_det['box'][3]
                    nude_center_x = nx1 + (nx2 - nx1) / 2
                    nude_center_y = ny1 + (ny2 - ny1) / 2

                    if person_x1 <= nude_center_x <= person_x2 and person_y1 <= nude_center_y <= person_y2:
                        associated_nudenet_dets.append(nude_det)

                if associated_nudenet_dets:
                    body_measurements_str = estimate_body_measurements(person_bbox, associated_nudenet_dets, analysis_mode)
                    persons_data.append({
                        'person_bbox': person_bbox,
                        'nudenet_detections': associated_nudenet_dets,
                        'face_area': face_det['facial_area'],
                        'body_measurements': body_measurements_str
                    })
            print(f"[INFO] {len(persons_data)} persons with associated NudeNet detections found for mode '{analysis_mode}'.")

        annotated_original_img = original_img.copy()
        draw_annotated = ImageDraw.Draw(annotated_original_img)

        current_image_crops_with_details = []
        processed_nudenet_ids = set()

        for i, person in enumerate(persons_data):
            px1, py1, px2, py2 = person['person_bbox']
            # Draw person bounding box if there are associated detections
            if any(det['class'] in allowed_classes for det in person['nudenet_detections']):
                draw_annotated.rectangle([(px1, py1), (px2, py2)], outline=(0, 255, 0), width=BORDER_WIDTH)
                label_person = f"Person {i+1}"
                bbox_label_person = FONT_LABEL_SIMPLE.getbbox(label_person)
                text_width_person = bbox_label_person[2] - bbox_label_person[0]
                text_height_person = bbox_label_person[3] - bbox_label_person[1]
                draw_annotated.rectangle([(px1, py1 - text_height_person - 2), (px1 + text_width_person, py1)], fill=(0, 255, 0))
                draw_annotated.text((px1, py1 - text_height_person - 2), label_person, font=FONT_LABEL_SIMPLE, fill=BACKGROUND_COLOR)

                if person['body_measurements'] and person['body_measurements'] != "Körpermaße nicht schätzbar (ungültiger Personen-BBox)":
                    current_image_crops_with_details.append((f"Person {i+1} Körpermaße", Image.new('RGB', (1,1), (0,0,0)), person['body_measurements']))

            for det in person['nudenet_detections']:
                det_class = det['class']
                x1, y1, x2, y2 = det['box'][0], det['box'][1], det['box'][0] + det['box'][2], det['box'][1] + det['box'][3]
                x1, y1, x2, y2 = max(0, x1), max(0, y1), min(original_img.width, x2), min(original_img.height, y2)

                draw_annotated.rectangle([(x1, y1), (x2, y2)], outline=BORDER_COLOR, width=BORDER_WIDTH)

                crop = original_img.crop((x1, y1, x2, y2))
                age_str = 'Alter unbekannt'
                if analysis_mode == 'Komplett (Brüste + Vagina + geschätztes Alter)':
                    try:
                        face_x, face_y, face_w, face_h = person['face_area']['x'], person['face_area']['y'], person['face_area']['w'], person['face_area']['h']
                        face_crop_for_age = original_img.crop((face_x, face_y, face_x + face_w, face_y + face_h))
                        age_str = estimate_age(face_crop_for_age)
                    except Exception as e:
                        print(f"[ERROR] Error estimating age for person {i+1} crop: {e}")

                if 'FEMALE_GENITALIA_EXPOSED' in det_class and analysis_mode in ['Komplett (Brüste + Vagina + geschätztes Alter)', 'Vagina (Nur Vagina)']:
                    label_detailed = f"Person {i+1} Vagina"
                    desc = describe_vagina_precise(crop)
                    if analysis_mode == 'Komplett (Brüste + Vagina + geschätztes Alter)':
                        desc += f" · Alter: {age_str}"
                    current_image_crops_with_details.append((label_detailed, resize_crop(crop, TARGET_MAX_DIMENSION), desc))
                    processed_nudenet_ids.add(id(det))
                elif 'FEMALE_BREAST_EXPOSED' in det_class and analysis_mode in ['Komplett (Brüste + Vagina + geschätztes Alter)', 'Brüste (Nur Brüste)']:
                    label_detailed = f"Person {i+1} Brust"
                    desc = describe_breast_precise(crop)
                    if analysis_mode == 'Komplett (Brüste + Vagina + geschätztes Alter)':
                        desc += f" · Alter: {age_str}"
                    current_image_crops_with_details.append((label_detailed, resize_crop(crop, TARGET_MAX_DIMENSION), desc))
                    processed_nudenet_ids.add(id(det))
                elif ('ANUS_EXPOSED' in det_class or 'BUTTOCKS_EXPOSED' in det_class) and analysis_mode == 'Komplett (Brüste + Vagina + geschätztes Alter)':
                    label_detailed = f"Person {i+1} {det_class.replace('_EXPOSED', '').replace('_', ' ').title()}"
                    desc = f"Erkannt: {det_class.replace('_EXPOSED', '').replace('_', ' ').title()}"
                    if analysis_mode == 'Komplett (Brüste + Vagina + geschätztes Alter)':
                        desc += f" · Alter: {age_str}"
                    current_image_crops_with_details.append((label_detailed, resize_crop(crop, TARGET_MAX_DIMENSION), desc))
                    processed_nudenet_ids.add(id(det))

        unassociated_nudenet_detections = [det for det in nudenet_detections if id(det) not in processed_nudenet_ids]

        for det in unassociated_nudenet_detections:
            det_class = det['class']
            x1, y1, x2, y2 = det['box'][0], det['box'][1], det['box'][0] + det['box'][2], det['box'][1] + det['box'][3]
            x1, y1, x2, y2 = max(0, x1), max(0, y1), min(original_img.width, x2), min(original_img.height, y2)

            draw_annotated.rectangle([(x1, y1), (x2, y2)], outline=(255, 255, 0), width=BORDER_WIDTH)
            label_global_simple = f"Global {det_class.replace('_EXPOSED', '').replace('_', ' ').title()}"
            bbox_label_global = FONT_LABEL_SIMPLE.getbbox(label_global_simple)
            text_width_global = bbox_label_global[2] - bbox_label_global[0]
            text_height_global = bbox_label_global[3] - bbox_label_global[1]
            draw_annotated.rectangle([(x1, y1 - text_height_global - 2), (x1 + text_width_global, y1)], fill=TEXT_COLOR)
            draw_annotated.text((x1, y1 - text_height_global - 2), label_global_simple, font=FONT_LABEL_SIMPLE, fill=BACKGROUND_COLOR)

            crop = original_img.crop((x1, y1, x2, y2))
            age_str = 'Alter unbekannt'
            if analysis_mode == 'Komplett (Brüste + Vagina + geschätztes Alter)':
                try:
                    resized_crop_for_age = resize_crop(crop, TARGET_MAX_DIMENSION)
                    age_str = estimate_age(resized_crop_for_age)
                except Exception as e:
                    print(f"[ERROR] Error estimating age for global crop: {e}")

            if 'FEMALE_GENITALIA_EXPOSED' in det_class and analysis_mode in ['Komplett (Brüste + Vagina + geschätztes Alter)', 'Vagina (Nur Vagina)']:
                label_detailed = "Global Vagina"
                desc = describe_vagina_precise(crop)
                if analysis_mode == 'Komplett (Brüste + Vagina + geschätztes Alter)':
                    desc += f" · Alter: {age_str}"
                current_image_crops_with_details.append((label_detailed, resize_crop(crop, TARGET_MAX_DIMENSION), desc))
            elif 'FEMALE_BREAST_EXPOSED' in det_class and analysis_mode in ['Komplett (Brüste + Vagina + geschätztes Alter)', 'Brüste (Nur Brüste)']:
                label_detailed = "Global Brust"
                desc = describe_breast_precise(crop)
                if analysis_mode == 'Komplett (Brüste + Vagina + geschätztes Alter)':
                    desc += f" · Alter: {age_str}"
                current_image_crops_with_details.append((label_detailed, resize_crop(crop, TARGET_MAX_DIMENSION), desc))
            elif ('ANUS_EXPOSED' in det_class or 'BUTTOCKS_EXPOSED' in det_class) and analysis_mode == 'Komplett (Brüste + Vagina + geschätztes Alter)':
                label_detailed = f"Global {det_class.replace('_EXPOSED', '').replace('_', ' ').title()}"
                desc = f"Erkannt: {det_class.replace('_EXPOSED', '').replace('_', ' ').title()}"
                if analysis_mode == 'Komplett (Brüste + Vagina + geschätztes Alter)':
                    desc += f" · Alter: {age_str}"
                current_image_crops_with_details.append((label_detailed, resize_crop(crop, TARGET_MAX_DIMENSION), desc))

        if not current_image_crops_with_details:
             text = "Keine relevanten Bereiche für den ausgewählten Analysemodus erkannt."
             original_img_width, original_img_height = original_img.size
             bbox_text = FONT_TITLE.getbbox(text)
             text_width = bbox_text[2] - bbox_text[0]
             text_height = bbox_text[3] - bbox_text[1]
             draw_annotated.text(((original_img_width - text_width) / 2, original_img_height - text_height - PADDING), text, font=FONT_TITLE, fill=TEXT_COLOR)
             print(f"[INFO] No relevant detections for mode '{analysis_mode}', adding message to original image.")

        if not current_image_crops_with_details:
            composite_crops_img = create_error_image("Keine detailreichen Bereiche für Crops gefunden.")
        else:
            max_crop_width = 0
            total_height_crops = PADDING

            for title, crop_img, desc in current_image_crops_with_details:
                if crop_img.width == 1 and crop_img.height == 1: # This is for body measurements
                    bbox_title = FONT_TITLE.getbbox(title)
                    bbox_desc = FONT_DESC.getbbox(desc)
                    text_title_height = bbox_title[3] - bbox_title[1]
                    text_desc_height = bbox_desc[3] - bbox_desc[1]
                    total_height_crops += text_title_height + text_desc_height + PADDING * 2 + ITEM_SPACING
                    max_crop_width = max(max_crop_width, (bbox_title[2] - bbox_title[0]), (bbox_desc[2] - bbox_desc[0]))
                else:
                    max_crop_width = max(max_crop_width, crop_img.width)
                    bbox_title = FONT_TITLE.getbbox(title)
                    bbox_desc = FONT_DESC.getbbox(desc)
                    text_title_height = bbox_title[3] - bbox_title[1]
                    text_desc_height = bbox_desc[3] - bbox_desc[1]
                    total_height_crops += crop_img.height + text_title_height + text_desc_height + PADDING * 2 + ITEM_SPACING
            total_height_crops += PADDING

            canvas_width_crops = max_crop_width + PADDING * 2
            for title, crop_img, desc in current_image_crops_with_details:
                bbox_title = FONT_TITLE.getbbox(title)
                bbox_desc = FONT_DESC.getbbox(desc)
                text_title_width = bbox_title[2] - bbox_title[0]
                text_desc_width = bbox_desc[2] - bbox_desc[0]
                canvas_width_crops = max(canvas_width_crops, text_title_width + PADDING * 2, text_desc_width + PADDING * 2)

            composite_crops_img = Image.new('RGB', (canvas_width_crops, total_height_crops), color = BACKGROUND_COLOR)
            draw_crops = ImageDraw.Draw(composite_crops_img)

            current_y_offset_crops = PADDING

            for title, crop_img, desc in current_image_crops_with_details:
                if crop_img.width == 1 and crop_img.height == 1: # This is for body measurements
                    bbox_title = FONT_TITLE.getbbox(title)
                    text_title_width = bbox_title[2] - bbox_title[0]
                    text_title_height = bbox_title[3] - bbox_title[1]
                    draw_crops.text(((canvas_width_crops - text_title_width) / 2, current_y_offset_crops), title, font=FONT_TITLE, fill=TEXT_COLOR)
                    current_y_offset_crops += text_title_height + PADDING // 2

                    bbox_desc = FONT_DESC.getbbox(desc)
                    text_desc_width = bbox_desc[2] - bbox_desc[0]
                    text_desc_height = bbox_desc[3] - bbox_desc[1]
                    draw_crops.text(((canvas_width_crops - text_desc_width) / 2, current_y_offset_crops), desc, font=FONT_DESC, fill=TEXT_COLOR)
                    current_y_offset_crops += text_desc_height + ITEM_SPACING

                else:
                    x_offset_crop = (canvas_width_crops - crop_img.width) // 2

                    draw_crops.rectangle(
                        (x_offset_crop - BORDER_WIDTH,
                         current_y_offset_crops - BORDER_WIDTH,
                         x_offset_crop + crop_img.width + BORDER_WIDTH,
                         current_y_offset_crops + crop_img.height + BORDER_WIDTH),
                        fill=BORDER_COLOR
                    )

                    composite_crops_img.paste(crop_img, (x_offset_crop, current_y_offset_crops))

                    current_y_offset_crops += crop_img.height + PADDING

                    bbox_title = FONT_TITLE.getbbox(title)
                    text_title_width = bbox_title[2] - bbox_title[0]
                    text_title_height = bbox_title[3] - bbox_title[1]
                    draw_crops.text(((canvas_width_crops - text_title_width) / 2, current_y_offset_crops), title, font=FONT_TITLE, fill=TEXT_COLOR)
                    current_y_offset_crops += text_title_height + PADDING // 2

                    bbox_desc = FONT_DESC.getbbox(desc)
                    text_desc_width = bbox_desc[2] - bbox_desc[0]
                    text_desc_height = bbox_desc[3] - bbox_desc[1]
                    draw_crops.text(((canvas_width_crops - text_desc_width) / 2, current_y_offset_crops), desc, font=FONT_DESC, fill=TEXT_COLOR)
                    current_y_offset_crops += text_desc_height + ITEM_SPACING

        separator_text_original = "Originalbild mit Markierungen"
        separator_text_crops = "Detaillierte Analysen"

        if analysis_mode == 'Brüste (Nur Brüste)':
            separator_text_crops = "Detaillierte Brust-Analysen"
        elif analysis_mode == 'Vagina (Nur Vagina)':
            separator_text_crops = "Detaillierte Vagina-Analysen"
        elif analysis_mode == 'Komplett (Brüste + Vagina + geschätztes Alter)':
            separator_text_crops = "Detaillierte Gesamt-Analysen"

        bbox_separator_original = FONT_TITLE.getbbox(separator_text_original)
        bbox_separator_crops = FONT_TITLE.getbbox(separator_text_crops)

        separator_height_total = (bbox_separator_original[3] - bbox_separator_original[1]) + (bbox_separator_crops[3] - bbox_separator_crops[1]) + PADDING * 4

        combined_width = max(annotated_original_img.width, composite_crops_img.width,
                             (bbox_separator_original[2] - bbox_separator_original[0]) + PADDING * 2,
                             (bbox_separator_crops[2] - bbox_separator_crops[0]) + PADDING * 2)

        combined_width = max(combined_width, ERROR_IMAGE_WIDTH)

        combined_height = annotated_original_img.height + separator_height_total + composite_crops_img.height + PADDING * 2
        combined_img = Image.new('RGB', (combined_width, combined_height), color=BACKGROUND_COLOR)
        combined_draw = ImageDraw.Draw(combined_img)

        current_y_combined = PADDING

        text_width_orig_sep = bbox_separator_original[2] - bbox_separator_original[0]
        text_height_orig_sep = bbox_separator_original[3] - bbox_separator_original[1]
        combined_draw.text(((combined_width - text_width_orig_sep) / 2, current_y_combined), separator_text_original, font=FONT_TITLE, fill=TEXT_COLOR)
        current_y_combined += text_height_orig_sep + PADDING

        x_offset_original = (combined_width - annotated_original_img.width) // 2
        combined_img.paste(annotated_original_img, (x_offset_original, current_y_combined))
        current_y_combined += annotated_original_img.height + PADDING

        text_width_crops_sep = bbox_separator_crops[2] - bbox_separator_crops[0]
        text_height_crops_sep = bbox_separator_crops[3] - bbox_separator_crops[1]
        combined_draw.text(((combined_width - text_width_crops_sep) / 2, current_y_combined), separator_text_crops, font=FONT_TITLE, fill=TEXT_COLOR)
        current_y_combined += text_height_crops_sep + PADDING

        x_offset_crops = (combined_width - composite_crops_img.width) // 2
        combined_img.paste(composite_crops_img, (x_offset_crops, current_y_combined))

        print("[INFO] Combined image generated successfully.")

        with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp_pdf:
            combined_img.save(tmp_pdf.name, "PDF")
            pdf_path = tmp_pdf.name

        return combined_img, pdf_path

    except Exception as e:
        print(f"[CRITICAL ERROR] An unexpected error occurred during single image analysis: {e}")
        if temp_img_path and os.path.exists(temp_img_path):
            os.remove(temp_img_path)
        return create_error_image(f'Unerwarteter Fehler bei der Bildanalyse für {os.path.basename(input_image_path)}: {e}'), None
    finally:
        if temp_img_path and os.path.exists(temp_img_path):
            os.remove(temp_img_path)

def analyze_images_for_gallery(analysis_mode, input_image_paths):
    print(f"[INFO] analyze_images_for_gallery called with mode: {analysis_mode} and {len(input_image_paths) if input_image_paths else 0} paths.")
    all_combined_images = []
    all_pdf_paths = []

    if not input_image_paths:
        return [create_error_image('Keine Bilder ausgewählt.')], [None]

    for input_image_path in input_image_paths:
        combined_img, pdf_path = _analyze_single_image_and_generate_outputs(analysis_mode, input_image_path)
        all_combined_images.append(combined_img)
        all_pdf_paths.append(pdf_path)

    return all_combined_images, all_pdf_paths

interface = gr.Interface(
    fn=analyze_images_for_gallery,
    inputs=[
        gr.Radio(
            choices=['Komplett (Brüste + Vagina + geschätztes Alter)', 'Brüste (Nur Brüste)', 'Vagina (Nur Vagina)'],
            value='Komplett (Brüste + Vagina + geschätztes Alter)',
            label='Analyse Modus'
        ),
        gr.File(file_count="multiple", type="filepath", label="Bilder hochladen (mehrere Dateien erlaubt)")
    ],
    outputs=[
        gr.Gallery(label="Analysierte Kompositbilder"),
        gr.File(file_count="multiple", label="PDFs herunterladen")
    ],
    title="🔞 Nacktheits-Analysator",
    description="Laden Sie ein oder mehrere Bilder hoch, um eine detaillierte Analyse basierend auf dem ausgewählten Modus zu erhalten. Das Ergebnis ist ein Kompositbild mit Originalbild und detaillierten Crops, pro Person gruppiert. Sie können auch eine PDF-Version herunterladen."
)

if __name__ == "__main__":
    interface.launch(debug=True, share=True)