Skip to content

Commit

Permalink
build back-end
Browse files Browse the repository at this point in the history
  • Loading branch information
igoorsimoess committed Dec 21, 2022
1 parent a1db1af commit 70d4ff3
Show file tree
Hide file tree
Showing 33 changed files with 8,201 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.venv
back-end/back-end/bin/
back-end/back-end/lib/
back-end/back-end/share/
/yolov5/
8 changes: 8 additions & 0 deletions back-end/back-end/pyvenv.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
home = /usr
implementation = CPython
version_info = 3.8.10.final.0
virtualenv = 20.0.17
include-system-site-packages = false
base-prefix = /usr
base-exec-prefix = /usr
base-executable = /usr/bin/python3
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
16 changes: 16 additions & 0 deletions back-end/back-end/src/CV/CV/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for CV project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CV.settings")

application = get_asgi_application()
139 changes: 139 additions & 0 deletions back-end/back-end/src/CV/CV/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
"""
Django settings for CV project.
Generated by 'django-admin startproject' using Django 4.1.4.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path

import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-q8_s3ygz6-xq$_fs(u9y#fw(xr&=lbo!8_!xxzyk2tpvpoxun2"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
'rest_framework',
'ImageDetection',
]

MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "CV.urls"

TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]

WSGI_APPLICATION = "CV.wsgi.application"


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}


# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]


# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = "static/"

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
}

# sets the URL which stores the image

MEDIA_URL = '/media/'

# sets the absolute path to each instance storage

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
33 changes: 33 additions & 0 deletions back-end/back-end/src/CV/CV/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""CV URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from ImageDetection import views

from django.conf.urls.static import static
from django.conf import settings
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

urlpatterns = [
path("admin/", admin.site.urls),
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # specifies the route django will search when the occurrence_image field is called


16 changes: 16 additions & 0 deletions back-end/back-end/src/CV/CV/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for CV project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CV.settings")

application = get_wsgi_application()
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
5 changes: 5 additions & 0 deletions back-end/back-end/src/CV/ImageDetection/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.contrib import admin
from . import models
# Register your models here.

admin.site.register(models.ImageDetection)
6 changes: 6 additions & 0 deletions back-end/back-end/src/CV/ImageDetection/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class ImagedetectionConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "ImageDetection"
39 changes: 39 additions & 0 deletions back-end/back-end/src/CV/ImageDetection/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Generated by Django 4.1.4 on 2022-12-21 05:51

import ImageDetection.models
from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = []

operations = [
migrations.CreateModel(
name="ImageDetection",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("created_at", models.DateTimeField(auto_now_add=True)),
(
"image",
models.ImageField(
null=True, upload_to=ImageDetection.models.upload_image
),
),
(
"model_evaluation",
models.JSONField(blank=True, default=list, null=True),
),
],
),
]
Empty file.
Binary file not shown.
15 changes: 15 additions & 0 deletions back-end/back-end/src/CV/ImageDetection/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from django.db import models
import torch
import pandas
# Create your models here.

def upload_image(object, filename):
return f'{object.create_at}--{filename}'


class ImageDetection(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to=upload_image, blank=False, null=True)
model_evaluation = models.JSONField(default=list, blank=True, null=True)


22 changes: 22 additions & 0 deletions back-end/back-end/src/CV/ImageDetection/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from django.contrib.auth.models import User, Group
from .models import ImageDetection
from rest_framework import serializers

class UserSerializer(serializers.HyperlinkedModelSerializer):
groups = []
serializers.HyperlinkedIdentityField(view_name="rest_framework:user-detail")
class Meta:
model = User
fields = ['url', 'username', 'email', 'groups']


class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ['url', 'name']


class ImageDetectionSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ImageDetection
fields = ["create_at", "image", "model_evaluation", "model_evaluation_dict"]
3 changes: 3 additions & 0 deletions back-end/back-end/src/CV/ImageDetection/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
39 changes: 39 additions & 0 deletions back-end/back-end/src/CV/ImageDetection/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from django.contrib.auth.models import User, Group
from .models import ImageDetection
from rest_framework import viewsets
from rest_framework import permissions
from ImageDetection.serializers import UserSerializer, GroupSerializer, ImageDetectionSerializer
import torch
from rest_framework.decorators import action
# queryset = Group.objects.all().order_by()
from rest_framework.decorators import action
# Create your views here.
import os

class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]


class GroupViewSet(viewsets.ModelViewSet):
queryset = Group.objects.all()
serializer_class = GroupSerializer
permission_classes = [permissions.IsAuthenticated]

class ImageDetectionViewSet(viewsets.ModelViewSet):
queryset = ImageDetection.objects.all()
serializer_class = ImageDetectionSerializer
permission_classes = [permissions.IsAuthenticated]

model_state_dict = torch.load('../../../../resources/PS_TAIL.pt')
model = torch.hub.load('../../../../yolov5', 'custom', path='../../../../resources/best.pt', source='local')
model_loaded = model.load_state_dict(model_state_dict)
folder_path = os.path.join("")

@action(method=["POST"], url_path='evaluate', detail=False)
def evaluate(self, request, model=model_loaded):
image = request.query_params["image"]
model_evaluation = model(image)
model_evaluation_dict = model_evaluation.pandas().xyxy[0].to_dict(orient="records")
return model_evaluation_dict
Binary file added back-end/back-end/src/CV/db.sqlite3
Binary file not shown.
22 changes: 22 additions & 0 deletions back-end/back-end/src/CV/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CV.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)


if __name__ == "__main__":
main()
Loading

0 comments on commit 70d4ff3

Please sign in to comment.