コード例 #1
0
ファイル: views.py プロジェクト: dkuspawono/phai
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
			#request docfile
            newdoc = Document(docfile = request.FILES['docfile'])
            #save information in database
            newdoc.save()
            libc = ctypes.CDLL("myproject/src/myproject/media/lib/lib.so")
            #call to address library
            #/home/ht/workspace/myproject/src/myproject/media/documents
            libc.transfer_color("/myproject/src/myproject/media/documents/rose.jpg","/myproject/src/myproject/media/documents/blue.jpg","/myproject/src/myproject/media/documents/test.jpg")
            #call function in library
            #document = Document(docfile='documents/tem.jpg')
            #document.save()
            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myapp.views.list'))
    else:
        form = DocumentForm() 
    # A empty, unbound form
    # Load documents for the list page
    documents = Document.objects.all()#list image in database
    # Render list page with the documents and the form
    return render_to_response(
        'myapp/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )# return list image
コード例 #2
0
def upload(request):
    # Handle file upload
    if request.user.is_authenticated() == False:
        return HttpResponseRedirect('/accounts/login')
    print(request.user.is_authenticated())
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            some_var = request.POST.getlist('checks[]')
            print some_var
            newdoc = Document(docfile=request.FILES['docfile'], videoname=request.POST['videoname'], channel=some_var[0])
            newdoc.save()
            clip = VideoFileClip('media/'+str(newdoc.docfile))
            clip.save_frame('media/frame'+str(newdoc.id)+'.png', t=2)
            newVideo = VideoQueue(videoID=newdoc.id, clipduration=clip.duration, clipurl='frame'+str(newdoc.id)+'.png')
            newVideo.save()
            # Redirect to the document list after POST
            return HttpResponseRedirect('/myapp/index?videoid='+str(newVideo.id))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render(
        request,
        'list.html',
        {'documents': documents, 'form': form}
    )
コード例 #3
0
ファイル: views.py プロジェクト: leonardox/pythonHeat
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(user=request.POST['user'],
                              docfile=request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # _get_token()
    # Load documents for the list page
    documents = {}
    documents_db = Document.objects.all()

    for document in documents_db:
        if documents.has_key(document.user):
            documents[document.user].append(document)
        else:
            documents[document.user] = [document]

    # Render list page with the documents and the form
    return render(request, 'list.html', {'documents': documents, 'form': form})
コード例 #4
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            rfile = str(request.FILES['docfile'])
            extension = rfile[::-1][:rfile[::-1].find('.')][::-1]
            if extension == 'mp3':
                newdoc = Document(docfile=request.FILES['docfile'])
                newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
コード例 #5
0
ファイル: views.py プロジェクト: AnkushAppy/apk_checker
def list(request):
    # Handle file upload

    if request.method == "POST":
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES["docfile"])
            newdoc.save()
            apk_reader.delay(newdoc.docfile.url, request.FILES["docfile"].name)

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse("myproject.myapp.views.list"))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()
    fileinfos = FileInfo.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        "list2.html",
        {"documents": documents, "form": form, "fileinfos": fileinfos},
        context_instance=RequestContext(request),
    )
コード例 #6
0
def list(request):
    if request.method == 'GET':
        return HttpResponseRedirect("/home/")
        # return HttpResponse('This page shows a list of most recent posts.')
        # pass
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()
            runScript()

            # Redirect to the document list after POST
            return HttpResponseRedirect("../home/")
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'home.html',
        {'documents': documents, 'form': form},

        context_instance=RequestContext(request)
    )
コード例 #7
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    my_document = None
    for document in documents:
        my_document = document

    # Render list page with the documents and the form
    return render(request, 'list.html', {
        'documents': my_document,
        'form': form
    })
コード例 #8
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myproject.myapp.views.list'))

    else:
        form = DocumentForm()  # empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    api_res = []
    #    for f in documents:
    #       api_res.append(faceApi(f.docfile.url))

    # Render list page with the documents and the form
    return render_to_response('myapp/list.html', {
        'documents': documents,
        'form': form
    },
                              context_instance=RequestContext(request))
コード例 #9
0
ファイル: views.py プロジェクト: vasudevgarg/pbbauea
def upload_files(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'],user=request.user)
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
    else:
        form = DocumentForm()
        
 
    # Load documents for the list page
 #   d1=Document()
  #  documents = d1.get_my_files(request.user)
    documents = Document.objects.filter(user=request.user)
#    shared_doc = Document.objects.filter(user=request.user)
 #   shared_doc=Document.objects.filter(event__to_user=request.user)
   # sharing.objects.filter(shared_user=request.user)    #filter(shared_file= ,shared_user= )
    # Render list page with the documents and the form
    return render_to_response(
        'list.html',
        {'documents': documents, 'form': form,  'username':request.user },
        context_instance=RequestContext(request)
    )
コード例 #10
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
		form = DocumentForm(request.POST, request.FILES)
		files = request.FILES.getlist('docfile')
		# files = form.cleaned_data['docfile']
		for newdoc in files:
			if form.is_valid():
				# newdoc = Document(docfile=request.FILES['docfile'])
				newdoc.save()

				# Redirect to the document list after POST
				return HttpResponseRedirect(reverse('list'))
	else:
		form = DocumentForm()  # A empty, unbound form

	# Load documents for the list page
	documents = Document.objects.all()

	# Render list page with the documents and the form
	return render(
		request,
		'list.html',
		{'documents': documents, 'form': form}
	)
コード例 #11
0
def list(request):
    imglist=[]
    namelist=[]
    if request.method=='POST':
        form=DocumentForm(request.POST,request.FILES)

        if 'file' in request.FILES:
            image=request.FILES['file']
            imglist.append(image)
        if 'file1' in request.FILES:
            image=request.FILES['file1']
            imglist.append(image)
        for image in imglist:
            u=Document()
            u.docfile=image
            namelist.append(u.docfile)
            u.save()

        path1='D:/87/media/'+str(namelist[0])
        path2='D:/87/media/'+str(namelist[1])
        path=imgtest(path1,path2)


        return render(request, 'list.html', {'form': form, 'path':path})

        #return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm()
    return render(
        request,
        'list.html',
        {'form': form}
    )
コード例 #12
0
ファイル: views.py プロジェクト: GauthamGoli/anotherportal
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()
            output_path = "D:/potree-1.4RC/potree-1.4RC/resources/pointclouds/"+ntpath.basename(newdoc.docfile.path)
            p = subprocess.Popen(['PotreeConverter.exe',
                                  newdoc.docfile.path,
                                  "-o",
                                  output_path],
                                  stdout=subprocess.PIPE,
                                  shell=True)
            output, err = p.communicate()
            print output
            # Redirect to the document list after POST
            #return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
            return HttpResponse('../'+output_path[output_path.index('resources'):]+'/cloud.js')
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
コード例 #13
0
def home(request):
    import os
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()
            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myproject.myapp.views.home'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()
    for document in documents:
        document.docfile.documentName = os.path.basename(document.docfile.name)


    # Render list page with the documents and the form
    return render_to_response(
        'home.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
コード例 #14
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            fname = form.cleaned_data['fname']
            lname = form.cleaned_data['lname']
            description = form.cleaned_data['description']
            #need to figure out how to handle data from choice
            #here is where we put this data on some database      
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render(
        request,
        'myapp/list.html',
        {'documents': documents, 'form': form}
    )
コード例 #15
0
def list(request):

    context = {}
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()

            context.update(get_table_context(request.FILES['docfile']))
            context["has_table"] = True
    else:
        form = DocumentForm() # A empty, unbound form
        context["has_table"] = False

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    context["documents"] = documents
    context["form"] = form
    
    return render_to_response(
        'myapp/list.html',
        context,
        context_instance=RequestContext(request)
    )
コード例 #16
0
def list(request):
    # Handle file upload

    # f**k(request)

    print "something enter"
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        print "//////////////////////////////////////////"
        # print request
        # print form


        print "//////////////////////////////////////////"

        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()
            # logger.debug(request)
            # logger.debug(request.POST)

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
コード例 #17
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()

            #pass to opencv
            BASE_PATH = '/home/apon/Ongoing/SDL/myproject/media/'
            folder = 'documents/'
            uploaded_filename = request.FILES['docfile'].name
            full_filename = BASE_PATH + folder + uploaded_filename
            print(full_filename)
            #global images = opencv.ProcessImage(full_filename)

            # Redirect to the document list after POST
            #return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
            return HttpResponseRedirect(reverse('myproject.myapp.views.show'))
            #return render(request, 'show.html')
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response('list.html', {
        'documents': documents,
        'form': form
    },
                              context_instance=RequestContext(request))
コード例 #18
0
ファイル: views.py プロジェクト: nipa0827/OCR
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()

            text = pytesseract.image_to_string(Image.open(newdoc.docfile),
                                               lang='eng',
                                               config='digits')

            #writing data in data.doc file
            handle = open('data.doc', 'w+')
            handle.write(text)
            handle.close()

            #writing data in data.txt file
            textFile = open('data.txt', 'w+')
            textFile.write(text)
            textFile.close()

            ll = []

            with open('data.txt', 'r') as readFile:
                rr = readFile.readline()
                ll.append(rr)

            readFile.close()

            f = open('data.doc', 'r')

            for x in f:
                ll.append(x)

            file_content = ll
            f.close()

            #writing data in data.csv file
            with open('data.csv', 'w') as csvFile:
                writer = csv.writer(csvFile)
                writer.writerow(ll)
            csvFile.close()

            context = {'file_content': file_content}

            # Redirect to the document list after POST
            return render(request, 'showText.html', context)
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response('list.html', {
        'documents': documents,
        'form': form
    },
                              context_instance=RequestContext(request))
コード例 #19
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        art = ImageForm(request.POST, request.FILES)
        if form.is_valid() and art.is_valid():
            print "poopoerz"
            newdoc = Document(docfile = request.FILES['docfile'], genre=request.POST['genre'], title=request.POST['title'])
            newimg = Image(image = request.FILES['image'])
            newdoc.save()
            newimg.save()
            newdemo = Demo(doc = newdoc, img = newimg)
            newdemo.save()
            print  "HERE"
            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
    else:
        form = DocumentForm() # A empty, unbound form
        art = ImageForm()
    # Load documents for the list page
    documents = Document.objects.all()
    images =  Image.objects.all()


    # Render list page with the documents and the form
    return render_to_response(
        'myapp/list.html',
        {'documents': documents, 'images':images, 'form': form, 'art': art},
        context_instance=RequestContext(request)
    )
コード例 #20
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()
            url=newdoc.docfile.url
            obj = Classification()
            name = obj.imageClassification(newdoc.docfile.path)
            Predicted_image_name=name[0]

            # Redirect to the document list after POST
            return render(request,'abc.html',{"image_path" : url,"object_name" : Predicted_image_name})
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
コード例 #21
0
def list(request):
    if request.method == 'GET':
        return HttpResponseRedirect("/home/")
        # return HttpResponse('This page shows a list of most recent posts.')
        # pass
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()
            runScript()

            # Redirect to the document list after POST
            return HttpResponseRedirect("../home/")
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response('home.html', {
        'documents': documents,
        'form': form
    },
                              context_instance=RequestContext(request))
コード例 #22
0
ファイル: views.py プロジェクト: kirankaranth1/ShareIt
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()
            url = newdoc.docfile.url
            request.session['file_url'] = url

            # Redirect to the document list after POST
            return HttpResponseRedirect(
                reverse('myproject.myapp.views.email_url'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response('myapp/list.html', {
        'documents': documents,
        'form': form
    },
                              context_instance=RequestContext(request))
コード例 #23
0
def list(request):
    # Handle file upload
    #Document.objects.all().delete()
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            #newdoc = Document(docfile = request.FILES['docfile'])
            #newdoc.save()
            #Root Image File
            newdoc = BasicImage(docfile = request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            #return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
            imagenm = newdoc.docfile.url
            #[nameList,django_file,returnstr] = classification(imagenm)
            [nameListList,djangoFileList,returnStrList] = classification(imagenm)
            
            #for each detection result, save them in the database
            print '-----------------------------'
            print len(nameListList)
            print '-----------------------------'
            
            for i in range(0,len(nameListList)):
                nameList = nameListList[i]
                returnstr = returnStrList[i]
                django_file = djangoFileList[i]
                
                subImage = Document(basefile=newdoc)
                
    
                #results = Result.objects.all()
                subImage.catagory = returnstr
                subImage.imgfile = django_file
                subImage.top1 = subImage.catagory+'processed/'+nameList[0]
                subImage.top2 = subImage.catagory+'processed/'+nameList[1]
                subImage.top3 = subImage.catagory+'processed/'+nameList[2]
                
                #look up the database to fetch name and url of these three top bags
                [subImage.top1_url,subImage.top1_name] = fetchDatafromSQL(1,subImage)
                [subImage.top2_url,subImage.top2_name] = fetchDatafromSQL(2,subImage)
                [subImage.top3_url,subImage.top3_name] = fetchDatafromSQL(3,subImage)
                
                subImage.save()
                
            my_images = Document.objects.filter(basefile_id=newdoc.id)
            return render(request, 'myapp/index.html', {'newdoc':newdoc,'my_images':my_images})
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
コード例 #24
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():

            # # original code
            # newdoc = Document(docfile=request.FILES['docfile'])
            # newdoc.save()

            # # Redirect to the document list after POST
            # return HttpResponseRedirect(reverse('list'))
            # # orignal code up to here commented out

            # set up an Excel file
            # cf: https://xlsxwriter.readthedocs.org/en/latest/example_http_server3.html
            import io
            output    = io.BytesIO()
            workbook  = xlsxwriter.Workbook(output, {'in_memory': True})
            worksheet = workbook.add_worksheet()

            # do something to the file being uploaded
            for row, item in enumerate(request.FILES['docfile']):
                # logging.debug(item)
                # logging.debug( type(item) )
                worksheet.write( row, 0, item.decode() )  # item is bytes. convert it to string

            workbook.close()
            excel_data = output.getvalue()

            # Rewind the buffer.
            response = HttpResponse(content_type='application/vnd.ms-excel')
            response['Content-Disposition'] = 'attachment; filename=Report.xlsx'
            response.write(excel_data)

            # # actually I don't need save the original file
            # newdoc = Document(docfile=request.FILES['docfile'])
            # newdoc.save()
            # logging.debug('type of newdoc is {}.'.format(type(newdoc)) )
            # logging.debug(newdoc)

            # # Redirect to the document list after POST
            # return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
            return response

    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render(
        request,
        'list.html',
        {'documents': documents, 'form': form}
    )
コード例 #25
0
ファイル: views.py プロジェクト: zhaw/wine_private
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()
            file_name = newdoc.docfile.name
            if 0 and not file_name.split('/')[1].replace('.','').isalnum():
                new_name = ''
                for c in file_name.split('/')[1]:
                    if c.isalnum() or c == '.':
                        new_name += c
                os.system('mv media/query/%s media/query/%s'%(file_name, new_name))
                with open('job', 'w') as f:
                    f.write(new_name)
                    os.system('convert media/query/%s -resize x750 media/query/%s'%(new_name, new_name))
            else:
                with open('job', 'w') as f:
                    file_name = newdoc.docfile.name.split('/')[1].encode('utf-8')
                    f.write(file_name)
                    os.system('convert media/query/%s -resize x750 media/query/%s'%(file_name, file_name))

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()
    
    with open('job') as f:
        file_name = f.read()
    done = 0
    if file_name.strip() != 'nojob':
        while done == 0:
            try:
                with open('media/result/'+file_name.decode('utf-8')+'txt') as f:
                    t = f.read()
                    if not t:
                        raise Exception
                with open('job', 'w') as f:
                    f.write('nojob')
                done = 1
            except Exception as e:
                done = 0
    else:
        file_name = []
        done = 0

    # Render list page with the documents and the form
    return render_to_response(
        'list.html',
        {'file_name': file_name, 'form': form, 'done': done},
        context_instance=RequestContext(request)
    )
コード例 #26
0
ファイル: views.py プロジェクト: tsennott/etc_projects
def gif(request, guid_id):

    user = get_object_or_404(User, pk=guid_id)
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            orig_file = request.FILES['docfile']
            orig_image = Image.open(orig_file)
            point = pointillizeStack(image=orig_image,
                                     reduce_factor=2,
                                     border=0,
                                     queue=True)
            point.resize(0, 550)
            point.plot('balanced')
            multipliers = [
                5, 4.5, 4, 3.5, 3, 2.6, 2.3, 2, 1.75, 1.5, 1.25, 1.1, 1, 1
            ]
            multipliers.reverse()
            point.build_multipliers(multipliers, reverse=True)
            # point.save_gif('temp/' + guid_id + '_pointqueue.gif', 0.1)
            new_gif_IO = io.BytesIO()
            point.save_gif(new_gif_IO, 0.1)
            new_file = InMemoryUploadedFile(
                new_gif_IO,
                u"docfile",  # change this?
                (orig_file.name.split('.')[0] + ' pointillized.gif'),
                'image/gif',
                None,
                None)
            newdoc = user.document_set.create(docfile=new_file)
            newdoc.save()
            origdoc = user.document_set.create(docfile=orig_file)
            origdoc.save()
            # os.remove('temp/' + guid_id + '_pointqueue.gif')

            # Redirect to the document upload page after POST
            return HttpResponseRedirect(
                reverse('gif', kwargs={'guid_id': user.pk}))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the upload page
    all_documents = user.document_set.order_by("-id")
    documents = []
    for document in all_documents:
        if (document.docfile.name[-16:] == 'pointillized.gif'):
            documents.append(document)

    # Render upload page with the documents and the form
    return render(request, 'upload_to_gif.html', {
        'documents': documents,
        'form': form,
        'guid_id': user.pk
    })
コード例 #27
0
ファイル: views.py プロジェクト: Super12He/Dashborad_Website
def upload(request, template='upload.html'):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        files = request.FILES.getlist('file')
        if form.is_valid():
            for f in files:
                handle_uploaded_file(f)
            return HttpResponse('upload success')
    else:
        form = DocumentForm()
    return render(request, 'upload.html', {'form': form})
コード例 #28
0
def upload(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():

            my_file = Paths("/home/fernando/Desktop/myproject/media/samples/" +
                            request.FILES['docfile'].name)
            if my_file.is_file():
                os.remove("/home/fernando/Desktop/myproject/media/samples/" +
                          request.FILES['docfile'].name)  # remove duplicates
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()
            my_file = '/home/fernando/Desktop/myproject/media/samples/' + request.FILES[
                'docfile'].name
            pathtofile = my_file.encode('ascii', 'ignore')
            subprocess.call(
                '/home/fernando/Desktop/myproject/myproject/myapp/submitsample.sh '
                + pathtofile,
                shell=True)
            time.sleep(5)
            latest_file_sha = max([
                os.path.join('/home/fernando/.cuckoo/storage/binaries', d)
                for d in os.listdir('/home/fernando/.cuckoo/storage/binaries')
            ],
                                  key=os.path.getmtime)
            latest_file_sha = os.path.basename(latest_file_sha)
            latest_dir_analisys = os.path.basename(
                os.readlink('/home/fernando/.cuckoo/storage/analyses/latest'))
            filename = request.FILES['docfile'].name
            dirpath = '/home/fernando/.cuckoo/storage/analyses/' + str(
                (int(latest_dir_analisys) + 1)) + '/'
            newinfo = Path(namefile=filename,
                           idsha256=latest_file_sha,
                           pathto=dirpath)  # Ok
            newinfo.save()
            print newinfo.idsha256
            # analisysinfo = Path.objects.create(namefile=filename,idsha256=latest_file_sha,pathto=dirpath)
            return render(
                request, 'submited.html', {
                    'latest_file_sha': latest_file_sha,
                    'dirpath': dirpath,
                    'filename': filename
                })

            # Redirect to the document list after POST
            # return HttpResponseRedirect(reverse('upload'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Render list page with the documents and the form
    return render(request, 'upload.html', {'form': form})
コード例 #29
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        print "reset logIn to empty"
        print "HERE IS THE POST METHOD"
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()

            print("Retrive the uploaded file")
            dirTwoLevelUp = os.path.abspath(
                os.path.join(os.path.dirname(__file__), '../..',
                             'media/documents'))
            addSlashToFile = '/' + request.FILES['docfile'].name
            uploadedFileAbsPath = os.path.join(dirTwoLevelUp,
                                               request.FILES['docfile'].name)

            print("uploadedFileAbsPath  : ")
            print(uploadedFileAbsPath)

            print("fileFormatSelection: ")
            print(request.POST['fileFormatSelection'])

            if (request.POST['fileFormatSelection'] == 'M_V_1'):
                ValidationIndex = 1
            else:
                ValidationIndex = 3
            print("Start the validation process")
            validateMarginFile.validateMarginFileProcess(
                uploadedFileAbsPath, ValidationIndex, logInfo, logError)
            # validateMarginFile.validateMarginFileProcess("/Users/mifang/Documents/Expedia/Project/tutorial/djangoTutorial/dq-djang-python-validation-webapp/myproject/myproject/myapp/resource/DataFile/sample3.0.csv",3,logInfo)

            print("Start to remove the file from the folder")
            try:
                os.remove(uploadedFileAbsPath)
            except:
                print("Failed to remove the file from cloud")

            print "HERE IS THE LogInfo before reverse to log"
            print logInfo
            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('log'))
    else:
        print "HERE ISTHE ELSE CONDTION"
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render(request, 'list.html', {'documents': documents, 'form': form})
コード例 #30
0
ファイル: views.py プロジェクト: tsennott/etc_projects
def upload(request, guid_id):

    user = get_object_or_404(User, pk=guid_id)
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            orig_file = request.FILES['docfile']
            orig_image = Image.open(orig_file)
            point = pointillize(image=orig_image, reduce_factor=2)
            # point.plotRecPoints(n=40, multiplier=1, fill=False)
            # point.plotRandomPointsComplexity(n=2e4, constant=0.01, power=1.3)
            point.resize(ratio=0, min_size=2200)
            setting = request.POST['setting']
            point.plot(setting)
            new_stringIO = io.BytesIO()
            point.out.convert('RGB').save(
                new_stringIO,
                orig_file.content_type.split('/')[-1].upper())
            new_file = InMemoryUploadedFile(
                new_stringIO,
                u"docfile",  # change this?
                (orig_file.name.split('.')[0] + ' ' + setting +
                 ' pointillized.jpg'),
                orig_file.content_type,
                None,
                None)
            newdoc = user.document_set.create(docfile=new_file)
            newdoc.save()
            origdoc = user.document_set.create(docfile=orig_file)
            origdoc.save()

            # Redirect to the document upload page after POST
            return HttpResponseRedirect(
                reverse('upload', kwargs={'guid_id': user.pk}))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the upload page
    all_documents = user.document_set.order_by("-id")
    documents = []
    for document in all_documents:
        if document.docfile.name[-16:] == 'pointillized.jpg':
            documents.append(document)

    # Render upload page with the documents and the form
    return render(request, 'upload.html', {
        'documents': documents,
        'form': form,
        'guid_id': user.pk
    })
コード例 #31
0
def uploadtest(request):
	# Handle file upload

	if request.method == 'POST':
		docform = DocumentForm(request.POST, request.FILES)
		if docform.is_valid():
			newdoc = Document(docfile=request.FILES['docfile'])

			filename = docform.cleaned_data['docfile'].name.split('.')[0]
			fileformat = docform.cleaned_data['docfile'].name.split('.')[-1]
			name = docform.cleaned_data['your_name']

			my = filename.split('_')[0]
			vp = filename.split('_')[1]
			code = filename.split('_')[2]
			phase = filename.split('_')[3]

			ftime = filename.split('_')[-1]
			fname = filename.replace(" ","_")
			localtime = timeNorm(ftime)
			# localtime = time.strftime('%Y-%m-%d',time.localtime(time.time()))

			if fileformat == 'xlsx':
				pythoncom.CoInitialize()
				newdoc.save()
				summaryTable = 'D:/DjangoWeb/myproject/media/DYNOTable.csv'
				fpath = 'D:/DjangoWeb/myproject/media/documents/' + fname
				csvfile = file(summaryTable,'ab+')
				writer = csv.writer(csvfile)
				writer.writerow([name,filename,vp,code,phase,localtime,my])
				csvfile.close()
				convertExcel(fpath)
			# else:
				# raise forms.ValidationError("gaga")

			# Redirect to the document list after POST


	else:
		docform = DocumentForm()  # A empty, unbound form
	# Load documents for the list page
	documents = Document.objects.all()

	# Render list page with the documents and the form
	return render(
		request,
		'upload.html',
		{'documents': documents, 'form': docform}
	)
コード例 #32
0
ファイル: views.py プロジェクト: ocrplusplus/ocrplusplus
def list(request):
    if request.method == 'GET':
        return HttpResponseRedirect("/home/")
        # return HttpResponse('This page shows a list of most recent posts.')
        # pass
    # Handle file upload
    if request.method == 'POST':

        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            # Manage Sessions
            lock.acquire()
            sId = '0'
            try:
                sId = open("sessionId.txt",'rb').read()
            except Exception as e:
                print e
            try:
                sId = str((int(sId))+1)
            except Exception as e:
                sId = '1'
                print e
            open("sessionId.txt",'wb').write(sId)
            request.session['id'] = sId
            # lock.release()

            newdoc = Document(docfile = request.FILES['docfile'])
            fname = request.FILES['docfile'].name
            request.session['filename'] = fname
            newdoc.save()
            runScript(request)
            lock.release()

            # Redirect to the document list after POST
            return HttpResponseRedirect("../home/")
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'home.html',
        {'documents': documents, 'form': form},

        context_instance=RequestContext(request)
    )
コード例 #33
0
ファイル: views.py プロジェクト: zongorla/ocrplusplus
def list(request):
    if request.method == 'GET':
        return HttpResponseRedirect("/home/")
        # return HttpResponse('This page shows a list of most recent posts.')
        # pass
    # Handle file upload
    if request.method == 'POST':

        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            # Manage Sessions
            lock.acquire()
            sId = '0'
            try:
                sId = open("sessionId.txt", 'rb').read()
            except Exception as e:
                print e
            try:
                sId = str((int(sId)) + 1)
            except Exception as e:
                sId = '1'
                print e
            open("sessionId.txt", 'wb').write(sId)
            request.session['id'] = sId
            # lock.release()

            newdoc = Document(docfile=request.FILES['docfile'])
            fname = request.FILES['docfile'].name
            request.session['filename'] = fname
            newdoc.save()
            runScript(request)
            lock.release()

            # Redirect to the document list after POST
            return HttpResponseRedirect("../home/")
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response('home.html', {
        'documents': documents,
        'form': form
    },
                              context_instance=RequestContext(request))
コード例 #34
0
ファイル: views.py プロジェクト: avkozlov/statov
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()



            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myproject.myapp.views.list'))

    else:
        form = DocumentForm() # A empty, unbound form


    # Load documents for the list page
    documents = Document.objects.all()[4:]

    a = Document.objects.last()
    url = 'myproject' + a.docfile.url

    if os.path.isfile(url):
        vic = 'TRUE'

        v = ExcelFile(url).parse("Sheet1", parse_cols=[0, 18, 26, 25, 23])
        v.columns = ['Request','Product', 'Paid', 'PaidDate', 'Type']
        # it is right!.to_datetime,
        v.PaidDate = pd.to_datetime(v.PaidDate, format='%d.%m.%Y' )
        df = pd.pivot_table(v, values='Paid', rows='PaidDate', cols=['Type', 'Product'], aggfunc=[np.sum, np.count_nonzero])
        df = df.resample('M', how='sum')
        df = df.fillna(value=0)

        # Render list page with the documents and the form
        return render_to_response(
            'myapp/list.html',
            {'documents': documents, 'form': form, 'df': df.to_html(classes="table-condensed"),'url':url, 'vic': vic},
            context_instance=RequestContext(request)
        )
    else:
        vic = 'False'
        return render_to_response(
            'myapp/list.html',
            {'documents': documents, 'form': form, 'url': url, 'vic': vic},
            context_instance=RequestContext(request)
        )
コード例 #35
0
ファイル: views.py プロジェクト: stepanevich/match_maker
def filename(request):
    pair ={}
    results = []
    # Handle file upload
    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            #newdoc = Document(docfile=request.FILES['docfile'])
            #newdoc.save()
            #picture = Document.objects.get(name = picture_name)
            documents = Document.objects.all()
            documents_dict = {}
            features = {}
            names = []
            for i in documents:
                name = i.docfile.name.split('/')[-1].lower()
                names.append(name)
                features[name] = pickle.loads(i.features)[(i.docfile.name).lower()]
                documents_dict[name] = i
            #names.append(request.FILES['docfile'].name)
            file = os.path.join(settings.MEDIA_ROOT, request.FILES['docfile'].name) 
            print(file)
            files = [os.path.join(settings.MEDIA_ROOT, p) for p in names]
            #print ('Extracting features from image %s' % file)
            #name = file.split('/')[-1].lower()
            #features[name] = extract_features(file)
            #print(features)
            #print(len(files))
            
            ma = Matcher(features)

            print ('Query image ==========================================')
            names, match = ma.match(file)
            print ('ЭТО documents_dict')
            print (documents_dict)
            pair = zip(names,match)
            list_pair = sorted(pair, key=lambda x: x[-1])
            for n, w in list_pair:
                documents_dict[n].weight = w
                results.append(documents_dict[n])
                print('Wheight %s' % (1-w))
            print ('Result images ========================================')
            #print (names)
            #print (match)
            for m in range(len(files)):
                print ('Match %s' % (1-match[m]))
    else:
        form = DocumentForm()  # A empty, unbound form


    # Render list page with the documents and the form
    return render(
        request,
        'filename.html',
        {'form': form,
         'documents': results}
    )  
コード例 #36
0
ファイル: views.py プロジェクト: Granvanoeli/Demo-upload
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        # art = ImageForm(request.POST, request.FILES)

        if form.is_valid():
            print "poopoerz"
            # newimg = Image(image = request.FILES['image'])
            # newimg.save()
            # print "image saved"
            newdoc = Document()
            newdoc.img = request.FILES['img']
            newdoc.user = request.user.username
            print newdoc.user
            # newdoc = Document(docfile= request.FILES['docfile'], genre=request.POST['genre'], title=request.POST['title'], up=request.POST['up'], down=request.POST['down'], img = newimg)
            newdoc.docfile = request.FILES['docfile']
            newdoc.genre = request.POST['genre']
            newdoc.title = request.POST['title']
            newdoc.up = request.POST['up']
            newdoc.down = request.POST['down']
            # newdoc.img = newimg
            newdoc.save()



            print "HERE"
            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
    else:
        form = DocumentForm() # A empty, unbound form
        # art = ImageForm()
    # Load documents for the list page
    documents = Document.objects.all()
    # images = Image.objects.all()


    # Render list page with the documents and the form
    return render_to_response(
        'myapp/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
コード例 #37
0
ファイル: views.py プロジェクト: nipa0827/OCR
def home(request):
    form = DocumentForm()
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response('list.html', {
        'documents': documents,
        'form': form
    },
                              context_instance=RequestContext(request))
コード例 #38
0
def list(request):
    global i
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()

            i += 1
            # import ipdb;ipdb.set_trace()
            d = Document.objects.get(id=i)

            #print d.docfile
            k = pytesseract.image_to_string(Image.open(d.docfile))
            #print k
            handle = open('data.txt', 'a+')
            handle.write(k)
            handle.close()

            txt_file = r"data.txt"
            csv_file = r'mycsv.csv'

            in_txt = csv.reader(open(txt_file, "rb"), delimiter=' ')
            out_csv = csv.writer(open(csv_file, 'wb'))

            out_csv.writerows(in_txt)

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response('list.html', {
        'documents': documents,
        'form': form
    },
                              context_instance=RequestContext(request))
コード例 #39
0
ファイル: views.py プロジェクト: wang1540/myproject
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)

        if form.is_valid():
            uploaded = request.FILES['docfile']
            #newdoc = Document(docfile = uploaded)
            #newdoc.save()

            if ('.zip' in uploaded.name):
                unzipped = zipfile.ZipFile(uploaded)
                dirlist = []
                for files in unzipped.namelist():
                    if (('.DS_Store' not in files) and ('.' in files)):
                        dir = os.path.dirname(files)
                        if dir not in dirlist:
                            dirlist.append(dir)
                        if not os.path.exists(dir):
                            os.makedirs(dir)
                        outpath = "/Users/xihui/Documents/myproject/myproject/media"
                        unzipped.extract(files, outpath)
                unzipped.close()
                for dir in reversed(dirlist):
                    os.rmdir(dir)
            else:
                newdoc = Document(docfile = uploaded)
                newdoc.save()

            return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'myapp/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
コード例 #40
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()
            dict = {'names': newdoc.docfile.name, 'urls': newdoc.docfile.url}
            return HttpResponse(json.dumps(dict), mimetype="application/json")

    else:
        form = DocumentForm()  # A empty, unbound form

    documents = Document.objects.all()

    return render_to_response('myapp/list.html', {
        'documents': documents,
        'form': form
    },
                              context_instance=RequestContext(request))
コード例 #41
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            if '_googleapiclient' in request.POST:
                print("Google Api Client Test")
                print(googleapiremote("a"))
            elif '_upload' in request.POST:
                newdoc = Document(docfile=request.FILES['docfile'])
                newdoc.save()
                # Redirect to the document list after POST
                return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render(request, 'list.html', {'documents': documents, 'form': form})
コード例 #42
0
ファイル: views.py プロジェクト: squidward/test_project
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()
            dict = {'names':newdoc.docfile.name,
                    'urls': newdoc.docfile.url}
            return  HttpResponse(json.dumps(dict), mimetype="application/json")

    else:
        form = DocumentForm() # A empty, unbound form

    documents = Document.objects.all()

    return render_to_response(
        'myapp/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
コード例 #43
0
ファイル: views.py プロジェクト: changbindu/study
def upload(request):
    # Handle file upload
    response_data = dict()
    response_data['version'] = 0.1
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid() or len(request.FILES) > 0:
            logging.info('looking for upload files')
            for fname in request.FILES:
                logging.info('saving file %s!' % fname)
                newdoc = Document(docfile = request.FILES[fname])
                newdoc.save()
            response_data['success'] = True
            response_data['description'] = 'This is a peony, beautiful!'
        else:
            response_data['success'] = False
            response_data['description'] = 'no image found'
    else:
        response_data['success'] = False
        response_data['description'] = 'please use post method'
    return HttpResponse(json.dumps(response_data), content_type="application/json")
コード例 #44
0
ファイル: views.py プロジェクト: kintautas2/python
def list(request):
    tags = Gallery.objects.filter(username=request.user)
    tagArray = []

    
    while (tags):
        tagArray.append(tags.first().tag)
        tags = tags.exclude(tag=tags.first().tag)

    #choices = Document.objects.order_by().values('tag').distinct()
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            tagSpace = slugify(request.POST.get('tag'))
            if Gallery.objects.filter(username=request.user,tag=tagSpace).exists():
                newdoc = Document(docfile=request.FILES['docfile'],gallery=Gallery.objects.filter(username=request.user,tag=tagSpace).first())
                newdoc.save()
            else:
                newGallery = Gallery(username=request.user,tag=tagSpace,thumb=request.FILES['docfile'])
                newGallery.save()
                newdoc = Document(docfile=request.FILES['docfile'],gallery=newGallery)
                newdoc.save()



            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    galleries = Gallery.objects.all()

    # Render list page with the documents and the form
    return render( 
        request,
        'list.html',
        {'form': form,'galleries':galleries,'tags':tagArray}
    )
コード例 #45
0
ファイル: views.py プロジェクト: stepanevich/match_maker
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            picture = form.save()
            print(picture.docfile)
            file = os.path.join(settings.MEDIA_ROOT, picture.docfile.name)
            
            result = {}
            print ('Extracting features from image %s' % file)
            name = file.split('/')[-1].lower()
            result[name] = extract_features(file)
            picture.features = pickle.dumps(result)
            picture.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render(
        request,
        'list.html',
        {'documents': documents, 'form': form}
    )
コード例 #46
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render(
        request,
        'list.html',
        {'documents': documents, 'form': form}
    )
コード例 #47
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()

            global renders
            renders = net.run('./' + newdoc.docfile.url)
            
            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Render list page with the documents and the form
    return render(
        request,
        'list.html',
        {'renders': renders, 'form': form}
    )
コード例 #48
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()
            # return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm()

    profile = Profile()
    print("X", profile.photo.avatar)
    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render(request, 'list.html', {
        'documents': documents,
        'form': form,
        'profile': profile
    })
コード例 #49
0
ファイル: views.py プロジェクト: harman28/async-uploader
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.docfile = None
            save_document(form.cleaned_data['docfile'], instance)

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
コード例 #50
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])

            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm()  # A empty, unbound form

    #Viewing the graph
    # for document in documents:
    # EmotionAnalysis.printgraph(document.docfile.name)

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render(request, 'list.html', {'documents': documents, 'form': form})
コード例 #51
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            global scale
            scale = form.cleaned_data['scale']
            if scale >120:
                scale = 100
            elif scale <1:
                scale = 1
            newdoc = Document(docfile = request.FILES['docfile'])
            docfile = request.FILES['docfile']
            fn = docfile.name
            newdoc.save()
            global ourl
            global cn
            ourl = merge(fn)
            cn = 1
            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
    else:
        form = DocumentForm() # A empty, unbound form
    
    if cn == 0:
        ourl = 'http://'+SITE_URL+'/media/documents/kotori.png'
    else:
        cn = 0
    # Load documents for the list page
    documents = Document.objects.all()
    # Render list page with the documents and the form
    
    return render_to_response(
        'myapp/list.html',
        {'documents': documents, 'form': form,'ourl':ourl,'scale':scale},
        context_instance=RequestContext(request)
    )
コード例 #52
0
def home(request):
    import os
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()
            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myproject.myapp.views.home'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()
    for document in documents:
        document.docfile.documentName = os.path.basename(document.docfile.name)

    # Render list page with the documents and the form
    return render_to_response('home.html', {
        'documents': documents,
        'form': form
    },
                              context_instance=RequestContext(request))
コード例 #53
0
def uploadFile(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            uploadFilename = "%s.%s" % (uuid.uuid4(), ".html")
            newdoc = open(uploadFilename, "wb")
            data = request.FILES['docfile'];
            newdoc.write(data.read())
            Document(docfile=newdoc)
            newdoc.close()
            request.session["uploadFilename"] = uploadFilename

            return HttpResponseRedirect(reverse('myproject.myapp.views.selectProgram'))
    else:
        form = DocumentForm()  

    documents = '' #Document.objects.all()

    return render_to_response(
        'uploadFile.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
コード例 #54
0
def list(request):
    # Handle file upload
    global processing_instance
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'],uploadtime = calendar.timegm(datetime.now().utctimetuple()))
            newdoc.save()
            # Redirect to the document list after POST
            #return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
            #========it's a processing time!
            ObtPath = os.path.join(settings.MEDIA_ROOT, (str(Document.objects.order_by('-uploadtime')[0].docfile)).replace("/", os.sep)) #get item with the biggest uploadtime
            ObtTime = Document.objects.order_by('-uploadtime')[0].uploadtime 
            processing_instance = FileProcessor(ObtPath, ObtTime)
            readable_time = processing_instance.get_upload_time()
            processing_instance.get_file_contents()
            data_list = processing_instance.get_file_contents_as_string();
            #string_list_copy = copy.deepcopy(data_list)
            #===============================
            #=============it's cleanup time!
                #No, it's not a cleanup time...
            #===============================
            return render_to_response('myapp/list.html', {'documents': [str(ObtPath), str(readable_time), data_list], 'form': form}, context_instance=RequestContext(request))
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    #user does not need to see the list of all documents. 
    #documents = Document.objects.all()
    documents=None
    # Render list page with the documents and the form
    return render_to_response(
        'myapp/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
コード例 #55
0
def list(request):
    # gulby
    results = None
    results2 = None
    model_def = '%s/gulby/uspace3_vgg16_original.prototxt' % caffe_home
    pretrained_model = '%s/gulby/uspace_50_final_add_aug_ft2_8800.caffemodel' % caffe_home
    label_file = '%s/gulby/labels_only_name.txt' % caffe_home
    images_dim = '256,256'
    input_scale = None
    raw_scale = 255.0
    channel_swap = '2,1,0'
    
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            # address
            #print('address : %s' % request.POST['newaddr'])
            db = MySQLdb.connect(host="127.0.0.1", port=3306, user="******", passwd="", db="address")
            db.query("set character_set_connection=utf8;")
            db.query("set character_set_server=utf8;")
            db.query("set character_set_client=utf8;")
            db.query("set character_set_results=utf8;")
            db.query("set character_set_database=utf8;")
            cursor = db.cursor()
            new_addr = request.POST['newaddr'].replace(' ', '')
            query = u"select place_name from place where new_addr like '%s%%'" % new_addr
            #print u"query : %s " % query
            cursor.execute(query.encode('utf8'))
            raw_result = cursor.fetchall()
            results2 = ['%s : %2.2f%%' % (r[0], 0.5/len(raw_result)*100) for r in raw_result[:5]]
            results = {}
            for i, t in enumerate(raw_result[:5]):
                results['top%d' % (i+1)] = (t[0], '%f' % (0.5/len(raw_result)))
            db.close()

            if not results:
                with open('address.log', 'a') as f:
                  f.write(new_addr.encode('utf8'))
                  f.write(u'\n')

            # uspace
            #'''
            if (new_addr.startswith(u'경기도성남시분당구대왕판교로660') or new_addr.startswith(u'경기도성남시분당구대왕판교로670')) and 'docfile' in request.FILES:
                newdoc = Document(docfile=request.FILES['docfile'])
                newdoc.save()
                test_file = newdoc.docfile.name
                image_dims = [int(s) for s in images_dim.split(',')]
                mean = np.ndarray(shape=(3), dtype=float)
                mean[0] = 104
                mean[1] = 117
                mean[2] = 123
                channel_swap = [int(s) for s in channel_swap.split(',')]
                caffe.set_mode_cpu()
                #caffe.set_mode_gpu()
                classifier = caffe.Classifier(model_def, pretrained_model, image_dims=image_dims, mean=mean, input_scale=input_scale, raw_scale=raw_scale, channel_swap=channel_swap)
                np_result = classifier.predict([caffe.io.load_image('%s/%s' % (documents_home, test_file))], True).flatten()
                #print(np_result)
                labels = np.loadtxt(label_file, str, delimiter='\t')
                #print(np_result.argsort()[-1:-6:-1])
    
                results2 = labels[np_result.argsort()[-1:-6:-1]]
                results2 = ['%s : %2.2f%%' % (labels[i], np_result[i]*100/2) for i in np_result.argsort()[-1:-6:-1]]
                results = {}
                for i, t in enumerate(np_result.argsort()[-1:-6:-1]):
                    results['top%d' % (i+1)] = (labels[t], '%f' % (np_result[t]/2))
                
                # Redirect to the document list after POST
                #return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
            #'''

            if request.POST['resulttype'] == 'html':
                return render_to_response(
                    'list.html',
                    {'form': form, 'results': results2},
                    context_instance=RequestContext(request)
                )
            else:
                return JsonResponse(results)
    else:
        form = DocumentForm()  # A empty, unbound form

    # Render list page with the documents and the form
    labels = np.loadtxt(label_file, str, delimiter='\t')
    results = labels
    return render_to_response(
        'list.html',
        {'form': form, 'results': results},
        context_instance=RequestContext(request)
    )
コード例 #56
0
def list(request):
    # Handle file upload!
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST!
            return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
    else:
        form = DocumentForm() # A empty, unbound form!



    # Load documents for the list page!
    documents = Document.objects.all()
    if documents:
        for document in documents:
            print ( document.docfile.url)
            psd =PSDImage.load(os.path.join(os.path.dirname(__file__), "/myproject" + document.docfile.url))
            layer_details = psd.layers
            items = []

            psd_header = psd.header
            try:
                os.makedirs(os.path.join(os.path.dirname(__file__), "/myproject/" + 'media/' + str(document.docfile.name).rsplit('.', 1)[0]))

            except OSError:
                pass
            
            filename = str(document.docfile.name).rsplit('.', 1)[0] + '.json'
            f = open(filename, 'a')



            # save  the flatened image in png format in a directory!
            merged_image = psd.as_PIL()
            merged_image_filename = str(document.docfile.name).rsplit('.', 1)[0] + '.png'
            merged_image.save(os.path.join(os.path.dirname(__file__), "/myproject/" + 'media/' + str(document.docfile.name).rsplit('.', 1)[0] + '/' + merged_image_filename))



            # for loop to extract layer and its information from the psd uploaded
            for layer_count in layer_details:


                # empty dict for storing layer information
                item = {}


                # psd header details viz falana and dekana are extracted here!
                item['psdheader_details'] = psd_header




                # layer names
                item['layer_name'] = layer_count.name




                # convert layer as an image for further processing in future.
                layer_image = layer_count.as_PIL()
                layer_image_filename = str(layer_count.name) + '.png'
                

                # save layer in a paricular directory.
                layer_image.save(os.path.join(os.path.dirname(__file__), "/myproject/" + 'media/' + str(document.docfile.name).rsplit('.', 1)[0] + '/' + layer_image_filename))



            # write layer informations to a jason file.
            f.write(str(items) + '\n')
            f.close()

            #json_data = str(items)
            #return HttpResponse(json.dumps(json_data), content_type="text/json")
   

    # Render list page with the documents and the form.
    return render_to_response(
        'list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
コード例 #57
0
def show(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()
            print newdoc.docfile

            i = Image.open(newdoc.docfile)
            i = i.convert('RGB')
            pix=i.load()
            w=i.size[0]
            h=i.size[1]
            RT = numpy.zeros(w*h)
            BT = numpy.zeros(w*h)
            GT = numpy.zeros(w*h)
            for i in range(h):
                for j in range(w):
                    r,g,b = pix[j,i]
                    RT[i*32 + j] = r
                    GT[i*32 + j] = g
                    BT[i*32 + j] = b

            grayMatrixT = (RT*0.2989+GT*0.5870+BT*0.1140)
            #Normalize
            grayMatrixT -= grayMatrixT.mean()

            dict = unpickle('data_batch_1')
            dt = unpickle('batches.meta')
            print dt
            size = len(dict['data'])
            featureSize = len(dict['data'][0])/3
            grayMatrix = numpy.zeros((size, featureSize))
            normalRGB = numpy.zeros((size, featureSize,3))

            #Compute intensity and normalize
            items = list(dict.items())
            dataItem = items[0]
            labels = numpy.array(dict['labels'])
            print labels
            dataMatrix = numpy.array(dataItem[1])
            R = dataMatrix[:,:1024]
            G = dataMatrix[:,1024:2048]
            B = dataMatrix[:,2048:]
            #Construct original picture
            normalRGB = numpy.rollaxis(numpy.asarray([R,G,B]), 0,3)
            #Construct intensity Array
            grayMatrix = (R*0.2989+G*0.5870+B*0.1140)
            #Normalize
            grayMatrix -= grayMatrix.mean(axis=1)[:, None]

            #Apply PCA
            train(grayMatrix, featureSize, labels, grayMatrixT)

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myproject.myapp.views.show'))
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'myapp/show.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
コード例 #58
0
ファイル: views.py プロジェクト: deepredink/sentilysis
def list(request):
    txt=str(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))))
    txt=txt.replace("/myproject/myapp","/media/")
    txt=txt.replace(" ","")
     
    APIkey="###############################" #Give your HPE Haven on Demand API Key 
 	    
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()
            docfile=request.FILES['docfile']
            
            txt=txt+str(docfile)
            import requests
            url = 'https://api.havenondemand.com/1/api/async/recognizespeech/v1'.format('recognizespeech')
            files = {'file': open(str(txt),'rb')}
            while True:
              r = requests.post(url,data={"apikey":str(APIkey)}, files=files)
              k= r.json()
              try:
            
               jobID= k["jobID"]
               url1="https://api.havenondemand.com/1/job/result/"+jobID
               while True:
                p=requests.post(url1,data={'apikey':str(APIkey)},files=files)
                res=p.json()

                try:
                  content= res["actions"][0]["result"]["document"][0]["content"]
                  
                  d=str(content)

                  urlS='https://api.havenondemand.com/1/api/async/analyzesentiment/v1'
                  files1={'file':d}
                  a= requests.post(urlS,data={"apikey":str(APIkey)},files=files1)
                  l=a.json()
                  jobIDS=l["jobID"]
                  url1S="https://api.havenondemand.com/1/job/result/"+jobIDS
                  pS=requests.post(url1S,data={'apikey':str(APIkey)},files=files1)
                  res1=pS.json()
                  final=(res1["actions"][0]["result"]["aggregate"]["score"])
                  finalp=str(final*100)
                  result1=res1["actions"][0]["result"]["aggregate"]["sentiment"]
                  
                    
                  from django.contrib.staticfiles.templatetags.staticfiles import static

                  url = static('css/bootstrap.css')
                  url1=static('file.txt')
                  y=str(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))))
                  y=y.replace("/myproject/myapp","/static_in_pro/our_static/file.txt")
                  y=y.replace(" ","")
                  f=open(str(y),'w+')
                  f.write(content)
                  f.close()
                  ans=str("""
                  <!DOCTYPE html>
                      <html lang="en">
                      <head>
                          <meta charset="utf-8">
                          <meta http-equiv="X-UA-Compatible" content="IE=edge">
                          <meta name="viewport" content="width=device-width, initial-scale=1">
                          <title>Sentilysis</title>

                          <!-- Bootstrap core CSS -->
                          <link href="""+url+""" rel="stylesheet" type="text/css">
                          <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
                          <script src="https://cdn.rawgit.com/aterrien/jQuery-Knob/master/dist/jquery.knob.min.js"></script>
                          <script type="text/javascript" src="http://yourjavascript.com/36616422911/excanvas.js"></script>
                      </head>
                      <body>
                        <div class="container">
                          <div class="header clearfix">
                            <nav>
                            </nav>
                            <h3 class="text-muted" style="line-height: 40px;">Sentilysis</h3>
                          </div>

                          <div class="jumbotron" style="text-align:center">
                            <div class="row"><h1 style="text-align:center">Sentilysis</h1></div>
                            <div class="row" style="text-align:center">
                                <p style="font-size:20px">Result:"""+result1+"""</p>
                            </div>
                            <div class="row" style="text-align:center">
                                <input type="text" class="dial" value="""+finalp+""" data-min="-100" data-max="100"  ></div> Download the audio file text :<a href="""+url1+""" download="audiotext">
                                <input type="button" value="download" style="margin-top:25px;" ></button></a>
                            </div>
                            <script>
                                $(function() {
                                  $(".dial").knob();
                                });
                            </script>
                            <footer class="footer">
                              <p>&copy; 2016 Deep Red Ink Consulting Pvt. Ltd.</p>
                            </footer>
                          </div> <!-- /container -->
                      </body>
                  </html>""")
                  return HttpResponse(ans)
                  break
                except:
                  continue
              except:
                 continue
            #HPE API
			
            # Redirect to the document list after POST
            #return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
        else:
            form = DocumentForm()  # A empty, unbound form
        
        # Load documents for the list page
        documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
コード例 #59
0
ファイル: views.py プロジェクト: thesivis/SEB
def list(request):
    # Handle file upload
    if request.method == 'POST':
        erro = ''
        form = DocumentForm(request.POST, request.FILES)
        form2 = DocumentForm2(request.POST, request.FILES)
        form3 = DocumentForm3(request.POST, request.FILES)

        if form.is_valid() and form2.is_valid() and form3.is_valid():
            docfile = Document(docfile = request.FILES['docfile'])
            docfile.save()
            #---

            nomeImagem = 'myproject'+docfile.docfile.url
            i = len(nomeImagem)-1
            posPath = 0
            posExt = 0

            while(i > 0):
                if(nomeImagem[i] == '/'):
                    posPath = i
                    break

                if(nomeImagem[i] == '.'):
                    posExt = i

                i = i - 1

            endArquivoImg = nomeImagem[:posPath+1]
            extensaoImg = nomeImagem[posExt:]
            nomeImagem = nomeImagem[posPath+1:]

            #---

            funcfile = Document2(funcfile = request.FILES['funcfile'])
            funcfile.save()

            #---
            nomeFuncao = 'myproject'+funcfile.funcfile.url
            i = len(nomeFuncao)-1
            posPath = 0

            while(i > 0):
                if(nomeFuncao[i] == '/'):
                    posPath = i
                    break

                i = i - 1

            endArquivoFunc = nomeFuncao[:posPath+1]
            nomeFuncao = nomeFuncao[posPath+1:]

            #---

            bandfile = request.FILES['bandfile'].read().split('\n')
            bandfile = bandfile[:len(bandfile)-1]

            #---

            codigo = toPy.analisarETransformar(endArquivoFunc,nomeFuncao)

            if(codigo[0] == False):
                erro = codigo[1]
            else:
                #----------

                auxValPar = ''

                for i in xrange(len(codigo[4])):
                    if(bandfile[i][0] == 'B'):
                        auxValPar = auxValPar + 'bandas['+str(i)+']' + ','
                    else:
                        auxValPar = auxValPar + str(bandfile[i]) + ','

                parametros = auxValPar[:len(auxValPar)-1]

                #----------

                bandas, entrada = imgIO.abrirELer(endArquivoImg,nomeImagem) #mudar depois

                #----------

                retorno = toPy.executar(codigo,bandas,parametros)

                #----------

                terminado = imgIO.salvar(entrada,retorno,codigo[3],endArquivoImg,extensaoImg)

                if(terminado[0] == False):
                    erro = terminado[1]

                    #----------

                erro = "Processo Concluído com Sucesso."

                #----------

            # Redirect to the document list after POST

            form = DocumentForm() # A empty, unbound form
            form2 = DocumentForm2()
            form3 = DocumentForm3()

            try:
                images = os.listdir('myproject/media/imagem/')
            except:
                images = None

            return render_to_response(
            'myapp/list.html',
            {'images': images, 'erro': erro, 'form': form, 'form2' : form2, 'form3' : form3},
            context_instance=RequestContext(request)
            )

            #return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
    else:
        form = DocumentForm() # A empty, unbound form
        form2 = DocumentForm2()
        form3 = DocumentForm3()
        erro = ''

        try:
            images = os.listdir('myproject/media/imagem/')
        except:
            images = None



    # Render list page with the documents and the form
    return render_to_response(
        'myapp/list.html',
        {'images': images, 'erro': erro, 'form': form, 'form2' : form2, 'form3' : form3},
        context_instance=RequestContext(request)
    )