62 lines
2.8 KiB
Python
62 lines
2.8 KiB
Python
from rest_framework import viewsets, permissions, status
|
|
from rest_framework.response import Response
|
|
from rest_framework.decorators import action
|
|
from django.db.models import Avg, Count, Q
|
|
from django.utils import timezone
|
|
from datetime import timedelta
|
|
|
|
from api.models import InferenceAuditLog
|
|
from api.serializers.audit_serializer import InferenceAuditLogSerializer
|
|
from permissions.permission_classes import IsAdminOrManager # ใช้สิทธิ์เดียวกันกับ Model Registry
|
|
|
|
class AuditLogViewSet(viewsets.ReadOnlyModelViewSet):
|
|
"""
|
|
API สำหรับการเข้าถึง Inference Audit Log และสถิติรวม
|
|
"""
|
|
queryset = InferenceAuditLog.objects.all()
|
|
serializer_class = InferenceAuditLogSerializer
|
|
permission_classes = [permissions.IsAuthenticated] # อนุญาตให้เข้าถึงเมื่อล็อกอินแล้ว
|
|
|
|
# ใช้ 'id' เป็นฟิลด์ค้นหา
|
|
lookup_field = 'id'
|
|
|
|
# ใช้ 'id' เป็นชื่อพารามิเตอร์ใน URL
|
|
lookup_url_kwarg = 'id'
|
|
|
|
def retrieve(self, request, *args, **kwargs):
|
|
# บังคับให้ Lookup Key (pk) เป็น String
|
|
kwargs[self.lookup_url_kwarg] = str(kwargs[self.lookup_url_kwarg])
|
|
|
|
return super().retrieve(request, *args, **kwargs)
|
|
|
|
def get_queryset(self):
|
|
# คืน Log ล่าสุด 10 รายการ (สำหรับ Recent Events ใน Dashboard)
|
|
return self.queryset.select_related('user')[:10]
|
|
|
|
# -----------------------------------------------
|
|
# Custom Action: ดึงสถิติรวมสำหรับ Dashboard
|
|
# Endpoint: GET /api/v1/audit/inference-summary/
|
|
# -----------------------------------------------
|
|
@action(detail=False, methods=['get'], url_path='inference-summary')
|
|
def get_summary(self, request):
|
|
one_day_ago = timezone.now() - timedelta(hours=24)
|
|
|
|
# 1. คำนวณสถิติรวม (Global Metrics)
|
|
metrics = self.queryset.filter(timestamp__gte=one_day_ago).aggregate(
|
|
total_runs=Count('id'),
|
|
success_count=Count('id', filter=Q(is_success=True)),
|
|
avg_latency_ms=Avg('latency_ms')
|
|
)
|
|
|
|
# 2. คำนวณ Success Rate
|
|
total = metrics.get('total_runs', 0)
|
|
success = metrics.get('success_count', 0)
|
|
success_rate = (success / total) * 100 if total > 0 else 0
|
|
|
|
return Response({
|
|
"time_window": "24 hours",
|
|
"total_runs": total,
|
|
"success_rate": round(success_rate, 2),
|
|
"avg_latency_ms": round(metrics.get('avg_latency_ms', 0) or 0, 2),
|
|
"last_logs": InferenceAuditLogSerializer(self.get_queryset(), many=True).data
|
|
}) |