Spaces:
Sleeping
Sleeping
| from django.contrib import admin | |
| from django.utils.html import format_html | |
| from .models import Detection | |
| from .utils import run_detection | |
| import json | |
| 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)' | |
| 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',) | |
| }), | |
| ) | |