File size: 2,609 Bytes
1624b73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from django.contrib import admin
from django.utils.html import format_html
from .models import Detection
from .utils import run_detection
import json

@admin.register(Detection)
class DetectionAdmin(admin.ModelAdmin):
    list_display = ('id', 'thumbnail', 'user', 'object_count', 'top_labels', 'created_at')
    list_filter = ('created_at', 'user')
    search_fields = ('results', 'user__username')
    readonly_fields = ('thumbnail_large', 'formatted_results', 'created_at')
    actions = ['re_analyze_detections']

    def thumbnail(self, obj):
        if obj.image:
            return format_html('<img src="{}" style="width: 50px; height: auto; border-radius: 4px;" />', obj.image.url)
        return "No Image"
    thumbnail.short_description = 'Preview'

    def thumbnail_large(self, obj):
        if obj.image:
            return format_html('<img src="{}" style="max-width: 100%; height: auto; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);" />', obj.image.url)
        return "No Image"
    thumbnail_large.short_description = 'Image View'

    def object_count(self, obj):
        return len(obj.results) if obj.results else 0
    object_count.short_description = 'Objects Found'

    def top_labels(self, obj):
        if not obj.results:
            return "-"
        labels = [item['label'] for item in obj.results]
        unique_labels = list(set(labels))
        return ", ".join(unique_labels[:3]) + ("..." if len(unique_labels) > 3 else "")
    top_labels.short_description = 'Main Detections'

    def formatted_results(self, obj):
        return format_html('<pre style="background: #f4f4f4; padding: 10px; border-radius: 4px; max-height: 400px; overflow: auto;">{}</pre>', 
                           json.dumps(obj.results, indent=2))
    formatted_results.short_description = 'Analysis Data (JSON)'

    @admin.action(description='Re-analyze selected detections with AI')
    def re_analyze_detections(self, request, queryset):
        count = 0
        for obj in queryset:
            if obj.image:
                detections = run_detection(obj.image.path)
                obj.results = detections
                obj.save()
                count += 1
        self.message_user(request, f"Successfully re-analyzed {count} images.")

    fieldsets = (
        ('General Information', {
            'fields': ('user', 'image', 'created_at')
        }),
        ('Visual Analysis', {
            'fields': ('thumbnail_large',)
        }),
        ('Detailed Results', {
            'fields': ('formatted_results',),
            'classes': ('collapse',)
        }),
    )