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('', obj.image.url) return "No Image" thumbnail.short_description = 'Preview' def thumbnail_large(self, obj): if obj.image: return format_html('', 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('
{}
', 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',) }), )