File size: 20,416 Bytes
8ed5ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import torch
from PIL import Image
import numpy as np
import os
import requests
import json
import base64
from io import BytesIO
import uuid

# Model initialization
print("Loading models... This may take a moment.")

# YOLOv8 model
yolo_model = None
try:
    from ultralytics import YOLO
    yolo_model = YOLO("yolov8n.pt")  # Using the nano model for faster inference
    print("YOLOv8 model loaded successfully")
except Exception as e:
    print("Error loading YOLOv8 model:", e)
    yolo_model = None

# DETR model (DEtection TRansformer)
detr_processor = None
detr_model = None
try:
    from transformers import DetrImageProcessor, DetrForObjectDetection
    
    # Load the DETR image processor
    # DetrImageProcessor: Handles preprocessing of images for DETR model
    # - Resizes images to appropriate dimensions
    # - Normalizes pixel values
    # - Converts images to tensors
    # - Handles batch processing
    detr_processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
    
    # Load the DETR object detection model
    # DetrForObjectDetection: The actual object detection model
    # - Uses ResNet-50 as backbone
    # - Transformer-based architecture for object detection
    # - Predicts bounding boxes and object classes
    # - Pre-trained on COCO dataset by Facebook AI Research
    detr_model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
    
    print("DETR model loaded successfully")
except Exception as e:
    print("Error loading DETR model:", e)
    detr_processor = None
    detr_model = None

# ViT model
vit_processor = None
vit_model = None
try:
    from transformers import ViTImageProcessor, ViTForImageClassification
    vit_processor = ViTImageProcessor.from_pretrained("google/vit-base-patch16-224")
    vit_model = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224")
    print("ViT model loaded successfully")
except Exception as e:
    print("Error loading ViT model:", e)
    vit_processor = None
    vit_model = None

# Get device information
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")

# ๋ฒกํ„ฐ DB์— ๊ฐ์ฒด ์ €์žฅ ํ•จ์ˆ˜
def save_objects_to_vector_db(image, detection_results, model_type='yolo'):
    if image is None or detection_results is None:
        return "์ด๋ฏธ์ง€๋‚˜ ๊ฐ์ฒด ์ธ์‹ ๊ฒฐ๊ณผ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."
    
    try:
        # ์ด๋ฏธ์ง€๋ฅผ base64๋กœ ์ธ์ฝ”๋”ฉ
        buffered = BytesIO()
        image.save(buffered, format="JPEG")
        img_str = base64.b64encode(buffered.getvalue()).decode('utf-8')
        
        # ๋ชจ๋ธ ํƒ€์ž…์— ๋”ฐ๋ผ ๋‹ค๋ฅธ API ์—”๋“œํฌ์ธํŠธ ํ˜ธ์ถœ
        if model_type in ['yolo', 'detr']:
            # ๊ฐ์ฒด ์ •๋ณด ์ถ”์ถœ
            objects = []
            for obj in detection_results['objects']:
                objects.append({
                    "class": obj['class'],
                    "confidence": obj['confidence'],
                    "bbox": obj['bbox']
                })
            
            # API ์š”์ฒญ ๋ฐ์ดํ„ฐ ๊ตฌ์„ฑ
            data = {
                "image": img_str,
                "objects": objects,
                "image_id": str(uuid.uuid4())
            }
            
            # API ํ˜ธ์ถœ
            response = requests.post(
                "http://localhost:7860/api/add-detected-objects", 
                json=data
            )
            
            if response.status_code == 200:
                result = response.json()
                if 'error' in result:
                    return f"์˜ค๋ฅ˜ ๋ฐœ์ƒ: {result['error']}"
                return f"๋ฒกํ„ฐ DB์— {len(objects)}๊ฐœ ๊ฐ์ฒด ์ €์žฅ ์™„๋ฃŒ! ID: {result.get('ids', '์•Œ ์ˆ˜ ์—†์Œ')}"
        
        elif model_type == 'vit':
            # ViT ๋ถ„๋ฅ˜ ๊ฒฐ๊ณผ ์ €์žฅ
            data = {
                "image": img_str,
                "metadata": {
                    "model": "vit",
                    "classifications": detection_results.get('classifications', [])
                }
            }
            
            # API ํ˜ธ์ถœ
            response = requests.post(
                "http://localhost:7860/api/add-image", 
                json=data
            )
            
            if response.status_code == 200:
                result = response.json()
                if 'error' in result:
                    return f"์˜ค๋ฅ˜ ๋ฐœ์ƒ: {result['error']}"
                return f"๋ฒกํ„ฐ DB์— ์ด๋ฏธ์ง€ ๋ฐ ๋ถ„๋ฅ˜ ๊ฒฐ๊ณผ ์ €์žฅ ์™„๋ฃŒ! ID: {result.get('id', '์•Œ ์ˆ˜ ์—†์Œ')}"
        
        else:
            return "์ง€์›ํ•˜์ง€ ์•Š๋Š” ๋ชจ๋ธ ํƒ€์ž…์ž…๋‹ˆ๋‹ค."
            
        if response.status_code != 200:
            return f"API ์˜ค๋ฅ˜: {response.status_code}"
    except Exception as e:
        return f"์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"

# ๋ฒกํ„ฐ DB์—์„œ ์œ ์‚ฌ ๊ฐ์ฒด ๊ฒ€์ƒ‰ ํ•จ์ˆ˜
def search_similar_objects(image=None, class_name=None):
    try:
        data = {}
        
        if image is not None:
            # ์ด๋ฏธ์ง€๋ฅผ base64๋กœ ์ธ์ฝ”๋”ฉ
            buffered = BytesIO()
            image.save(buffered, format="JPEG")
            img_str = base64.b64encode(buffered.getvalue()).decode('utf-8')
            data["image"] = img_str
            data["n_results"] = 5
        elif class_name is not None and class_name.strip():
            data["class_name"] = class_name.strip()
            data["n_results"] = 5
        else:
            return "์ด๋ฏธ์ง€๋‚˜ ํด๋ž˜์Šค ์ด๋ฆ„ ์ค‘ ํ•˜๋‚˜๋Š” ์ œ๊ณตํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.", []
        
        # API ํ˜ธ์ถœ
        response = requests.post(
            "http://localhost:7860/api/search-similar-objects", 
            json=data
        )
        
        if response.status_code == 200:
            results = response.json()
            if isinstance(results, dict) and 'error' in results:
                return f"์˜ค๋ฅ˜ ๋ฐœ์ƒ: {results['error']}", []
                
            # ๊ฒฐ๊ณผ ํฌ๋งทํŒ…
            formatted_results = []
            for i, result in enumerate(results):
                similarity = (1 - result.get('distance', 0)) * 100
                img_data = result.get('image', '')
                
                # ์ด๋ฏธ์ง€ ๋ฐ์ดํ„ฐ๋ฅผ PIL ์ด๋ฏธ์ง€๋กœ ๋ณ€ํ™˜
                if img_data:
                    try:
                        img_bytes = base64.b64decode(img_data)
                        img = Image.open(BytesIO(img_bytes))
                    except Exception:
                        img = None
                else:
                    img = None
                
                # ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ ์ถ”์ถœ
                metadata = result.get('metadata', {})
                class_name = metadata.get('class', 'N/A')
                confidence = metadata.get('confidence', 0) * 100 if metadata.get('confidence') else 'N/A'
                
                formatted_results.append({
                    'image': img,
                    'info': f"๊ฒฐ๊ณผ #{i+1} | ์œ ์‚ฌ๋„: {similarity:.2f}% | ํด๋ž˜์Šค: {class_name} | ์‹ ๋ขฐ๋„: {confidence if isinstance(confidence, str) else f'{confidence:.2f}%'} | ID: {result.get('id', 'N/A')}"
                })
                
            return f"{len(formatted_results)}๊ฐœ์˜ ์œ ์‚ฌ ๊ฐ์ฒด๋ฅผ ์ฐพ์•˜์Šต๋‹ˆ๋‹ค.", formatted_results
        else:
            return f"API ์˜ค๋ฅ˜: {response.status_code}", []
    except Exception as e:
        return f"์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}", []

# Define model inference functions
def process_yolo(image):
    if yolo_model is None:
        return None, "YOLOv8 model not loaded", None
    
    # Measure inference time
    import time
    start_time = time.time()
    
    # Convert to numpy if it's a PIL image
    if isinstance(image, Image.Image):
        image_np = np.array(image)
    else:
        image_np = image
        
    # Run inference
    results = yolo_model(image_np)
    
    # Process results
    result_image = results[0].plot()
    result_image = Image.fromarray(result_image)
    
    # Get detection information
    boxes = results[0].boxes
    class_names = results[0].names
    
    # Format detection results
    detections = []
    detection_objects = {'objects': []}
    
    for box in boxes:
        class_id = int(box.cls[0].item())
        class_name = class_names[class_id]
        confidence = round(box.conf[0].item(), 2)
        bbox = box.xyxy[0].tolist()
        bbox = [round(x) for x in bbox]
        
        detections.append("{}: {} at {}".format(class_name, confidence, bbox))
        
        # ๋ฒกํ„ฐ DB ์ €์žฅ์šฉ ๊ฐ์ฒด ์ •๋ณด ์ถ”๊ฐ€
        detection_objects['objects'].append({
            'class': class_name,
            'confidence': confidence,
            'bbox': bbox
        })
    
    # Calculate inference time
    inference_time = time.time() - start_time
    
    # Add inference time and device info to detection text
    device_info = "GPU" if torch.cuda.is_available() else "CPU"
    performance_info = f"\n\nInference time: {inference_time:.3f} seconds on {device_info}"
    detection_text = "\n".join(detections) if detections else "No objects detected"
    detection_text += performance_info
    
    return result_image, detection_text, detection_objects
    
    return result_image, detection_text

def process_detr(image):
    if detr_model is None or detr_processor is None:
        return None, "DETR model not loaded"
    
    # Measure inference time
    import time
    start_time = time.time()
    
    # Prepare image for the model
    inputs = detr_processor(images=image, return_tensors="pt")
    
    # Run inference
    with torch.no_grad():
        outputs = detr_model(**inputs)
    
    # Convert outputs to image with bounding boxes
    # Create tensor with original image dimensions (height, width)
    # image.size[::-1] reverses the (width, height) to (height, width) as required by DETR
    target_sizes = torch.tensor([image.size[::-1]])
    
    # Process raw model outputs into usable detection results
    # - Maps predictions back to original image size
    # - Filters detections using confidence threshold (0.9)
    # - Returns a dictionary with 'scores', 'labels', and 'boxes' keys
    # - [0] extracts results for the first (and only) image in the batch
    results = detr_processor.post_process_object_detection(
        outputs, target_sizes=target_sizes, threshold=0.9
    )[0]
    
    # Create a copy of the image to draw on
    result_image = image.copy()
    import matplotlib.pyplot as plt
    from matplotlib.patches import Rectangle
    import io
    
    # Create figure and axes
    fig, ax = plt.subplots(1)
    ax.imshow(result_image)
    
    # Format detection results
    detections = []
    for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
        box = [round(i) for i in box.tolist()]
        class_name = detr_model.config.id2label[label.item()]
        confidence = round(score.item(), 2)
        
        # Draw rectangle
        rect = Rectangle((box[0], box[1]), box[2] - box[0], box[3] - box[1],
                         linewidth=2, edgecolor='r', facecolor='none')
        ax.add_patch(rect)
        
        # Add label
        plt.text(box[0], box[1], "{}: {}".format(class_name, confidence), 
                 bbox=dict(facecolor='white', alpha=0.8))
        
        detections.append("{}: {} at {}".format(class_name, confidence, box))
    
    # Save figure to image
    buf = io.BytesIO()
    plt.tight_layout()
    plt.axis('off')
    plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0)
    buf.seek(0)
    result_image = Image.open(buf)
    plt.close(fig)
    
    # Calculate inference time
    inference_time = time.time() - start_time
    
    # Add inference time and device info to detection text
    device_info = "GPU" if torch.cuda.is_available() else "CPU"
    performance_info = f"\n\nInference time: {inference_time:.3f} seconds on {device_info}"
    detection_text = "\n".join(detections) if detections else "No objects detected"
    detection_text += performance_info
    
    return result_image, detection_text

def process_vit(image):
    if vit_model is None or vit_processor is None:
        return "ViT model not loaded"
    
    # Measure inference time
    import time
    start_time = time.time()
    
    # Prepare image for the model
    inputs = vit_processor(images=image, return_tensors="pt")
    
    # Run inference
    with torch.no_grad():
        outputs = vit_model(**inputs)
        # Extract raw logits (unnormalized scores) from model output
        # Hugging Face models return logits directly, not probabilities
        logits = outputs.logits
    
    # Get the predicted class
    # argmax(-1) finds the index with highest score across the last dimension (class dimension)
    # item() converts the tensor value to a Python scalar
    predicted_class_idx = logits.argmax(-1).item()
    # Map the class index to human-readable label using the model's configuration
    prediction = vit_model.config.id2label[predicted_class_idx]
    
    # Get top 5 predictions
    # Apply softmax to convert raw logits to probabilities
    # softmax normalizes the exponentials of logits so they sum to 1.0
    # dim=-1 applies softmax along the class dimension
    # Shape before softmax: [1, num_classes] (batch_size=1, num_classes=1000)
    # [0] extracts the first (and only) item from the batch dimension
    # Shape after [0]: [num_classes] (a 1D tensor with 1000 class probabilities)
    probs = torch.nn.functional.softmax(logits, dim=-1)[0]
    # Get the values and indices of the 5 highest probabilities
    top5_prob, top5_indices = torch.topk(probs, 5)
    
    results = []
    for i, (prob, idx) in enumerate(zip(top5_prob, top5_indices)):
        class_name = vit_model.config.id2label[idx.item()]
        results.append("{}. {}: {:.3f}".format(i+1, class_name, prob.item()))
    
    # Calculate inference time
    inference_time = time.time() - start_time
    
    # Add inference time and device info to results
    device_info = "GPU" if torch.cuda.is_available() else "CPU"
    performance_info = f"\n\nInference time: {inference_time:.3f} seconds on {device_info}"
    result_text = "\n".join(results)
    result_text += performance_info
    
    return result_text

# Define Gradio interface
with gr.Blocks(title="Object Detection Demo") as demo:
    gr.Markdown("""
    # Multi-Model Object Detection Demo
    
    This demo showcases three different object detection and image classification models:
    - **YOLOv8**: Fast and accurate object detection
    - **DETR**: DEtection TRansformer for object detection
    - **ViT**: Vision Transformer for image classification
    
    Upload an image to see how each model performs!
    """)
    
    with gr.Row():
        input_image = gr.Image(type="pil", label="Input Image")
    
    with gr.Row():
        yolo_button = gr.Button("Detect with YOLOv8")
        detr_button = gr.Button("Detect with DETR")
        vit_button = gr.Button("Classify with ViT")
    
    with gr.Row():
        with gr.Column():
            yolo_output = gr.Image(type="pil", label="YOLOv8 Detection")
            yolo_text = gr.Textbox(label="YOLOv8 Results")
        
        with gr.Column():
            detr_output = gr.Image(type="pil", label="DETR Detection")
            detr_text = gr.Textbox(label="DETR Results")
        
        with gr.Column():
            vit_text = gr.Textbox(label="ViT Classification Results")
    
    # ๋ฒกํ„ฐ DB ์ €์žฅ ๋ฒ„ํŠผ ๋ฐ ๊ฒฐ๊ณผ ํ‘œ์‹œ
    with gr.Row():
        with gr.Column():
            gr.Markdown("### ๋ฒกํ„ฐ DB ์ €์žฅ")
            save_yolo_button = gr.Button("YOLOv8 ์ธ์‹ ๊ฒฐ๊ณผ ์ €์žฅ", variant="primary")
            save_detr_button = gr.Button("DETR ์ธ์‹ ๊ฒฐ๊ณผ ์ €์žฅ", variant="primary")
            save_vit_button = gr.Button("ViT ๋ถ„๋ฅ˜ ๊ฒฐ๊ณผ ์ €์žฅ", variant="primary")
            save_result = gr.Textbox(label="๋ฒกํ„ฐ DB ์ €์žฅ ๊ฒฐ๊ณผ")
        
        with gr.Column():
            gr.Markdown("### ๋ฒกํ„ฐ DB ๊ฒ€์ƒ‰")
            search_class = gr.Textbox(label="ํด๋ž˜์Šค ์ด๋ฆ„์œผ๋กœ ๊ฒ€์ƒ‰")
            search_button = gr.Button("๊ฒ€์ƒ‰", variant="secondary")
            search_result_text = gr.Textbox(label="๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ ์ •๋ณด")
            search_result_gallery = gr.Gallery(label="๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ", columns=5, height=300)
    
    # ๊ฐ์ฒด ์ธ์‹ ๊ฒฐ๊ณผ ์ €์žฅ์šฉ ์ƒํƒœ ๋ณ€์ˆ˜
    yolo_detection_state = gr.State(None)
    detr_detection_state = gr.State(None)
    vit_classification_state = gr.State(None)
    
    # Set up event handlers
    yolo_button.click(
        fn=process_yolo,
        inputs=input_image,
        outputs=[yolo_output, yolo_text, yolo_detection_state]
    )
    
    # DETR ๊ฒฐ๊ณผ ์ฒ˜๋ฆฌ ํ•จ์ˆ˜ ์ˆ˜์ • - ์ƒํƒœ ์ €์žฅ ์ถ”๊ฐ€
    def process_detr_with_state(image):
        result_image, result_text = process_detr(image)
        
        # ๊ฐ์ฒด ์ธ์‹ ๊ฒฐ๊ณผ ์ถ”์ถœ
        detection_results = {"objects": []}
        
        # ๊ฒฐ๊ณผ ํ…์ŠคํŠธ์—์„œ ๊ฐ์ฒด ์ •๋ณด ์ถ”์ถœ
        lines = result_text.split('\n')
        for line in lines:
            if ': ' in line and ' at ' in line:
                try:
                    class_conf, location = line.split(' at ')
                    class_name, confidence = class_conf.split(': ')
                    confidence = float(confidence)
                    
                    # ๋ฐ”์šด๋”ฉ ๋ฐ•์Šค ์ •๋ณด ์ถ”์ถœ
                    bbox_str = location.strip('[]').split(', ')
                    bbox = [int(coord) for coord in bbox_str]
                    
                    detection_results["objects"].append({
                        "class": class_name,
                        "confidence": confidence,
                        "bbox": bbox
                    })
                except Exception:
                    pass
        
        return result_image, result_text, detection_results
    
    # ViT ๊ฒฐ๊ณผ ์ฒ˜๋ฆฌ ํ•จ์ˆ˜ ์ˆ˜์ • - ์ƒํƒœ ์ €์žฅ ์ถ”๊ฐ€
    def process_vit_with_state(image):
        result_text = process_vit(image)
        
        # ๋ถ„๋ฅ˜ ๊ฒฐ๊ณผ ์ถ”์ถœ
        classifications = []
        
        # ๊ฒฐ๊ณผ ํ…์ŠคํŠธ์—์„œ ๋ถ„๋ฅ˜ ์ •๋ณด ์ถ”์ถœ
        lines = result_text.split('\n')
        for line in lines:
            if '. ' in line and ': ' in line:
                try:
                    rank_class, confidence = line.split(': ')
                    _, class_name = rank_class.split('. ')
                    confidence = float(confidence)
                    
                    classifications.append({
                        "class": class_name,
                        "confidence": confidence
                    })
                except Exception:
                    pass
        
        return result_text, {"classifications": classifications}
    
    detr_button.click(
        fn=process_detr_with_state,
        inputs=input_image,
        outputs=[detr_output, detr_text, detr_detection_state]
    )
    
    vit_button.click(
        fn=process_vit_with_state,
        inputs=input_image,
        outputs=[vit_text, vit_classification_state]
    )
    
    # ๋ฒกํ„ฐ DB ์ €์žฅ ๋ฒ„ํŠผ ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ
    save_yolo_button.click(
        fn=lambda img, det: save_objects_to_vector_db(img, det, 'yolo'),
        inputs=[input_image, yolo_detection_state],
        outputs=save_result
    )
    
    save_detr_button.click(
        fn=lambda img, det: save_objects_to_vector_db(img, det, 'detr'),
        inputs=[input_image, detr_detection_state],
        outputs=save_result
    )
    
    save_vit_button.click(
        fn=lambda img, det: save_objects_to_vector_db(img, det, 'vit'),
        inputs=[input_image, vit_classification_state],
        outputs=save_result
    )
    
    # ๊ฒ€์ƒ‰ ๋ฒ„ํŠผ ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ
    def format_search_results(result_text, results):
        images = []
        captions = []
        
        for result in results:
            if result.get('image'):
                images.append(result['image'])
                captions.append(result['info'])
        
        return result_text, [(img, cap) for img, cap in zip(images, captions)]
    
    search_button.click(
        fn=lambda class_name: search_similar_objects(class_name=class_name),
        inputs=search_class,
        outputs=[search_result_text, search_result_gallery]
    )
    
   

# Launch the app
if __name__ == "__main__":
    demo.launch()