示例#1
0
class RecordAddForm(RecordUpdateForm):
    category = forms.ModelChoiceField(label=u'분류', empty_label=u'미분류',
            queryset=Category.objects.none(), required=False)
    work_title = forms.CharField(label=u'작품 제목', max_length=100)

    def __init__(self, user, *args, **kwargs):
        super(RecordAddForm, self).__init__(Record(), *args, **kwargs)
        self.fields['category'].queryset = user.category_set.all()
        self.user = user

    @property
    def connected_services(self):
        return ' '.join(get_connected_services(self.user))

    def clean_work_title(self):
        title = self.cleaned_data['work_title']
        self.work = get_or_create_work(title)
        try:
            r = self.user.record_set.get(work=self.work)
            raise forms.ValidationError(u'이미 같은 작품이 "%s"로 등록되어 있습니다.' % r.title)
        except Record.DoesNotExist:
            pass
        return title

    def save(self):
        try:
            self.record = self.user.record_set.get(work=self.work)
            raise Exception('Already added')
        except Record.DoesNotExist:
            self.record = Record(user=self.user, work=self.work, title=self.cleaned_data['work_title'])
            self.record.category = self.cleaned_data['category']
            self.record.save()

            super(RecordAddForm, self).save()
示例#2
0
def receiveImage(request, idclient):
    logger.info(">>receive image idcliente: " + str(idclient))
    try:
        lastRecordId = Record.objects.latest('idRecord').idRecord + 1
    except Record.DoesNotExist:
        lastRecordId = 1
    logger.info(">>future lastRecordId: " + str(lastRecordId))

    directoryByClient = os.path.join(
        Path().absolute(),
        "opencv-face-recognition/dataset/records/" + str(idclient))

    if not os.path.exists(directoryByClient):
        os.makedirs(directoryByClient)

    feikPath = directoryByClient + "/record_" + str(lastRecordId) + "_feik.jpg"
    truePath = directoryByClient + "/record_" + str(lastRecordId) + ".jpg"

    #pathForeingImage = directoryByClient+"/record_"+str(lastRecordId)+".jpg"
    response = bytesToImage(request, feikPath)
    if response is 'ERROR':
        logger.info(">>ERROR UPLOAD IMAGEN FROM ARDUINO")
        return HttpResponse("<h1>ERROR</h1>")

    img_rt_90 = rotate_img(feikPath, -90)
    img_rt_90.save(truePath)
    os.remove(feikPath)

    personRecognition = proccessRecognition(truePath, idclient)
    logger.info("person: " + personRecognition.name)
    logger.info("percent: " + str(personRecognition.percent))
    if personRecognition.name is 'unknown':
        myFamily = Family(familyName="Desconocido", relationship="Desconocido")
    else:
        try:
            myFamily = Family.objects.get(familyName=personRecognition.name)
        except Family.DoesNotExist:
            myFamily = Family(familyName=personRecognition.name,
                              relationship="Desconocido")

    #user = User.objects.get(id=idclient)
    user = CustomUser.objects.get(id=idclient)

    arrayPath = truePath.split("/", 2)
    photoPath = arrayPath[2]

    myRecord = Record(familyName=personRecognition.name,
                      relationship=myFamily.relationship,
                      percent=str(personRecognition.percent),
                      recordPhotoPath=photoPath,
                      idClient=user)
    myRecord.save()
    logger.info(">>id record: " + str(myRecord.idRecord))
    fcm_send_topic_message(topic_name='my-event',
                           message_body='la persona ' + myRecord.familyName +
                           ' ingreso a tu hogar a las ' +
                           myRecord.dateRecord.strftime("%Y-%m-%d %H:%M:%S"),
                           message_title='Mensaje Arduino')

    return HttpResponse("<h1>OK</h1>")
示例#3
0
def startRecord(request):
    cap = cv2.VideoCapture(0)
    fourcc = cv2.VideoWriter_fourcc('U', '2', '6', '3')
    dt = datetime.date.today()
    outfile = 'static/video/{}.mp4'.format(dt)
    out = cv2.VideoWriter(
        '../../Envs/virtual_env/Lib/site-packages/simpleui/{}'.format(outfile),
        fourcc, 30.0, (640, 480))

    while (cap.isOpened()):
        ret, frame = cap.read()

        if ret == True:
            frame = cv2.flip(frame, 1)
            out.write(frame)

            cv2.imshow('camera', frame)
            if cv2.waitKey(1) & 0xFF == ord('1'):
                break
        else:
            break

    cap.release()
    out.release()
    cv2.destroyAllWindows()

    rd = Record.objects.filter(datetime=dt).first()
    if rd:
        pass
    else:
        rd = Record(record_url=outfile, datetime=dt)
        rd.save()
    return JsonResponse({"res": "请求成功"})
示例#4
0
def record_insert(request):
    player_id = request.POST.get('player_id')
    difficulty = request.POST.get('difficulty')
    finish_time = request.POST.get('finish_time')

    player = User.objects.get(pk=player_id)
    record = Record()
    record.player = player
    record.difficulty = difficulty
    record.finish_time = finish_time
    record.save()

    try:
        best_record = BestRecord.objects.get(player_id=player_id,
                                             difficulty=difficulty)
    except BestRecord.DoesNotExist:
        best_record = None

    if best_record is None:
        best_record = BestRecord()
        best_record.player = player
        best_record.difficulty = difficulty
        best_record.finish_time = 999999999999

    best_record.finish_time = min(best_record.finish_time, int(finish_time))
    best_record.save()

    return redirect('index')
示例#5
0
def add(request):
    data = {'result': ''}

    if 'isbn' in request.POST:
        isbn = request.POST.get('isbn', "")

        item = Record(status="created",
                      ref_owner=request.user.profile,
                      ref_book=Book.objects.filter(ISBN=isbn).first(),
                      ref_workspace=Workspace.objects.filter(
                          ref_profile=request.user.profile,
                          active=True).first())
        item.save()
        print("Save record")
    else:
        print("else")

    return render(request, 'book/search.html', data)
示例#6
0
    def save(self):
        try:
            self.record = self.user.record_set.get(work=self.work)
            raise Exception('Already added')
        except Record.DoesNotExist:
            self.record = Record(user=self.user, work=self.work, title=self.cleaned_data['work_title'])
            self.record.category = self.cleaned_data['category']
            self.record.save()

            super(RecordAddForm, self).save()
    def save(self, validated_data):
        request = self.context['request']
        # Obtain record info
        date_paid = validated_data.get('date_paid')
        payperiod_start = validated_data.get('payperiod_start')
        payperiod_end = validated_data.get('payperiod_end')
        company = request.user.company

        already_paid = company.employees.filter(
            record__date_paid=date_paid).exists()
        host_url = request.META.get(
            'wsgi.url_scheme') + '://' + request.META['HTTP_HOST']

        if not already_paid:
            record_list = []
            total_paid = 0

            new_report = Report(company_id=company.id, )
            new_report.save()

            for employee in company.employees.all():
                new_record = Record(date_paid=date_paid,
                                    payperiod_start=payperiod_start,
                                    payperiod_end=payperiod_end,
                                    user_id=employee.id,
                                    company_id=company.id,
                                    report_id=new_report.id)
                new_record.save()
                payslip_pdf(employee, new_record, host_url)
                record_list.append(new_record)
                total_paid += new_record.user.salary.gross_month

            report_pdf(company, record_list, total_paid, new_report, employee,
                       new_record, host_url)

        else:
            raise ValidationError(
                'You have already scheduled payments on this day')

        return
示例#8
0
    def handle(self, *args, **options):
        users = ['Kate', 'Ilya', 'Denis', 'Dmitry', 'Grigory', 'Stas']
        records = []

        for username in users:
            u = User.objects.create_user(username,
                                         '{}@asd.asd'.format(username),
                                         username)

            for _ in range(10):
                r = Record(inode=uuid4().hex,
                           url='http://google.com/' + uuid4().hex,
                           filename=uuid4().hex,
                           server_path='\\\\server\\path\\' + uuid4().hex,
                           size=0,
                           dotcms_updated=timezone.now(),
                           dotcms_author=username,
                           last_reuploaded=None,
                           reupload_author=u,
                           original_file=None)
                records.append(r)

        Record.objects.bulk_create(records)
def startRecord(request):
    cap = cv2.VideoCapture(0)
    fourcc = cv2.VideoWriter_fourcc('U', '2', '6', '3')
    dt = datetime.date.today()
    outfile = 'static/video/{}.mp4'.format(dt)
    out = cv2.VideoWriter(
        '../../Envs/virtual_env/Lib/site-packages/simpleui/{}'.format(outfile),
        fourcc, 30.0, (640, 480))

    # print(ffmpegresult)

    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +
                                         'haarcascade_frontalface_default.xml')
    while (cap.isOpened()):
        ret, frame = cap.read()
        if ret == True:  #有视频时
            frame = cv2.flip(frame, 1)
            out.write(frame)
            cv2.imshow('camera', frame)
            # return HttpResponse(frame,content_type="image/png")
            if cv2.waitKey(1) & 0xFF == ord('s'):
                faces = face_cascade.detectMultiScale(frame, 1.3, 2)
                for (x, y, w, h) in faces:
                    cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0),
                                  2)
                    cv2.imshow('frame', frame)
                    face_image = frame[y:y + h, x:x + h]
                    face_readytoread_encodings = face_recognition.face_encodings(
                        face_image)  # 新图encoding
                    faces_dbs = Faces.objects.filter(face_date=dt)

                    for face_readytoread_encoding in face_readytoread_encodings:
                        for faces_db in faces_dbs:
                            face_read = face_recognition.load_image_file(
                                '../../Envs/virtual_env/Lib/site-packages/simpleui/{}'
                                .format(faces_db.face_url))
                            face_read_encoding = face_recognition.face_encodings(
                                face_read)

                            res = face_recognition.compare_faces(
                                face_read_encoding,
                                face_readytoread_encoding,
                                tolerance=0.6)

                            if res == [True]:
                                faces_db.delete()
                                # face_image.pop
                                break
                    else:
                        num = random.randint(0, 10000)
                        face_source = "static/faces/{}_{}.png".format(dt, num)
                        cv2.imwrite(
                            '../../Envs/virtual_env/Lib/site-packages/simpleui/{}'
                            .format(face_source), face_image)
                        faces_db = Faces(face_url=face_source, face_date=dt)
                        faces_db.save()
                if cv2.waitKey(0) & 0xFF == ord('1'):
                    break

            elif cv2.waitKey(1) & 0xFF == ord('1'):  #1退出视频
                break
        else:
            break
    cap.release()
    out.release()
    cv2.destroyAllWindows()

    rd = Record.objects.filter(datetime=dt).first()
    print(rd)
    # print(rd)
    if rd:
        # rd.record_url = outfile
        # rd.save()
        pass
    else:
        rd = Record(record_url=outfile, datetime=dt)
        rd.save()
    return HttpResponse(request, '监控成功')
示例#10
0
    def post(self, request, data, *args, **kwargs):

        #Checking the user if logged in
        try:
            user = request.user
        except:
            return Response("INVALID_USER")
        #dictionary for returning data with
        # field names as keys
        returnValue = {}

        #Extracting the data received from post request to get
        # first_name, last_name, province and date_of_birth
        try:
            data = data
            first_name = data['first_name']
            last_name = data['last_name']
            province = data['province']
            date_of_birth = parse_date(data['date_of_birth'])
        except:
            return Response("IMPROPER REQUEST")

        recordobj = None
        try:
            recordobj = Record(first_name=first_name,
                               last_name=last_name,
                               province=province,
                               date_of_birth=date_of_birth)
            recordobj.save()
        except:
            return Response("COULD NOT ADD ROW IN RECORD TABLE")

        #dictionary for returning match obj when one of the condition satisfies
        match_list = {}
        noticeobj = Notice.objects.all()
        for notice in noticeobj:
            #Condition for strong match
            #first or alt first and last or alt_last and province and date_of_birth
            if (
                    notice.first_name == recordobj.first_name
                    or notice.alt_first_name == recordobj.first_name
            ) and (
                    notice.last_name == recordobj.last_name
                    or notice.alt_last_name == recordobj.last_name
            ) and notice.province == recordobj.province and notice.date_of_birth == recordobj.date_of_birth:
                match_list['record_id'] = recordobj.record_id
                match_list['notice_id'] = notice.notice_id
                match_list['match_type'] = "Strong Match"
            #Condition for possible match
            #first  and last  and province
            elif (notice.first_name == recordobj.first_name
                  and notice.last_name == recordobj.last_name
                  and notice.province == recordobj.province):
                match_list['record_id'] = recordobj.record_id
                match_list['notice_id'] = notice.notice_id
                match_list['match_type'] = "Possible Match"
            #Condition for weak match
            #first  and last
            elif (notice.first_name == recordobj.first_name
                  and notice.last_name == recordobj.last_name):
                match_list['record_id'] = recordobj.record_id
                match_list['notice_id'] = notice.notice_id
                match_list['match_type'] = "Weak Match"
            else:
                pass

        #If match_list is not empty insert the record in match else exit the loop
        try:
            if match_list:
                add_row_match = Match(record_id=match_list['record_id'],
                                      notice_id=match_list['notice_id'],
                                      match_type=match_list['match_type'])
                add_row_match.save()
                returnValue['match_id'] = add_row_match.match_id
                returnValue['notice_id'] = add_row_match.notice_id
                returnValue['record_id'] = add_row_match.record_id
                returnValue['match_type'] = add_row_match.match_type

            else:
                returnValue['match_type'] = "NO MATCH FOUND"
        except:
            return Response("COULD NOT ADD ROW IN MATCH TABLE")

        return HttpResponse(json.dumps(returnValue), status=status.HTTP_200_OK)