Best Python code snippet using localstack_python
views.py
Source:views.py  
1import hashlib2import json3import os4import shutil5import uuid6import zipfile7from django.conf import settings8from django.contrib import messages9from django.contrib.admin.views.decorators import staff_member_required10from django.contrib.auth.decorators import login_required11from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage12from django.http import HttpResponse13from django.shortcuts import render, redirect14from django.utils.translation import gettext_lazy as _15from django.views.decorators.csrf import csrf_exempt16from images.forms import FormDataset, FormExperiment, TagFormset17from images.models import Dataset, Experiment, Image, IndividualTagBox, IndividualTagPoint, ImageTag, AnnotationType, \18    IndividualTag, IndividualTagCurve19from users.models import Team20from PIL import Image as PILImage21from collections.abc import Iterable22@login_required23def dataset_list(request):24    datasets = Dataset.objects.all()25    return render(request, 'dataset_list.html', {'datasets': datasets})26@login_required27def experiment_list(request):28    experiments = []29    for team in Team.objects.all():30        if request.user in team.users.all():31            result = Experiment.objects.filter(team_id=team.id)32            if isinstance(result, Iterable):33                for exp in result:34                    experiments.append(exp)35            else:36                experiments.append(result)37    return render(request, 'experiment_list.html', {'experiments': experiments})38def md5(file):39    hash_md5 = hashlib.md5()40    with open(file, "rb") as f:41        for chunk in iter(lambda: f.read(4096), b""):42            hash_md5.update(chunk)43    return hash_md5.hexdigest()44@staff_member_required45@login_required46def new_dataset(request):47    if request.method == 'POST':48        postForm = FormDataset(request.POST)49        if postForm.is_valid():50            path_name = settings.MEDIA_URL + postForm.cleaned_data.get('name')51            if not os.path.exists(path_name):52                os.makedirs(path_name)53                os.makedirs(path_name+"/originals")54            # Creamos dataset solo con el nombre y la descripción55            dataset = Dataset(name=postForm.cleaned_data['name'],56                              description=postForm.cleaned_data['description'])57            dataset.save()58            # para cada una de las imágenes seleccionadas realizamos lo siguiente:59            for file in request.FILES.getlist('files'):60                # Extraemos la extensión de la imagen61                file_name, original_extension = file.name.split(".")62                new_extension = "jpg"63                # generamos un nombre ÃNICO para la imagen y generamos su ruta dentro del proyecto64                random_name = str(uuid.uuid4())65                image_path = "{dir}/{name}.{ext}".format(dir=path_name,66                                                         name=random_name,67                                                         ext=new_extension)68                #repetimos lo mismo para la imagen que irá en originals69                image_path_original = "{dir}/{name}.{ext}".format(dir=path_name+"/originals",70                                                         name=file_name,71                                                         ext=original_extension)72                # guardamos la imagen en la ruta que proporcionamos73                PILImage.open(file).save(image_path)74                PILImage.open(file).save(image_path_original)75                # comprobación de images repetidas76                # generamos el checksum de la imagen a partir de la ruta que antes generamos y comprobamos si existe en la BD.77                checksum = md5(image_path)78                # En caso negativo almacenamos una instancia de Image en la BD y guardamos la imagen en la carpeta del dataset correspondiente.79                if not Image.objects.filter(dataset=dataset, checksum=checksum):80                    imagen = Image(name=file.name,81                                   checksum=checksum,82                                   path=path_name,83                                   name_unique="{name}.{ext}".format(name=random_name,84                                                                     ext=new_extension))85                    imagen.save()86                    dataset.images.add(imagen)87                # en caso de que sà exista debemos borrarla de la carpeta puesto que anteriormente la guardamos para poder hacer el checksum88                else:89                    os.remove(image_path)90                    os.remove(image_path_original)91            messages.success(request, _('The dataset has been created successfully!'))92            return redirect('dataset_list')93    else:94        postForm = FormDataset()95    return render(request, 'create_dataset.html', {'postForm': postForm})96@login_required97def dataset(request, id):98    data = Dataset.objects.get(id=id)99    images = data.images.all()100    page = request.GET.get('page', 1)101    paginator = Paginator(images, 36)  # 6x6 grid102    try:103        data_images = paginator.page(page)104    except PageNotAnInteger:105        data_images = paginator.page(1)106    except EmptyPage:107        data_images = paginator.page(paginator.num_pages)108    return render(request, 'dataset.html', {'data': data, 'data_images': data_images})109@login_required110def download_dataset(request, name):111    path=settings.MEDIA_URL+name+"/originals/"112    response = HttpResponse(content_type='application/zip')113    response['Content-Disposition'] = 'attachment; filename=' + name+".zip"114    zip = zipfile.ZipFile(response, 'w')115    for single_file in os.listdir(path):116        with open(path+single_file, 'rb') as f:117            zip.writestr(single_file, f.read())118    zip.close()119    return response120@staff_member_required121@login_required122def modify_dataset(request, id):123    dataset = Dataset.objects.get(id=id)124    name_old = dataset.name125    images = Dataset.objects.get(id=id).images.all()126    page = request.GET.get('page', 1)127    paginator = Paginator(images, 36)  # 6x6 grid128    try:129        data_images = paginator.page(page)130    except PageNotAnInteger:131        data_images = paginator.page(1)132    except EmptyPage:133        data_images = paginator.page(paginator.num_pages)134    duplicate_images = 0135    if request.method == 'POST':136        dataForm = FormDataset(request.POST, instance=dataset)137        if dataForm.is_valid():138            path_name = settings.MEDIA_URL + dataForm.cleaned_data.get('name')139            dataForm.save()  # actualizamos el dataset140            # Si el nombre fue cambiado141            if (name_old != dataForm.cleaned_data['name']):142                # actualizamos la carpeta de imágenes143                path_old = settings.MEDIA_URL + name_old144                path_new = settings.MEDIA_URL + dataForm.cleaned_data['name']145                os.rename(path_old, path_new)146                # y actualizamos la ruta de las imágenes de la BD147                Image.objects.filter(path=path_old).update(path=path_new)148            # para cada una de las imágenes seleccionadas realizamos lo siguiente:149            for file in request.FILES.getlist('files'):150                # Extraemos la extensión de la imagen151                file_name, original_extension = file.name.split(".")152                new_extension = "jpg"153                # generamos un nombre ÃNICO para la imagen y generamos su ruta dentro del proyecto154                random_name = str(uuid.uuid4())155                image_path = "{dir}/{name}.{ext}".format(dir=path_name,156                                                         name=random_name,157                                                         ext=new_extension)158                # repetimos lo mismo para la imagen que irá en originals159                image_path_original = "{dir}/{name}.{ext}".format(dir=path_name + "/originals",160                                                                  name=file_name,161                                                                  ext=original_extension)162                # guardamos la imagen en la ruta que proporcionamos163                # with open(image_path, 'wb+') as image:164                #     for chunk in file.chunks():165                #         image.write(chunk)166                PILImage.open(file).save(image_path)167                PILImage.open(file).save(image_path_original)168                    # comprobación de images repetidas169                checksum = md5(170                    image_path)  # generamos el checksum de la imagen a partir de la ruta que antes generamos y comprobamos si existe en la BD.171                # En caso negativo almacenamos una instancia de Image en la BD y guardamos la imagen en la carpeta del dataset correspondiente.172                if not Image.objects.filter(dataset=dataset, checksum=checksum):173                    imagen = Image(name=file.name,174                                   checksum=checksum,175                                   path=settings.MEDIA_URL + dataForm.cleaned_data['name'],176                                   name_unique="{name}.{ext}".format(name=random_name,177                                                                     ext=new_extension))178                    imagen.save()179                    dataset.images.add(imagen)180                    # en caso de que sà exista debemos borrarla de la carpeta puesto que anteriormente la guardamos para poder hacer el checksum181                else:182                    duplicate_images += 1183                    os.remove(image_path)184                    os.remove(image_path_original)185        if duplicate_images == 0:186            messages.success(request, _("The dataset has been modified successfully!"))187        else:188            messages.warning(request,189                             _(190                                 "The dataset has been modified, but {} duplicated image(s) have not been uploaded").format(191                                 duplicate_images))192        return redirect('dataset', id=id)193    else:194        dataForm = FormDataset(instance=dataset)195    return render(request, 'modify_dataset.html', {'dataForm': dataForm, 'data_images': data_images, 'id_data': id})196@staff_member_required197@login_required198def delete_dataset(request, id):199    query = Dataset.objects.get(id=id)200    query.images.all().delete()201    query.delete()202    name = query.name203    shutil.rmtree(settings.MEDIA_URL + name)204    messages.success(request, _('Dataset deleted successfully!'))205    return redirect('dataset_list')206@staff_member_required207@login_required208def delete_image_dataset(request, id_data, id):209    query = Image.objects.get(id=id)210    query.delete()211    path = query.path + "/" + query.name_unique212    path_original = query.path+"/originals/"+query.name213    os.remove(path_original)214    os.remove(path)215    return redirect('modify_dataset', id=id_data)216@staff_member_required217@login_required218def delete_annotation_type_experiment(request, id_exp, id_annotation_type):219    AnnotationType.objects.filter(id=id_annotation_type).delete()220    IndividualTag.objects.filter(type_id=id_annotation_type).all().delete()221    return redirect('modify_experiment', id_exp)222@staff_member_required223@login_required224def new_experiment(request):225    if request.method == 'POST':226        expForm = FormExperiment(request.POST)227        formset = TagFormset(request.POST)228        if expForm.is_valid():229            experiment = Experiment(name=expForm.cleaned_data['name'],230                                    description=expForm.cleaned_data['description'],231                                    dataset=expForm.cleaned_data['dataset'],232                                    team=expForm.cleaned_data['team'], )233            experiment.save()234            for form in formset:235                if form.is_valid():236                    annotation_type = AnnotationType(name=form.cleaned_data.get('name'),237                                                     color=form.cleaned_data.get('color'),238                                                     experiment=experiment,239                                                     primitive=form.cleaned_data.get('type'))240                    annotation_type.save()241            messages.success(request, _('Experiment created successfully!'))242            return redirect('experiment_list')243    else:244        formset = TagFormset()245        expForm = FormExperiment()246    return render(request, 'create_experiment.html', {'expForm': expForm, 'formset': formset})247@login_required248def experiment(request, id):249    exp = Experiment.objects.get(id=id)250    annotation_types = AnnotationType.objects.all().filter(experiment_id=id)251    tag_images = ImageTag.objects.all().filter(experiment_id=id)252    return render(request, 'experiment.html',253                  {'exp': exp, 'annotation_types': annotation_types, 'tag_images': tag_images})254@staff_member_required255@login_required256def delete_experiment(request, id):257    query = Experiment.objects.get(id=id)258    query.delete()259    messages.success(request, _('Experiment deleted'))260    return redirect('experiment_list')261@staff_member_required262@login_required263def modify_experiment(request, id):264    experiment = Experiment.objects.get(id=id)265    annotation_types = AnnotationType.objects.all().filter(experiment_id=id)266    if request.method == 'POST':267        expForm = FormExperiment(request.POST, instance=experiment)268        formset = TagFormset(request.POST)269        if expForm.is_valid():270            expForm.save()271            for form in formset:272                if form.is_valid():273                    annotation_type = AnnotationType(name=form.cleaned_data.get('name'),274                                                     color=form.cleaned_data.get('color'),275                                                     experiment=experiment,276                                                     primitive=form.cleaned_data.get('type'))277                    annotation_type.save()278            messages.success(request, _('The experiment has been modified'))279            return redirect('experiment', id=id)280    else:281        formset = TagFormset()282        expForm = FormExperiment(instance=experiment)283    return render(request, 'modify_experiment.html',284                  {'expForm': expForm, 'id_exp': id, 'formset': formset, 'annotation_types': annotation_types})285@login_required286def images_experiment(request, id):287    exp = Experiment.objects.get(id=id)288    tag_images = None289    if ImageTag.objects.filter(experiment_id=id).exists():290        tag_images = ImageTag.objects.all().filter(experiment_id=id)291    return render(request, 'images_experiment.html', {'exp': exp, 'tag_images': tag_images})292@login_required293def annotate_image(request, id_exp, id_image, id_user):294    image = Image.objects.get(id=id_image)295    exp = Experiment.objects.get(id=id_exp)296    annotation_types = AnnotationType.objects.filter(experiment_id=id_exp).all()297    tag_image = None298    # solo enviamos las anotaciones hechas por el usuario299    if ImageTag.objects.filter(image_id=id_image).filter(user_id=id_user).exists():300        tag_image = ImageTag.objects.get(image_id=id_image, user_id=id_user)301    return render(request, 'annotate.html',302                  {'exp': exp,303                   'image': image,304                   'annotation_types': annotation_types,305                   'tag_image': tag_image})306@login_required307@csrf_exempt308def save_tags(request, id_exp, id_image):309    if request.method == 'POST':310        tag_image = None311        if 'canvas_data' in request.POST:312            data = request.POST['canvas_data']313            decoded = json.loads(data)314            image_width = decoded['backgroundImage']['width']315            # Si existe un ImageTag para esta imagen donde el usuario corresponde con el actual, es decir, si el usuario que está anotando ya realizó anotaciones previas316            if ImageTag.objects.filter(image_id=id_image).filter(user_id=request.user.id).all():317                # Sobreescribimos las anotaciones (las borramos todas para volver a guardarlas de nuevo)318                tag_image = ImageTag.objects.get(image_id=id_image, user_id=request.user.id)319                tag_image.individual_tags.all().delete()320                #si el usuario que está anotando es básico y sus anotaciones fueron validadas, las desvalidamos (puesto que en este caso el usuario básico está volviendo a anotar y deben volver a ser validadas)321                if not request.user.is_staff and tag_image.check_by:322                    tag_image.check_by = None323                #en caso de que el usuario haya borrado todas las anotaciones, se borra el tagimage (porque actualmente no hay anotaciones sobre la imagen, da igual que anteriormente se realizaran)324                if decoded['objects'] == []:325                    tag_image.delete()326                tag_image.save()327            else:  # de lo contrario creamos un tagImage nuevo para este usuario328                if request.user.is_staff:  # si el usuario que está realizando la anotación es staff, entendemos que ya está validada329                    tag_image = ImageTag(image_id=id_image,330                                         user_id=request.user.id,331                                         experiment_id=id_exp,332                                         check_by=request.user)333                else:334                    tag_image = ImageTag(image_id=id_image,335                                         user_id=request.user.id,336                                         experiment_id=id_exp)337                tag_image.save()338            for obj in decoded['objects']:339                if obj['type'] == 'circle':340                    if AnnotationType.objects.all().filter(experiment_id=id_exp, name=obj['name']):341                        annotation_type = AnnotationType.objects.get(name=obj["name"], experiment_id=id_exp)342                        if annotation_type.primitive == 'Point': #para que almacene solo las anotaciones de tipo punto y no los puntos de los polÃgonos343                            x_absolute = (obj['left']*image_width)/obj['canvas_width']344                            y_absolute = (obj['top'] * image_width) / obj['canvas_width']345                            point = IndividualTagPoint(image_tag=tag_image,346                                                           type=annotation_type,347                                                           x=x_absolute,348                                                           y=y_absolute)349                            point.save()350                            annotation_type.state = True351                            annotation_type.save()352                elif obj['type'] == 'rect':353                    annotation_type = AnnotationType.objects.get(name=obj["name"], experiment_id=id_exp)354                    x_absolute = (obj['left'] * image_width) / obj['canvas_width']355                    y_absolute = (obj['top'] * image_width) / obj['canvas_width']356                    w_absolute = (obj['width'] * image_width) / obj['canvas_width']357                    h_absolute = (obj['height'] * image_width) / obj['canvas_width']358                    box = IndividualTagBox(image_tag=tag_image,359                                           type=annotation_type,360                                           x_top_left=x_absolute,361                                           y_top_left=y_absolute,362                                           width=w_absolute,363                                           height=h_absolute)364                    box.save()365                    annotation_type.state = True366                    annotation_type.save()367                elif obj['type'] == 'polygon':368                    annotation_type = AnnotationType.objects.get(name=obj["name"], experiment_id=id_exp)369                    polygon = IndividualTagCurve(image_tag=tag_image,370                                                 type=annotation_type,371                                                 id=obj['polyId'],372                                                 isClosed=True,373                                                 points=[])374                    for p in obj['points']: #para cada uno de los puntos del polÃgono375                        x_absolute = (p['x'] * image_width) / obj['canvas_width']376                        y_absolute = (p['y'] * image_width) / obj['canvas_width']377                        point = IndividualTagPoint(image_tag=tag_image,378                                                   type=annotation_type,379                                                   id=p['id'],380                                                   x=x_absolute,381                                                   y=y_absolute)382                        polygon.points.append(point)383                    polygon.save()384                    annotation_type.state = True385                    annotation_type.save()386                elif obj['type'] == 'polyline':387                    annotation_type = AnnotationType.objects.get(name=obj["name"], experiment_id=id_exp)388                    polyline = IndividualTagCurve(image_tag=tag_image,389                                                 type=annotation_type,390                                                 id=obj['polyId'],391                                                 isClosed=False,392                                                 points=[])393                    for p in obj['points']:394                        x_absolute = (p['x'] * image_width) / obj['canvas_width']395                        y_absolute = (p['y'] * image_width) / obj['canvas_width']396                        point = IndividualTagPoint(image_tag=tag_image,397                                                   type=annotation_type,398                                                   id=p['id'],399                                                   x=x_absolute,400                                                   y=y_absolute)401                        polyline.points.append(point)402                    polyline.save()403                    annotation_type.state = True404                    annotation_type.save()405    return redirect('experiment_list')406@login_required407@csrf_exempt408def validate(request, id_exp, id_image, id_user):409    if request.method == 'POST':410        tag_image = ImageTag.objects.get(image_id=id_image, experiment_id=id_exp, user_id=id_user)411        tag_image.individual_tags.all().delete()412        if 'canvas_data' in request.POST:413            data = request.POST['canvas_data']414            decoded = json.loads(data)415            image_width = decoded['backgroundImage']['width']416            # si se borran todas las anotaciones tambien borramos el tagimage417            if decoded['objects'] == []:418                tag_image.delete()419            else:420                for obj in decoded['objects']:421                    if obj['type'] == 'circle':422                        if AnnotationType.objects.all().filter(experiment_id=id_exp, name=obj['name']):423                            annotation_type = AnnotationType.objects.get(name=obj["name"], experiment_id=id_exp)424                            if annotation_type.primitive == 'Point':  # para que almacene solo las anotaciones de tipo punto y no los puntos de los polÃgonos425                                x_absolute = (obj['left'] * image_width) / obj['canvas_width']426                                y_absolute = (obj['top'] * image_width) / obj['canvas_width']427                                point = IndividualTagPoint(image_tag=tag_image,428                                                           type=annotation_type,429                                                           x=x_absolute,430                                                           y=y_absolute)431                                point.save()432                                annotation_type.state = True433                                annotation_type.save()434                    elif obj['type'] == 'rect':435                        annotation_type = AnnotationType.objects.get(name=obj["name"], experiment_id=id_exp)436                        x_absolute = (obj['left'] * image_width) / obj['canvas_width']437                        y_absolute = (obj['top'] * image_width) / obj['canvas_width']438                        w_absolute = (obj['width'] * image_width) / obj['canvas_width']439                        h_absolute = (obj['height'] * image_width) / obj['canvas_width']440                        box = IndividualTagBox(image_tag=tag_image,441                                               type=annotation_type,442                                               x_top_left=x_absolute,443                                               y_top_left=y_absolute,444                                               width=w_absolute,445                                               height=h_absolute)446                        box.save()447                        annotation_type.state = True448                        annotation_type.save()449                    elif obj['type'] == 'polygon':450                        annotation_type = AnnotationType.objects.get(name=obj["name"], experiment_id=id_exp)451                        polygon = IndividualTagCurve(image_tag=tag_image,452                                                     type=annotation_type,453                                                     id=obj['polyId'],454                                                     isClosed=True,455                                                     points=[])456                        for p in obj['points']:  # para cada uno de los puntos del polÃgono457                            x_absolute = (p['x'] * image_width) / obj['canvas_width']458                            y_absolute = (p['y'] * image_width) / obj['canvas_width']459                            point = IndividualTagPoint(image_tag=tag_image,460                                                       type=annotation_type,461                                                       id=p['id'],462                                                       x=x_absolute,463                                                       y=y_absolute)464                            polygon.points.append(point)465                        polygon.save()466                        annotation_type.state = True467                        annotation_type.save()468                    elif obj['type'] == 'polyline':469                        annotation_type = AnnotationType.objects.get(name=obj["name"], experiment_id=id_exp)470                        polyline = IndividualTagCurve(image_tag=tag_image,471                                                      type=annotation_type,472                                                      id=obj['polyId'],473                                                      isClosed=False,474                                                      points=[])475                        for p in obj['points']:476                            x_absolute = (p['x'] * image_width) / obj['canvas_width']477                            y_absolute = (p['y'] * image_width) / obj['canvas_width']478                            point = IndividualTagPoint(image_tag=tag_image,479                                                       type=annotation_type,480                                                       id=p['id'],481                                                       x=x_absolute,482                                                       y=y_absolute)483                            polyline.points.append(point)484                        polyline.save()485                        annotation_type.state = True486                        annotation_type.save()487        # ponemos en check_by al usuario staff que valida la anotación488        if request.user.is_staff:489            tag_image.check_by = request.user490            tag_image.save()491            messages.success(request, 'Anotaciones validadas')492    return redirect('experiment_list')493@login_required494@csrf_exempt495def invalidate(request, id_exp, id_image, id_user):496    if request.method == 'POST':497        tag_image = ImageTag.objects.get(image_id=id_image, experiment_id=id_exp, user_id=id_user)498        if request.user.is_staff:499            tag_image.check_by = None500            tag_image.save()501        elif request.user.is_superuser and tag_image.user.is_staff:502            tag_image.check_by = None503            tag_image.save()504    return redirect('experiment_list')505@login_required506def download_tags(request, id_exp):507    experiment = Experiment.objects.get(id=id_exp)508    experiment_data = {509        "name": experiment.name,510        "description": experiment.description,511        "creation_date": experiment.date.isoformat(),512        "dataset": experiment.dataset.name,513        "team": experiment.team.name,514        "annotations": [],  # contiene todos los TagImage del experimento515    }516    if ImageTag.objects.all().filter(experiment_id=experiment.id):517        tag_images = ImageTag.objects.all().filter(experiment_id=experiment.id)518        for tag in tag_images:519            tag_image = {520                "image": tag.image.name,521                "user": tag.user.username,522                "check_by": tag.check_by.username,523                "individual_annotations": [],524            }525            individual_tags = tag.individual_tags526            for it in individual_tags.all():527                if it.type.primitive == "Point":528                    tag_image["individual_annotations"].append({529                        "name": it.type.name,530                        "type": it.type.primitive,531                        "color": it.type.color,532                        "coordinate_x": it.individualtagpoint.x,533                        "coordinate_y": it.individualtagpoint.y,534                    })535                elif it.type.primitive == "Box":536                    tag_image["individual_annotations"].append({537                        "name": it.type.name,538                        "type": it.type.primitive,539                        "color": it.type.color,540                        "coordinate_x_top_left": it.individualtagbox.x_top_left,541                        "coordinate_y_top_left": it.individualtagbox.y_top_left,542                        "width": it.individualtagbox.width,543                        "height": it.individualtagbox.height,544                    })545                elif it.type.primitive == "Polygon":546                    polygon = {547                        "name": it.type.name,548                        "type": it.type.primitive,549                        "color": it.type.color,550                        "points": [],551                    }552                    for p in it.individualtagcurve.points:553                        polygon["points"].append({554                            "coordinate_x": p.x,555                            "coordinate_y":p.y,556                        })557                    tag_image["individual_annotations"].append(polygon)558                elif it.type.primitive == "Curve":559                    curve = {560                        "name": it.type.name,561                        "type": it.type.primitive,562                        "color": it.type.color,563                        "points": [],564                    }565                    for p in it.individualtagcurve.points:566                        curve["points"].append({567                            "coordinate_x": p.x,568                            "coordinate_y": p.y,569                        })570                    tag_image["individual_annotations"].append(curve)571            experiment_data["annotations"].append(tag_image)572    data = json.dumps(experiment_data)573    response = HttpResponse(data, content_type='application/json')574    response['Content-Disposition'] = 'attachment; filename=' + experiment.name + '.json'575    return response576@login_required577def download_tagged_images(request, id_exp):578    exp = Experiment.objects.get(id=id_exp)579    dataset = exp.dataset.name580    if ImageTag.objects.filter(experiment_id=id_exp).exists():581        tag_images = ImageTag.objects.all().filter(experiment_id=id_exp)582        names_images=[]583        for t in tag_images:584            if not t.image.name in names_images:585                names_images.append(t.image.name)586        print(names_images)587        path = settings.MEDIA_URL + dataset + "/originals/"588        response = HttpResponse(content_type='application/zip')589        response['Content-Disposition'] = 'attachment; filename=' + exp.name + "-tagged-images.zip"590        zip = zipfile.ZipFile(response, 'w')591        for single_file in os.listdir(path):592            if single_file in names_images:593                with open(path + single_file, 'rb') as f:594                    zip.writestr(single_file, f.read())595        zip.close()...test.py
Source:test.py  
1import mysql.connector2from mysql.connector import errorcode3SQL_SERVER = 'passion-mysql-server.mysql.database.azure.com'4SQL_DB = 'passiondb'5USERNAME = 'passionadmin'6PASSWORD = 'MonikMik17!'7list_tags = ('arbre','mangue')8recherche = "SELECT images.bloblink from images INNER JOIN ( SELECT A.id_image FROM tag_image A INNER JOIN \9            ( SELECT id FROM tags WHERE name IN"+ str(list_tags)+") AS B ON A.id_tag = B.id GROUP BY A.id_image \10            HAVING COUNT(*) = "+ str(len(list_tags))+") AS C ON images.id = C.id_image;"11try:12   cnxn = mysql.connector.connect(user=USERNAME, password=PASSWORD, host=SQL_SERVER, port=3306, database=SQL_DB)13   print("Connection established")14except mysql.connector.Error as err:15  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:16    print("Something is wrong with the user name or password")17  elif err.errno == errorcode.ER_BAD_DB_ERROR:18    print("Database does not exist")19  else:20    print(err)21else:22    cursor = cnxn.cursor()23    #Création de la table Images24    # cursor.execute("CREATE TABLE images (id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, name VARCHAR(50), bloblink VARCHAR(100) );")25    # cursor.execute("CREATE TABLE tags (id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, name VARCHAR(50) );")26    # cursor.execute("CREATE TABLE tag_image (id_image INT NOT NULL, id_tag INT NOT NULL, PRIMARY KEY(id_image, id_tag));")27    # cursor.execute("ALTER TABLE tag_image ADD CONSTRAINT FOREIGN KEY (id_image) REFERENCES images(id);")28    # cursor.execute("ALTER TABLE tag_image ADD CONSTRAINT FOREIGN KEY (id_tag) REFERENCES tags(id);")29    # cursor.execute("INSERT INTO images (name,bloblink) VALUES ('banane.jpeg','www/tmp/blob1');")30    # cursor.execute("INSERT INTO images (name,bloblink) VALUES ('ananas.jpeg','www/tmp/blob1');")31    # cursor.execute("INSERT IGNORE INTO tags (name) VALUES ('arbre');")32    # cursor.execute("INSERT INTO tag_image (id_image,id_tag) VALUES (1,5);")33    # cursor.execute("INSERT INTO tag_image (id_image,id_tag) VALUES (1,3);")34    # cursor.execute("INSERT INTO tag_image (id_image,id_tag) VALUES (3,2);")35    # cursor.execute("INSERT INTO tag_image (id_image,id_tag) VALUES (4,5);")36    # cursor.execute("INSERT INTO tag_image (id_image,id_tag) VALUES (5,4);")37    38    # print("Finished inserting row.")39    # cursor.execute("SELECT LAST_INSERT_ID();")40    # rows = cursor.fetchall()41    # print(rows)42    # cursor.execute("")43    # cursor.execute("SELECT * FROM tags;")44    # cursor.execute("SELECT DISTINCT id_image, id_tag FROM tag_image WHERE id_tag=5")45    cursor.execute(recherche)46    rows = cursor.fetchall()47    for row in rows:48        print("Data row = (%s, %s)" %(str(row[0]), str(row[1]))) #, str(row[2])))49    # print("Finished creating table.")50    # Cleanup51    cnxn.commit()52    cursor.close()53    cnxn.close()...AR_main.py
Source:AR_main.py  
1from AugmentedReality import *2import numpy as np3import cv24import copy5# Initiating the Augmented_Reality class.6ar_class = Augmented_Reality()7# Change these for different videos and image inputs8path_to_video = 'Tag0.mp4'9path_to_image = 'Lena.png'10# Video and image read objects11video_cap = cv2.VideoCapture(path_to_video)12image_cap = cv2.imread(path_to_image)13# template corners.14points_template = np.array([[0,image_cap.shape[0]],[image_cap.shape[1],image_cap.shape[0]],[image_cap.shape[1],0],[0,0]])15while video_cap.read():16	ret, image = video_cap.read()17	original_image = copy.deepcopy(image)18	if not ret:19		break20	21	tag_images_list, tag_corners_list = ar_class.tag_detection(original_image)22	if len(tag_images_list) > 0:23		for tag_image in tag_images_list:24			tag_image, tag_id = ar_class.get_tag_id(tag_image)25			cv2.putText(tag_image,str(tag_id),(tag_image.shape[0]/2 - 5,tag_image.shape[1]/2+15), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,0,0),1,cv2.LINE_AA)26			# cv2.imshow('Tag ID',tag_image)27	if len(tag_corners_list) > 0:28		for corner in tag_corners_list:29			for i in range(0,4):30				cv2.circle(image,(corner[i,0],corner[i,1]),3,(255,0,0),5)# Blue Corners31				resized_corner = cv2.resize(image,(0,0), fx=0.5, fy=0.5 )32				cv2.imshow('Corners', resized_corner)33			### Placing template Image on the Tag34			H = ar_class.inverse_homography(corner, points_template)35			width_at_destination = np.array([min(corner[:,0]+1), max(corner[:,0]-1)]).astype(int)36			height_at_destination = np.array([min(corner[:,1]+1), max(corner[:,1]-1)]).astype(int)37			Image_with_template = ar_class.place_template_on_tag(original_image, H, image_cap, width_at_destination, height_at_destination)38			#cv2.imshow('Lena replaces Tags', Image_with_template)			39			### Placing Cube on the Tag40			K = ar_class.calibration_matrix# Calibration Matrix41			Camera_Pose_R_T = ar_class.estimate_camera_pose(K, H)42			frame_with_cube = ar_class.put_a_cube(K, Camera_Pose_R_T, corner, points_template, original_image)43	resized_cube = cv2.resize(original_image, (0,0), fx=0.5, fy=0.5)44	cv2.imshow('Cube Placed', resized_cube)45	cv2.waitKey(1000/30)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
