@Jasper_Holton's profile photo

How to identify and recognize faces using python with no APIs I use the below code to implement a login with face function on Uglek. The code works by assigning a user a face ID when they upload a face to their profile or go to log in, and then retrieving their account by image using the face ID. Here is the code

# face/face.py
from django.contrib.auth.models import User
import uuid
from .models import Face
import face_recognition

NUM_FACES = 9

def get_face_id(image_path):
    image = face_recognition.load_image_file(image_path)
    face_locations = face_recognition.face_locations(image)
    if len(face_locations) > 1 or len(face_locations) < 1:
        return False

    for user in User.objects.filter(profile__enable_facial_recognition=True):
        known_image = face_recognition.load_image_file(user.profile.face.path)
        unknown_image = image
        user_encoding = face_recognition.face_encodings(known_image)[0]
        user_encodings = list()
        user_encodings.append(user_encoding)
        user_faces = Face.objects.filter(user=user).order_by('-timestamp')
        for face in user_faces:
            if open(face.image.path,"rb").read() == open(image_path,"rb").read():
                return False
        if user_faces.count() > NUM_FACES:
            user_faces = user_faces[:NUM_FACES]
        for face in user_faces:
            image = face_recognition.load_image_file(face.image.path)
            image_encoding = face_recognition.face_encodings(image)[0]
            user_encodings.append(image_encoding)
        unknown_encoding = face_recognition.face_encodings(unknown_image)[0]
        results = face_recognition.compare_faces(user_encodings, unknown_encoding)
        if results[0]:
            return user.profile.uuid
    return str(uuid.uuid4())
In action, the code looks like get_face_id(User.objects.get(id=1).face.path) in testing. This gets my face ID from the face uploaded to my profile. To get a face ID of a logging in user, I save a face form with a face object and then call get_face_id(face.image.path) to query the user instance and redirect to their authentication URL. This works well. I hope this is useful to you. For more information, see the GitHub below: github.com/ageitgey/face_recognition


@Jasper_Holton's profile photo

How to Identify Unique Faces with the Microsoft Azure Face API Using the Microsoft Azure Face API, you can assign unique faces a UUID and identify them for use in login, verification, or any other purpose. The following code accepts an image of a single face and returns a unique UUID representing that face. This has a huge application potential in internet security and could make some sites and businesses much more secure, by uniquely attributing faces to profiles within the apps or security solutions. Using the face API with Microsoft Azure is free for basic use, and isn't expensive otherwise. To install python modules for this code, run $ pip install --upgrade azure-cognitiveservices-vision-face $ pip install --upgrade Pillow The code is as follows.

# face/face.py
import asyncio
import io
import glob
import os
import sys
import time
import uuid
import requests
from urllib.parse import urlparse
from io import BytesIO
from PIL import Image, ImageDraw
from azure.cognitiveservices.vision.face import FaceClient
from msrest.authentication import CognitiveServicesCredentials
from azure.cognitiveservices.vision.face.models import TrainingStatusType, Person, QualityForRecognition
import json

# This key will serve all examples in this document.
KEY = "000000000000000000000000000000"
# This endpoint will be used in all examples in this quickstart.
ENDPOINT = "https://endpoint.api.cognitive.microsoft.com/"

PERSON_GROUP_ID = str("group") # assign a random ID (or name it anything)

def get_face_id(single_face_image_url):
    # Create an authenticated FaceClient.
    face_client = FaceClient(ENDPOINT, CognitiveServicesCredentials(KEY))
    # Detect a face in an image that contains a single face
    single_image_name = os.path.basename(single_face_image_url)
    # We use detection model 3 to get better performance.
    face_ids = []
    # We use detection model 3 to get better performance, recognition model 4 to support quality for recognition attribute.
    faces = face_client.face.detect_with_url(single_face_image_url, detection_model='detection_03') #, recognition_model='recognition_04', return_face_attributes=['qualityForRecognition'])
    # Remove this line after initial call with first face (or you will get an error on the next call)
    face_client.person_group.create(person_group_id=PERSON_GROUP_ID, name=PERSON_GROUP_ID)

    for face in faces: # Add faces in the photo to a list
        face_ids.append(face.face_id)

    if len(faces) > 1: # Return if there are too many faces
        return False

    results = None
    try:
        results = face_client.face.identify(face_ids, PERSON_GROUP_ID) # Identify the face
    except:
        results = None
    if not results: # Add the face if they are not identified
        p = face_client.person_group_person.create(PERSON_GROUP_ID, uuid.uuid4()) # Identify them with a UUID
        face_client.person_group_person.add_face_from_url(PERSON_GROUP_ID, p.person_id, single_face_image_url)
        face_client.person_group.train(PERSON_GROUP_ID) # Training
        while (True):
            training_status = face_client.person_group.get_training_status(PERSON_GROUP_ID)
            print("Training status: {}.".format(training_status.status))
            print()
            if (training_status.status is TrainingStatusType.succeeded):
                break
            elif (training_status.status is TrainingStatusType.failed):
                sys.exit('Training the person group has failed.')
            time.sleep(5)
        results = face_client.face.identify(face_ids, PERSON_GROUP_ID)
    if results and len(results) > 0: # Load their UUID
        res = json.loads(str(results[0].candidates[0]).replace('\'',"\""))['person_id']
        print(res)
        return res # Return their UUID
    return False # Or return false to indicate that no face was recognized.

f = 'uglek.com/media/face/1b195bf5-8150-4f84-931d-ef0f2a464d06.png'
print(get_face_id(f)) # Identify a face from this image
Using this code, you can call get_face_id(face_url) to get an ID from any face. Your face ID will be unique to each user, so you can cache it on a profile and use it to retrieve a profile. This is the way the "Login with your face" option works on Uglek. I hope you enjoy this code, and it is useful to you. Feel free to use it as you will, but be sure to install your own API keys from Azure.com. Thank you!


@Jasper_Holton's profile photo

How to Generate a String from a Number in Python I use the following code to generate a string from a number under 1000. It is using simple arrays and if statements to generate a compound number as a string.


import math
n = ['one','two','three','four','five', 'six', 'seven', 'eight', 'nine', 'ten']
tn = ['eleven','twelve','thir','four','fif','six','seven','eigh','nine']
nn = ['ten','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
def number_to_string(num):
    if not isinstance(num, int):
        num = int(num) if num != '' else 'done'
    if num == 'done':
        return ''
    if num == 0:
        return ''
    if num < 11:
        return n[num-1]
    if num < 20:
        if num < 13:
            return tn[num-11]
        return tn[num-11] + 'teen'
    if num < 100:
        extra = '-'+n[num%10-1]
        if num%10 == 0:
            extra = ''
        return nn[math.floor(num/10)-1]+extra
    if num < 1000:
        extra = '-'+n[num%10-1]
        if num%10 == 0:
            extra = ''
        snum = str(num)
        return n[math.floor(num/100)-1]+'-hundred'+ ('-' if number_to_string(int(snum[1:])) != '' else '') + number_to_string(int(snum[1:]))
    if num < 10000:
        snum = str(num)
        return number_to_string(int(snum[:1])) + '-thousand' + ('-' if number_to_string(int(snum[1:])) != '' else '') +number_to_string(int(snum[1:]))
    if num < 100000:
        snum = str(num)
        return number_to_string(int(snum[:2])) + '-thousand' + ('-' if number_to_string(int(snum[2:])) != '' else '') + number_to_string(int(snum[2:]))
    if num < 1000000:
        snum = str(num)
        return number_to_string(snum[:len(snum) - 3]) + '-thousand' + ('-' if number_to_string(snum[len(snum)-3:]) != '' else '') + number_to_string(snum[len(snum)-3:])    
    if num < 1000000000:
        snum = str(num)
        return number_to_string(snum[:len(snum) - 6]) + '-million' + ('-' if number_to_string(snum[len(snum)-6:]) != '' else '') + number_to_string(snum[len(snum)-6:])
    return 'number too large to compute!'

#for x in range(1,100000):
#    print(number_to_string(x))
print(number_to_string(999999999))
This returns a compound string number, "nine-hundred-ninety-nine-million-nine-hundred-ninety-nine-thousand-nine-hundred-ninety-nine".


@Jasper_Holton's profile photo

A JavaScript Drawing - Coffee Mug I created this simple drawing with code today as a product photo for the new buttons. It's a drawing of a coffee mug, made by using ovals and rectangles. The code that draws it is below.

function init() {
    var stage = new createjs.Stage("coffee");
    var background = new createjs.Shape();
    var yoffset = 40;
    background.graphics.beginFill("DeepSkyBlue").drawRect(0, 0, 500, 500);
    stage.addChild(background);
    var circle = new createjs.Shape();
    circle.graphics.beginFill("White").drawEllipse(10 + 300 + yoffset, 250 - 150, 120, 300);
    stage.addChild(circle);
    var circle3 = new createjs.Shape();
    circle3.graphics.beginFill("DeepSkyBlue").drawEllipse(370, 90 + yoffset, 70, 240);
    stage.addChild(circle3);
    var mug = new createjs.Shape();
    mug.graphics.beginFill("White").drawRect(100, 60 + yoffset, 300, 300);
    stage.addChild(mug);
    var circle = new createjs.Shape();
    circle.graphics.beginFill("White").drawEllipse(250 - 150, 10 + yoffset, 300, 100);
    stage.addChild(circle);
    var circle2 = new createjs.Shape();
    circle2.graphics.beginFill("Brown").drawEllipse(250 - 130, 30 + yoffset, 260, 60);
    stage.addChild(circle2);
    var circle4 = new createjs.Shape();
    circle4.graphics.beginFill("White").drawEllipse(250 - 150, 10 + 300 + yoffset, 300, 100);
    stage.addChild(circle4);
    stage.update();
}

View the photo from a post by @Jasper_Holton

@Jasper_Holton, likes this,

@Jasper_Holton's profile photo

How to Make a Dynamic Easy-Reading Theme Based on Sunrise and Sunset This code lets me automatically render pages in either light or dark mode (with light or dark styles) depending on whether the sun is up. I am querying the location and timezone info using an API. This is a great way to make a site easier on the eyes at night. A webpage with a lot of white blank space in it can be a little bit hard to use at night, so it's better to have a context processor that makes the site easier to read at night.

# app/context_processors.py
import pytz
from astral import LocationInfo
from astral.sun import sun
def context_processor(context_data)
    tz = request.user.profile.timezone # Get the timezone
    city = LocationInfo(request.user.profile.city, request.user.profile.country, tz, request.user.profile.lat, request.user.profile.lon) # Using astral to query location by city, country, timezone, latitude and longitude
    city_sun = sun(city.observer, date=datetime.now(pytz.timezone(tz))) # get 
    the city sunlight
    now_time = datetime.now(pytz.timezone(tz)).time() # Get the time now
    if now_time <= city_sun['sunrise'].astimezone(pytz.timezone(tz)).time() or now_time >= city_sun['sunset'].astimezone(pytz.timezone(tz)).time(): # If the sun is down
        context_data['darkmode'] = True # Make the page dark
    else:
        context_data['darkmode'] = False # Or otherwise make it light
    return context_data

# users/middleware.py
def simple_middleware(get_response):
    # One-time configuration and initialization.
    def middleware(request):
        User = get_user_model()
        if request.user.is_authenticated and hasattr(request.user, 'profile'):
            user = get_object_or_404(User, pk=request.user.pk)
            # Update last visit time after request finished processing.
            last_ip = request.user.profile.ip
            request.user.profile.ip = get_client_ip(request)
            if request.user.profile.ip != last_ip:
                request.user.profile.timezone = get_timezone(request.user.profile.ip)
                response = requests.get('http://https://ipinfo.io/' + request.user.profile.ip + '/json' ).json() # Get the IP info
                request.user.profile.city = response['city'] # Save it
                request.user.profile.country = response['country']
                request.user.profile.timezone = response['timezone']
                request.user.profile.lat = response['loc'].split(',')[0]
                request.user.profile.lon = response['loc'].split(',')[1]
            request.user.profile.save()
        response = get_response(request)
        return response
    return middleware


@Jasper_Holton's profile photo

A Handy Audio Fix For Iframes Using jQuery This is how I play pause audio in the document with iframes loaded in so audio doesn't play more than once in the document. This fix changes the site to fix double audio playing in multiple iframes. This code is included in each iframe and in the main document.

$(function() {
    $("audio").on("play", function() { // When each audio is played in main document
        $("audio", window.parent.document).not(this).each(function(index, audio) { // Get each audio that isn't this one
            audio.pause(); // Pause it
        });
        playing = this; // Save the audio that's playing
        $("iframe", window.parent.document).each(function(index, iframe) { // Get all iframes in parent document
            $(iframe).contents().find("audio").not(playing).each(function(index, audio) { // Filter audios that shoudln't be playing (not the one we clicked)
                audio.pause(); // Pause the audio
            });
        });
    });
});
This simple code pauses the audio elements on my site as a new one is played. It can be used to prevent duplicate audios from playing, and it runs on all audios and iframes so it can be used in any document. It should be integrated in the parent document and each iframe of the scrolling page.


@Jasper_Holton, likes this,

@Jasper_Holton's profile photo

Verbose Error Handling With Django Middleware This is a simple way to verbosely handle errors using Django middleware. Using this middleware, you can render your error tracebacks to custom HTML pages, instead of using the Django debug mode error pages. Here is how the code works. First, some middleware to get the current error in the error handler view.

# app/middleware.py
from threading import local 
import traceback 
from django.utils.deprecation import MiddlewareMixin

_error = local() # Store the error in a local

class ExceptionVerboseMiddleware(MiddlewareMixin):
    def process_exception(self, request, exception): # Process the exception
        _error.value = traceback.format_exc() # Store the stack trace from traceback

def get_current_exception(): # Return the error
    try:
        return _error.value
    except AttributeError:
        return None
In the views, add a call to the middleware to get the exception.
# app/views.py
def handler500(request):
    data = {'title':'Error 500', 'error': get_current_exception()} # Put the error in the context, so we can render it to the template.
    return render(request,'blog/500.html', data)
Include this middleware in your settings.py file.
# project/settings.py
MIDDLEWARE = [
    '...',
    'app.middleware.ExceptionVerboseMiddleware',
    '...'
]
And finally, add this line to your projects urls.py
# project/urls.py
handler500 = 'blog.views.handler500'
Now, you simply need to add a tag,
{{ error }}
, to render your error to the error 500 page. This is all it takes to set up a verbose error handling page in Django.


@Jasper_Holton's profile photo

How to Create an Infinitely Scrolling Django View Creating a pseudo-infinitely scrolling page for a Django site is fairly easy. It involves creating a main page that renders the first posts, a secondary page that renders more posts according to a page number, and using some basic JavaScript to load in more posts when the user scrolls to the bottom of the page. I created two views to handle the backend code.

# This view renders a scrollable page.
@vary_on_cookie
def scroll(request):
    posts = Post.objects.filter(public=True).order_by('date_posted') # Get the posts for the first page
    p = Paginator(posts, 10) # Paginate them
    if request.user.is_authenticated: # Mark viewership if users are logged in
        for post in p.page(p.num_pages):
            if not post.viewers.filter(id=request.user.id).exists():
                post.viewers.add(request.user)
    context = { # Render the posts
        'posts': p.page(p.num_pages),
        'count': p.count,
        'page_obj': p.get_page(p.num_pages),
        'title': 'Scroll Posts',
        'description': 'Scroll and see all the posts on Uglek here. This is the front page of Uglek.' + basedescription,
        'dontshowsidebar': True,
        'full': True,
        'num_pages': p.num_pages,
    }
    response = render(request, 'blog/scroll.html', context)
    if request.user.is_authenticated:
        patch_cache_control(response, private=True) # Render private page
    return response

# This view is simple. It renders the posts for each page as we scroll through them.
@vary_on_cookie
def scroll_page(request):
    posts = Post.objects.filter(public=True).order_by('date_posted') # Get posts
    p = Paginator(posts, 10) # Paginate them
    page = p.num_pages - 1
    if(request.GET.get('page', '') != ''): # Get the page from the querystring
        page = int(request.GET.get('page', ''))
    if request.user.is_authenticated: # Mark viewership if the user is logged in
        for post in p.page(page):
            if not post.viewers.filter(id=request.user.id).exists():
                post.viewers.add(request.user)
    context = {
        'posts': p.page(page), # Render the posts
        'count': p.count,
        'page_obj': p.get_page(page),
    }
    response = render(request, 'blog/scrollpage.html', context)
    if request.user.is_authenticated:
        patch_cache_control(response, private=True) # Render private page
    return response
The javascript is pretty simple too, we just load in new content every time the window is scrolled close to the bottom.
var page = {{ num_pages }};
$(window).scroll(function() { // On scroll
    if ($(window).scrollTop() + $(window).height() > $(document).height() - 5000) {
        loadNext(); // Load new content
    }
});
loadNext(); // Start by loading
var loading = false; // Keep track of whether we are loading
function loadNext() {
    if (!loading && page > 1) { // If we are not loading already and there is another page
        loading = true; // Mark that we are loading
        page = page - 1; // Decrement the page (to load the next page)
        var scrollContainer = document.getElementById("scroll-container"); // Get the container
        const urlParams = new URLSearchParams(window.location.search);
        var lang = '';
        if (urlParams.get('lang') != null) {
            lang = "&lang=" + urlParams.get('lang'); // Get the language
        }
        // Make a request to the next page with the language
        const Http = new XMLHttpRequest(); 
        const url = "https://uglek.com/scroll/page/?page=" + page + lang;
        Http.responseType = 'text';
        Http.onload = function() {
            if (Http.readyState === Http.DONE) {
                scrollContainer.insertAdjacentHTML("beforeend", Http.responseText);
                loading = false;
            }
        };
        Http.open("GET", url, true);
        Http.send(null); // Send the request
    }
}
The templates are fairly self-explanatory, you just need to render the first posts in the main template, scroll.html, and more posts in scrollpage.html. You'll need to render the pages in an iframe in order for some scripts and products like Google AdSense to work, this is easy to do as you will just need a base template including your styles and scripts which serves a full HTML page (capable of serving ads). You can use this template to render your posts and load them into the main view. The loadNext(); function looks a little different this time, more like this.
 // Load the next part of the site into the main site in an iframe
function loadNext() {
    if (!loading && page > 1) {
        loading = true;
        page = page - 1;
        var scrollContainer = document.getElementById("scroll-container");
        const urlParams = new URLSearchParams(window.location.search);
        var lang = '';
        if (urlParams.get('lang') != null) {
            lang = "&lang=" + urlParams.get('lang');
        }
        const url = "uglek.com/scroll/page/?page=" + page + lang;
        var iframe = document.createElement('iframe');
        iframe.src = url;
        iframe.frameBorder = 0;
        iframe.scrolling = 'no';
        iframe.style.width = '100%';
        iframe.classList.add('mb-3');
        $(iframe).attr('target', '_parent');
        iframe.onload = function() { // Adjust size of iframe on load
            iframe.height = iframe.contentWindow.document.body.scrollHeight + 'px';
            loading = false;
        };
        scrollContainer.appendChild(iframe); // Append it to the document
    }
}
This is all it takes to create an infinitely scrolling Django website. You will be able to automatically load in new posts as you scroll using this code. I am making use of this on the homepage, where you can now scroll to older posts without pressing a button for the next page.


@Jasper_Holton's profile photo

Database-Driven Translation Caching Django Template Filter This is a Django template filter designed to cache translations. It uses database models representing the translations and then queries them by text so you can render text in any language on a website, and only translate the text once. I have also included the code I use to translate the text, using NLP Translation from RapidAPI.com, as well as middleware to get the request in a template filter (in order to get the language). This code relies on the browser's language code, as well as a query string, ?lang=, to render the text in the users' languages. I have added comments to describe how the code works. The code begins with some middleware:

# app/middleware.py
from threading import local # Imports
from django.utils.deprecation import MiddlewareMixin

_request = local() # Store the request

class CurrentRequestMiddleware(MiddlewareMixin): # Use a middleware mixin to save the request
    def process_request(self, request):
        _request.value = request

def get_current_request(): # Return the request
    try:
        return _request.value
    except AttributeError:
        return None
Next is some settings
# project/settings.py
MIDDLEWARE = [
    'blog.middleware.CurrentRequestMiddleware', # The middleware we just made for the request
    'django.middleware.locale.LocaleMiddleware' # Middleware to store the language code in the request
]
And a model to store the translations.
# app/models.py
from django.db import models
class Translation(models.Model):
    id = models.AutoField(primary_key=True)
    src = models.CharField(max_length=2, default='en')
    lang = models.CharField(max_length=2, default='en')
    value = models.TextField(blank=True)
    translated = models.TextField(blank=True)
Lastly, the template filters and some helper functions to make them work
# app/templatetags/app_filters.py

from app.models import Translation # Imports
from app.middleware import get_current_request
from django import template

register = template.Library() # Register the template library

def get_lang(): # Get the language to translate to
    request = get_current_request()
    lang = request.LANGUAGE_CODE
    if(request.GET.get('lang', '') != ''):
        lang = request.GET.get('lang', '')
    if lang == None:
        lang = 'en'
    return lang

# Tranlsate a string to any language
def translateval(value, lang, src=None):
    src = src if src != None else 'en'
    if lang == src:
        return value
    trans = Translation.objects.filter(value=value,lang=lang,src=src if src != None else 'en') # Get the translation
    if trans.count() > 0: # Return it if it exists
        return trans.first().translated
    else: # Otherwise create it
        originalvalue = value
        value = value.replace('\n', '[=NEWLINE=]') # Preserve newlines
        translation = ''
        try:
            translation = requests.request("GET", url, headers=headers, params={"text": value, "to": lang, "from": src if src != None else 'en', 'protected_words': '@;[=NEWLINE=];'}).json()['translated_text'][lang]'protected_words>
        except:
            translation = value
        translation = translation.replace('[=NEWLINE=]', '\n').replace('[= NEWLINE =]','\n').replace('[=NEWLINE =]', '\n') # Newline fix, to preserve newlines
        ntrans = Translation.objects.create(value=originalvalue,lang=lang,src=src if src != None else 'en', translated=translation) # Create a new translation
        ntrans.save()
        return ntrans.translated # Return the translated value

# A template filter to translate from english to any language
@register.filter('etran') # Register the filter to translate
def etran(value):
    lang = get_lang() # Get the language
    translation = None
    if not lang == 'en':
        try:
            translation = translateval(value, lang, 'en') # Translate using NLP translation
        except:
            translation = None
    if translation != None:
        return translation
    return value
In action, this looks like
{{ 'Here is some text. This text will be translated from English to another language'|etran }}
I hope you find this Django code useful. I want to post lots of useful Python here so people can read it and make use of it in their own code. This code does a great job of translating all the text on the site to render it in the proper language.


@Jasper_Holton's profile photo

Render Template Without Line Breaks Using a Django Template Tag This Django block template tag renders your templates without any line breaks. Be aware, it might mess up the content of forms so I recommend using it outside of them. This is the block tag I use on Uglek to serve the site without any line breaks in the base code.

# /project/app/app_filters.py

# Imports
from django import template
from django.utils.html import strip_tags
from django.template.base import Node
from django.utils.functional import keep_lazy
import six

register = template.Library() # Register template library
@register.tag
def linebreakless(parser, token):
    nodelist = parser.parse(('endlinebreakless',))
    parser.delete_first_token() # Delete tags from the template
    return LinebreaklessNode(nodelist) # Render the node without line breaks

class LinebreaklessNode(Node):
    def __init__(self, nodelist):
        self.nodelist = nodelist # Initialize with nodelist

    def render(self, context):
        strip_line_breaks = keep_lazy(six.text_type)(lambda x: x.replace('\n', '')) # Using keep lazy
        return strip_line_breaks(self.nodelist.render(context).strip()) # Strip the line breaks and return the node

In action, this tag looks like
{% linebreakless %}This is some text here. This will render without a line break{% endlinebreakless %}
You can use this tag twice in your templates to render everything but the main content without line breaks, and it will save some server time serving fewer line breaks as well as make it more difficult for anyone to copy and use your code. It also could have other uses, such as removing line breaks in forms or in the text that contains too many and should be rendered only on one line. I hope this Django template filter is useful for you. Let me know if you have any questions about implementing it.


© Uglek, 2022

Terms of Use and Privacy Policy