Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

photos #78

Merged
merged 11 commits into from
Apr 16, 2024
70 changes: 35 additions & 35 deletions FRONTEND/fastparking/finance/templates/finance/payed.html
Original file line number Diff line number Diff line change
@@ -1,42 +1,42 @@
<!-- У вашому файлі add_tariff.html -->
{% extends "parking/base.html" %}
{% block content %}
<div class="container" id="payment_result">
<h2>Payment Results</h2>
<table class="table">
<thead>
<tr>
<th>Field Name</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for field, value in payment.items %}
<tr>
<td>{{ field }}:</td>
<td>{{ value | safe }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% extends "parking/base.html" %} {% block content %}
<div class="container" id="payment_result">
<h2>Payment Results</h2>
<table class="table">
<thead>
<tr>
<th>Field Name</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for field, value in payment.items %}
<tr>
<td>{{ field }}:</td>
<td>{{ value | safe }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>

<p><a class="btn btn-primary" href="{% url 'finance:main' %}">MAIN</a>
<button onclick="printDiv('payment_result')" class="btn btn-primary">Print</button>
<p>
<a class="btn btn-primary" href="{% url 'finance:main' %}">MAIN</a>
<button onclick="printDiv('payment_result')" class="btn btn-primary">Print</button>
</p>

<script>
function printPage() {
window.print(); // Trigger print functionality
}
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
<script>
function printPage() {
window.print(); // Trigger print functionality
}
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;

document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = printContents;
window.print();

document.body.innerHTML = originalContents;
}
</script>
document.body.innerHTML = originalContents;
}
</script>
{% endblock content %}
5 changes: 4 additions & 1 deletion FRONTEND/fastparking/parking/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from django.contrib import admin

# Register your models here.
from .models import ParkingSpace, Registration

admin.site.register(ParkingSpace)
admin.site.register(Registration)
86 changes: 83 additions & 3 deletions FRONTEND/fastparking/photos/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,88 @@
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User

from parking.models import Registration
from .repository import TYPES

TOTAL_DIGITS_ID = 6


class UploadFileForm(forms.Form):
choices = [("0", "IN"), ("1", "OUT")]
type = forms.ChoiceField(choices=choices)
photo = forms.ImageField()
choices = TYPES.items() # [(k, v) for k, v in TYPES.items()]
type = forms.ChoiceField(
choices=choices,
widget=forms.Select(
attrs={
"class": "form-select",
"title": "What type of photo is uploaded? IN - for cars entering, OUT - for cars leaving.",
} # ,
),
)
photo = forms.ImageField(
widget=forms.FileInput(
attrs={
"class": "form-control",
"title": "Upload photo of car",
} # ,
),
)

registration_id = forms.ModelChoiceField(
queryset=Registration.objects.all(),
required=False, # Set it to True if it's required
widget=forms.Select(
attrs={
"class": "form-select",
"title": "Select the Registration number you want to pay from the list",
}
),
help_text="Select the Registration number you want to pay from the list",
)

manual_registration_id = forms.DecimalField(
min_value=1,
max_digits=TOTAL_DIGITS_ID,
max_value=10**TOTAL_DIGITS_ID - 1,
required=False,
widget=forms.NumberInput(
attrs={
"class": "form-control col-8",
"placeholder": "X" * TOTAL_DIGITS_ID,
"title": "Enter a valid registration ID with which you want to OUT",
} # ,
),
# help_text="Enter a valid registration ID with which you want to pay",
)

def clean(self):
cleaned_data = super().clean()
registration_id = cleaned_data.get("registration_id")
manual_registration_id = cleaned_data.get("manual_registration_id")

if not registration_id and not manual_registration_id:
raise forms.ValidationError(
"Please select a registration ID from the list or enter it manually."
)

if registration_id:
# If registration_id is selected from the list, set manual_registration_id to None
cleaned_data["manual_registration_id"] = None
elif not manual_registration_id:
# If manual_registration_id is not provided and registration_id is not selected from the list, raise validation error
raise forms.ValidationError(
"Please select a registration ID from the list or enter it manually."
)
else:
cleaned_data["registration_id"] = manual_registration_id
return cleaned_data

def clean_manual_registration_id(self):
manual_registration_id = self.cleaned_data.get("manual_registration_id")
if manual_registration_id:
# Check if the manual_registration_id exists in the list of Registration.registration_id
if not Registration.objects.filter(pk=manual_registration_id).exists():
raise forms.ValidationError("Entered registration ID does not exist.")
return manual_registration_id

# class Meta:
# fields = ["registration_id", "manual_registration_id"]
86 changes: 75 additions & 11 deletions FRONTEND/fastparking/photos/repository.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import base64
from datetime import datetime
from io import BytesIO
from pathlib import Path
from django.conf import settings
from django.core import signing
import qrcode

from ds.predict_num import get_num_auto_png_io

Expand All @@ -21,10 +24,12 @@ def db_save_photo_information(predict: dict, type: str) -> int | None:
record.photo = num_img
record.type = type
record.save()
return record.id
return record.pk


def save_image(f, type: str = "", filepath: Path | None = None):
def save_image(
f, type: str = "", filepath: Path | None = None, filename: str | None = None
):
if filepath is None:
if settings.MEDIA_ROOT:
utc_datetime = datetime.utcnow()
Expand All @@ -33,8 +38,11 @@ def save_image(f, type: str = "", filepath: Path | None = None):
TYPES.get(type)
)
media.mkdir(parents=True, exist_ok=True)
image_type = "jpg"
filepath = media.joinpath(f"{file_date}.{image_type}")
if filename:
image_type = Path(filename).suffix
else:
image_type = ".jpg"
filepath = media.joinpath(f"{file_date}{image_type}")
if f and filepath:
with filepath.open("wb+") as destination:
for chunk in f.chunks():
Expand All @@ -54,13 +62,49 @@ def build_html_image(binary_image_data):
return f'<img src="data:image/jpeg;base64,{base64_image_data}">'


def handle_uploaded_file(f, type: str | None) -> dict[str, dict]:
def build_qrcode(qr_data) -> str:
qr = qrcode.QRCode( # type: ignore
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_M, # type: ignore
box_size=6,
border=2,
)
qr.add_data(qr_data)
qr.make(fit=True)
img = qr.make_image(fill_color=(56, 64, 88), back_color="white")

# img = qrcode.make(qr_data, border=2)
mem_file = BytesIO()
img.save(mem_file)
mem_file.seek(0)
return build_base64_image(mem_file.getvalue())


def sign_text(text):
signer = signing.Signer()
encoded_text = signer.sign(text)
return encoded_text


def unsign_text(text):
signer = signing.Signer()
try:
original = signer.unsign(text)
return original
except signing.BadSignature:
print("Tampering detected!")
return None


def handle_uploaded_file(
f, type: str | None, filename: str | None = None, registration_id: str | None = None
) -> dict[str, dict]:
if f and type:
utc_datetime = datetime.utcnow()
info = f"File accepted, sizes: {len(f) // 1024} KB, {type=}"
info = f"File accepted, sizes: {len(f) // 1024} KB, {TYPES.get(type)}, {filename=}."
# try to save
# try:
# save_image(f, type=type)
# save_image(f, type=type, filename)
# except Exception:
# ...

Expand All @@ -70,11 +114,31 @@ def handle_uploaded_file(f, type: str | None) -> dict[str, dict]:
photo_id = db_save_photo_information(predict, type)
# registration
num_auto = predict.get("num_avto_str")
registration_data = {"photo_id": photo_id, "num_auto": num_auto, "type": type}
registration_car(utc_datetime, registration_data)
registration_data = {
"photo_id": photo_id,
"num_auto": num_auto,
"type": type,
"registration_id": registration_id,
}
registration_result = registration_car(utc_datetime, registration_data)
# prepare for show on web page
binary_image_data = predict.get("num_img")
if binary_image_data:
base64_image = base64.b64encode(binary_image_data).decode("utf-8")
base64_image = build_base64_image(binary_image_data)
predict["num_img"] = base64_image
return {"info": info, "predict": predict}
date_formated = utc_datetime.strftime("%Y-%m-%d %H:%M:%S UTC")
registration_id = 1
registration_id_formatted = f"{registration_id:06}"
parking_place = "L01-01"
reg_info = f"id:{registration_id},place:{parking_place},date:{int(utc_datetime.timestamp())}|"
encoded_text = sign_text(reg_info)
hash_code = encoded_text.split("|:")[-1]
qrcode_img = build_qrcode(encoded_text)
registration = {
"id": registration_id_formatted,
"parking_place": parking_place,
"qr_code": qrcode_img,
"date": date_formated,
"hash": hash_code,
}
return {"info": info, "predict": predict, "registration": registration}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
49 changes: 32 additions & 17 deletions FRONTEND/fastparking/photos/templates/photos/main.html
Original file line number Diff line number Diff line change
@@ -1,28 +1,43 @@
{% extends "parking/base.html" %}
{% block content %}
{% extends "parking/base.html" %} {% block content %} {% load static %}
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="row">
<!-- <div class="col-md-4">
<div class="card bg-primary">
<div class="card-body">
<a href="{% url 'photos:upload' %}" class="btn btn-primary btn-lg btn-block">Upload photo of car</a>
</div>
</div>
</div> -->
<div class="col-md-4">
<div class="card bg-primary">
<div class="card-body mx-auto text-center">
<a href="{% url 'photos:upload' %}?type=0" class="btn btn-primary btn-lg btn-block">
<img
width="270"
height="270"
src="{% static 'photos/button_in_01_270x270.gif' %}"
title="Upload IN photo of car"
alt="Upload IN photo of car"
/></a>
<p>Upload IN photo of car</p>
</div>
<div class="col-md-4">
<div class="card bg-primary">
<div class="card-body">
<a href="{% url 'photos:upload' %}?type=0" class="btn btn-primary btn-lg btn-block">Upload IN photo of car</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card bg-primary">
<div class="card-body">
<a href="{% url 'photos:upload' %}?type=1" class="btn btn-primary btn-lg btn-block">Upload OUT photo of car</a>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card bg-success">
<div class="card-body mx-auto text-center">
<a href="{% url 'photos:upload' %}?type=1" class="btn btn-secondary btn-lg btn-block"
><img
width="270"
height="270"
src="{% static 'photos/button_out_01_270x270.gif' %}"
title="Upload OUT photo of car"
alt="Upload OUT photo of car"
/></a>
<p>Upload OUT photo of car</p>
</div>
</div>
</div>
</div>
</div>
{% endblock content %}
Loading
Loading