0% found this document useful (0 votes)
9 views4 pages

Analystic

Uploaded by

naveen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views4 pages

Analystic

Uploaded by

naveen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

Here's the full code for the "analytics" module, including models, serializers,

views, and URLs, with the addition of a pie chart for displaying analytics data
based on the "detection" module's database:

Models

In analytics/models.py:

# analytics/models.py
from django.db import models
from django.contrib.auth import get_user_model
from cameras.models import Camera

User = get_user_model()

class WeeklyAnalytics(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
camera = models.ForeignKey(Camera, on_delete=models.CASCADE)
week_start = models.DateField()
people_count = models.IntegerField(default=0)
individual_traffic = models.JSONField(default=dict)
people_count_by_hour = models.JSONField(default=dict)
known_faces_count = models.IntegerField(default=0)
unknown_faces_count = models.IntegerField(default=0)

def __str__(self):
return f"Weekly Analytics for {self.camera} ({self.week_start} -
{self.week_start + datetime.timedelta(days=6)})"

class DateBasedAnalytics(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
camera = models.ForeignKey(Camera, on_delete=models.CASCADE)
date = models.DateField()
people_count = models.IntegerField(default=0)
individual_traffic = models.JSONField(default=dict)
people_count_by_hour = models.JSONField(default=dict)
known_faces_count = models.IntegerField(default=0)
unknown_faces_count = models.IntegerField(default=0)

def __str__(self):
return f"Date-Based Analytics for {self.camera} on {self.date}"

Serializers

In analytics/serializers.py:

# analytics/serializers.py
from rest_framework import serializers
from .models import WeeklyAnalytics, DateBasedAnalytics

class WeeklyAnalyticsSerializer(serializers.ModelSerializer):
class Meta:
model = WeeklyAnalytics
fields = ['id', 'camera', 'week_start', 'people_count',
'individual_traffic', 'people_count_by_hour', 'known_faces_count',
'unknown_faces_count']
class DateBasedAnalyticsSerializer(serializers.ModelSerializer):
class Meta:
model = DateBasedAnalytics
fields = ['id', 'camera', 'date', 'people_count', 'individual_traffic',
'people_count_by_hour', 'known_faces_count', 'unknown_faces_count']

Views

In analytics/views.py:

# analytics/views.py
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from .serializers import WeeklyAnalyticsSerializer, DateBasedAnalyticsSerializer
from .models import WeeklyAnalytics, DateBasedAnalytics
from matplotlib import pyplot as plt
from detection.models import PersonDetection, FaceRecognition

class WeeklyAnalyticsListView(ListAPIView):
permission_classes = [IsAuthenticated]
serializer_class = WeeklyAnalyticsSerializer

def get_queryset(self):
user = self.request.user
return WeeklyAnalytics.objects.filter(user=user)

class WeeklyAnalyticsRetrieveView(RetrieveAPIView):
permission_classes = [IsAuthenticated]
serializer_class = WeeklyAnalyticsSerializer

def get_queryset(self):
user = self.request.user
camera_id = self.kwargs['camera_id']
return WeeklyAnalytics.objects.filter(user=user, camera__id=camera_id)

def get(self, request, *args, **kwargs):


instance = self.get_object()
people_count_by_hour = instance.people_count_by_hour
known_faces_count = PersonDetection.objects.filter(user=user,
camera__id=camera_id, is_known=True).count()
unknown_faces_count = PersonDetection.objects.filter(user=user,
camera__id=camera_id, is_known=False).count()

# Generate a pie chart for people count by hour


labels = ['Known Faces', 'Unknown Faces']
sizes = [known_faces_count, unknown_faces_count]
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
ax.axis('equal')
plt.savefig('people_count_by_hour.png')

# Include the pie chart image in the response


with open('people_count_by_hour.png', 'rb') as f:
image_data = f.read()
return Response({
'people_count_by_hour': people_count_by_hour,
'known_faces_count': known_faces_count,
'unknown_faces_count': unknown_faces_count,
'pie_chart_image': image_data,
}, status=status.HTTP_200_OK)

class DateBasedAnalyticsListView(ListAPIView):
permission_classes = [IsAuthenticated]
serializer_class = DateBasedAnalyticsSerializer

def get_queryset(self):
user = self.request.user
return DateBasedAnalytics.objects.filter(user=user)

class DateBasedAnalyticsRetrieveView(RetrieveAPIView):
permission_classes = [IsAuthenticated]
serializer_class = DateBasedAnalyticsSerializer

def get_queryset(self):
user = self.request.user
camera_id = self.kwargs['camera_id']
date = self.kwargs['date']
return DateBasedAnalytics.objects.filter(user=user, camera__id=camera_id,
date=date)

def get(self, request, *args, **kwargs):


instance = self.get_object()
people_count_by_hour = instance.people_count_by_hour
known_faces_count = FaceRecognition.objects.filter(user=user,
camera__id=camera_id, is_known=True).count()
unknown_faces_count = FaceRecognition.objects.filter(user=user,
camera__id=camera_id, is_known=False).count()

# Generate a pie chart for people count by hour


labels = ['Known Faces', 'Unknown Faces']
sizes = [known_faces_count, unknown_faces_count]
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
ax.axis('equal')
plt.savefig('people_count_by_hour.png')

# Include the pie chart image in the response


with open('people_count_by_hour.png', 'rb') as f:
image_data = f.read()

return Response({
'people_count_by_hour': people_count_by_hour,
'known_faces_count': known_faces_count,
'unknown_faces_count': unknown_faces_count,
'pie_chart_image': image_data,
}, status=status.HTTP_200_OK)

URLs

In analytics/urls.py:

# analytics/urls.py
from django.urls import path
from .views import WeeklyAnalyticsListView, WeeklyAnalyticsRetrieveView,
DateBasedAnalyticsListView, DateBasedAnalyticsRetrieveView

urlpatterns = [
path('analytics/weekly/', WeeklyAnalyticsListView.as_view(),
name='weekly_analytics_list'),
path('analytics/weekly/<int:camera_id>/',
WeeklyAnalyticsRetrieveView.as_view(), name='weekly_analytics_retrieve'),
path('analytics/date-based/', DateBasedAnalyticsListView.as_view(),
name='date_based_analytics_list'),
path('analytics/date-based/<int:camera_id>/<str:date>/',
DateBasedAnalyticsRetrieveView.as_view(), name='date_based_analytics_retrieve'),
]

Testing

You can now test the analytics retrieval endpoints using curl or a REST client. The
response will include a JSON object with the people count by hour data, known faces
count, unknown faces count, and a pie chart image:

# Retrieve weekly analytics with pie chart


curl -X GET -H "Authorization: JWT <access_token>"
http://127.0.0.1:8000/analytics/weekly/1/

# Retrieve date-based analytics with pie chart


curl -X GET -H "Authorization: JWT <access_token>"
http://127.0.0.1:8000/analytics/date-based/1/2023-08-25/

Conclusion:

With this code, you've implemented the "analytics" module, providing weekly and
date-based insights for user cameras. The system displays a pie chart for people
count by hour, along with the count of known and unknown faces. The module offers
valuable insights for security and monitoring purposes, and the pie chart enhances
the visual representation of the data.

You might also like