Пример #1
0
def upload_photo(request):
	if request.method == 'POST':
		sim_file= request.FILES['sim_id']
		f=sim_file.read()
		sim_id=int(f)
		#test if Sim with number=sim_id  exists
		if Sim.objects.filter(number = sim_id).count()==1:
			#Creating Photo object
			uploaded_photo = Photo(phototype= 'Blank', image = request.FILES['file_upload'])
			#Creating Notification object and save to DBB
			mySim=Sim.objects.get(number = sim_id)
			myBox=Box.objects.get(sim = mySim)
			if Notification.objects.filter(title__contains = uploaded_photo.image).count() > 1:
				i=0
				for notification in Notification.objects.filter(title__contains = uploaded_photo.image):
					i+=1			
				titleu=str(uploaded_photo.image) + str(i)
				myNotification = Notification(title = titleu, box=myBox)
			else:
				myNotification = Notification(title = uploaded_photo.image, box=myBox)
			#Traitement d'image
			myNotification.save()
			#Polishing Photo object and save to DBB
			uploaded_photo.notification=myNotification
			uploaded_photo.save()
			#to remove str(sim_id)
			return HttpResponse("Image Uploaded, owner of sim_id = " + str(sim_id))
		else:
			return HttpResponse("ACCESS DENIED: Box Not Identified")
	else:
		return HttpResponse("GET Denied")
Пример #2
0
def upload(request):
    attachedPhotoFiles = [(fieldName, file) for fieldName, file in request.FILES.iteritems() if 'photo' in fieldName]
    ids = []
    for fieldName, file in attachedPhotoFiles:
        photo = Photo(photo=file)
        photo.save()
        ids.append(photo.id)
    return HttpResponse(json.dumps(ids, sort_keys=True, indent=2), content_type="application/json")
Пример #3
0
 def post(self, request):
     create_time = request.POST.get('create_time', '1')
     photo_name = request.POST.get('photo_name', '1')
     photo = Photo()
     photo.create_time = create_time
     photo.image = photo_name
     photo.save()
     print(create_time, photo_name)
     return JsonResponse({"res": 1, "message": "chenggong"})
Пример #4
0
def photo_load(request, pk, apk):
    o = get_object_or_404(Object, pk=pk)
    a = get_object_or_404(Album, pk=apk)
    if request.method == 'POST':
        for file in request.FILES.getlist('file'):
            p = Photo()
            p.owner = request.user
            p.published_date = timezone.now()
            p.album = a
            p.photo.save(str(file), file, save=True)
            p.thumb_make()
            p.save()
    return redirect('object.views.object_view', pk=o.pk)
Пример #5
0
def photo_load (request, pk, apk):
    o = get_object_or_404(Object, pk=pk) 
    a = get_object_or_404(Album, pk=apk)   
    if request.method == 'POST': 
        for file in request.FILES.getlist('file'):
            p = Photo()
            p.owner = request.user
            p.published_date = timezone.now()  
            p.album = a
            p.photo.save(str(file),file,save=True)
            p.thumb_make()          
            p.save()           
    return redirect('object.views.object_view', pk=o.pk) 
Пример #6
0
 def pipeline(self, mediaItem):
     # only download images
     try:
         # get the image data
         filename = mediaItem['filename']
         imagebinary = self.session.get(mediaItem['baseUrl'] + '=d').content
         with open(f'{self.IFR}/{self.userId}/{filename}',
                   mode='wb') as handler:
             handler.write(imagebinary)
         image = Image(content=imagebinary)
         response = self.client.label_detection(image=image)
         if response.error.message:
             raise Exception(response.error.message)
         labels = response.label_annotations
         ltemp = list(map(getLabelDescription, labels))
         mLabels = toMandarin(ltemp)
         t = Tag()
         bs = BasicStructure()
         for el, l in zip(ltemp, labels):
             bs.main_tag.append(ATag(tag=el, precision=l.score))
         t.en = bs
         if mLabels and len(mLabels) > 0:
             bs = BasicStructure()
             for ml, l in zip(mLabels, labels):
                 bs.main_tag.append(ATag(tag=ml, precision=l.score))
             t.zh_tw = bs
         tempcreationTime = mediaItem['mediaMetadata']['creationTime']
         sliceTime = tempcreationTime.split('Z')[0].split(
             '.')[0] if '.' in tempcreationTime else tempcreationTime.split(
                 'Z')[0]
         realTime = datetime.datetime.strptime(sliceTime,
                                               "%Y-%m-%dT%H:%M:%S")
         pho = Photo(
             photoId=mediaItem['id'],
             filename=filename,
             userId=self.userId,
             tag=t,
             createTime=make_aware(realTime,
                                   timezone=pytz.timezone(
                                       settings.TIME_ZONE)),
         )
         pho.save()
     except Exception as e:
         logging.error(e)
         print(f'Error from initial vision api pipline {e}')
         print(traceback.format_exc())
Пример #7
0
def thread(request, title):
    if request.method == 'POST':
        # webhook POST receive action
        params = request.POST
        try:
            # titleなスレがなかったらエラーがおきるはず
            thread = Thread.objects.filter(title=title).get()
            try:
                # shooting_atがなかったら現在時刻
                shooting_at = datetime.strptime(params['shooting_at'], '%Y/%m/%d %H:%M:%S')
            except:
                shooting_at = datetime.now()
            # passphrase確認
            if thread.phrase == params['pass']:
                photo = Photo(name=params['photo_id'], shooting_at=shooting_at, thread=thread)
                photo.image.save('%s.jpg' % params['photo_id'], request.FILES['imagedata'])
                photo.save()
                thread.modified_at = datetime.now()
                thread.save()
        finally:
            # エラーや結果に関係なくレスポンスは返す
            return HttpResponse('hi')

    if request.method == 'GET':
        try:
            # titleスレがすでにある場合は写真一覧
            thread = Thread.objects.filter(title=title).get()
            photos = thread.photo_set.order_by('-created_at')[:40]
            thread.photos = []
            for photo in photos:
                thread.photos.append(photo)
            ec = {
                'thread' : thread
            }
            return direct_to_template(request, 'photo/thread.html', extra_context=ec)
        except:
            thread = Thread(title=title, phrase="")
            ec = {
                'thread' : thread
            }
            # スレがない場合はパスフレーズ入力フォーム
            return direct_to_template(request, 'photo/thread.html', extra_context=ec)
Пример #8
0
def upload_test(request):
	if request.method == 'POST':
		sim_id= request.POST['sim_id']
		#test if Sim with number=sim_id  exists
		if Sim.objects.filter(number = sim_id).count()==1:
			#Creating Photo object
			uploaded_photo = Photo(phototype= 'Blank', image = request.FILES['file_upload'])
			#Creating Notification object and save to DBB
			mySim=Sim.objects.get(number = sim_id)
			myBox=Box.objects.get(sim = mySim)
			if Notification.objects.filter(title__contains = uploaded_photo.image).count() > 1:
				i=0
				for notification in Notification.objects.filter(title__contains = uploaded_photo.image):
					i+=1			
				titleu=str(uploaded_photo.image) + str(i)
				myNotification = Notification(title = titleu, box=myBox)
			else:
				myNotification = Notification(title = uploaded_photo.image, box=myBox)
			#Traitement d'image
			myNotification.save()
			#Polishing Photo object and save to DBB
			uploaded_photo.notification=myNotification
			uploaded_photo.save()
			#C:\Users\Elomario\Desktop\PI\Phase2\CMAIL-django\
			#notificationu=Notification.objects.get(title='test recette')
			#photou=Photo.objects.get(notification=notificationu)
			print(str(uploaded_photo.image))
			ls_fd = subprocess.Popen('static\SimpleColorDetection_TEST.exe ' + str(uploaded_photo.image),stdout=subprocess.PIPE).communicate()[0]
			print('done')
			out = ls_fd
			#ENDOFIMAGEHANDLING
			if "letter" in str(out):
				uploaded_photo.phototype='enveloppe'
			elif "colis" in str(out):
				uploaded_photo.phototype='colis'
			elif "pub" in str(out):
				uploaded_photo.phototype='pub'
			uploaded_photo.save()
			return HttpResponse("DO A POST " +  str(out))
			
		else:
			return HttpResponse("ACCESS DENIED: Box Not Identified")
Пример #9
0
def photo_handle(request):
    userFolder = "img/" + str(request.user.id) + "-" + \
        str(request.user.username)
    ffolder = '{}/{}'.format(settings.MEDIA_ROOT, userFolder)
    if not os.path.exists(ffolder):
        os.makedirs(ffolder)

    f1 = request.FILES.get('pic')  # 从前端获取上传的图片
    fname = ffolder + "/" + f1.name  # 图片的完整路径
    # print(fname)

    with open(fname, 'wb') as pic:  # 文件操作
        for c in f1.chunks():  # 因为图片存储的方式是二进制流,用f1.chunks()获取图片的字节
            pic.write(c)

    pic1 = Photo()
    pic1.pic = '{}/{}'.format(userFolder, f1.name)
    pic1.author = request.user

    pic1.save()
    return HttpResponse('OK')
Пример #10
0
 def test_build_faces_from_photo(self):
     photo = Photo(path="/0e67e4b99c2c4028a7bfc9c7dabe5152_r.jpg")
     photo.save()
     face = Face.build_faces_from_photo(photo)
     self.assertIsNotNone(face)