Example #1
0
def __process_Document(entry, obj, g):
    full_name = __child_value_by_tags(entry, 'FILE')
    name = path.basename(full_name).decode('utf-8').strip()
    known = Document.objects.filter(docfile=name).exists()

    if not known and not gedcom_storage.exists(name):
        return None

    kind = __child_value_by_tags(entry, 'TYPE')
    if known:
        m = Document.objects.filter(docfile=name).first()
    else:
        m = Document(gedcom=g, kind=kind)
        m.docfile.name = name

    if kind == 'PHOTO':
        try:
            make_thumbnail(name, 'w128h128')
            make_thumbnail(name, 'w640h480')
        except Exception as e:
            print e
            print '  Warning: failed to make or find thumbnail: %s' % name
            return None  # Bail on document creation if thumb fails

    m.save()

    if isinstance(obj, Person) and \
            not m.tagged_people.filter(pointer=obj.pointer).exists():
        m.tagged_people.add(obj)
    elif isinstance(obj, Family) and \
            not m.tagged_families.filter(pointer=obj.pointer).exists():
        m.tagged_families.add(obj)

    return m
Example #2
0
def __process_Document(entry, obj, g):
    full_name = __child_value_by_tags(entry, 'FILE')
    name = path.basename(full_name).decode('utf-8').strip()
    known = Document.objects.filter(docfile=name).exists()

    if not known and not gedcom_storage.exists(name):
        return None

    kind = __child_value_by_tags(entry, 'TYPE')
    if known:
        m = Document.objects.filter(docfile=name).first()
    else:
        m = Document(gedcom=g, kind=kind)
        m.docfile.name = name

    if kind == 'PHOTO':
        try:
            make_thumbnail(name, 'w128h128')
            make_thumbnail(name, 'w640h480')
        except Exception as e:
            print e
            print '  Warning: failed to make or find thumbnail: %s' % name
            return None  # Bail on document creation if thumb fails

    m.save()

    if isinstance(obj, Person) and \
            not m.tagged_people.filter(pointer=obj.pointer).exists():
        m.tagged_people.add(obj)
    elif isinstance(obj, Family) and \
            not m.tagged_families.filter(pointer=obj.pointer).exists():
        m.tagged_families.add(obj)

    return m
Example #3
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(pk=1)
            f = request.FILES['docfile']
            newdoc.docfile = f
            newdoc.name = f.name
            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
    try:
        document = Document.objects.get(pk=1)
    except Document.DoesNotExist:
        document = None

    #update game
    if gameHeart:
        gameHeart.restart()
    # Render list page with the documents and the form
    return render_to_response(
        'list.html',
        {'document': document, 'form': form},
        context_instance=RequestContext(request)
    )
Example #4
0
def create_order():
    user_authenticated_id = get_jwt_identity()
    helper_id = request.form.get('helper_id')
    description = request.form.get('description')

    order = Order(description=description, helper_id=helper_id, status_id=1)
    order.save()

    if os.environ.get('AWS_S3_BUCKET_NAME'):
        files = request.files
        for key in files:
            file = files[key]
            if file:
                url_document = upload_file_to_s3(
                    file, os.environ.get('AWS_S3_BUCKET_NAME'))
                if url_document:
                    document = Document(name=file.filename,
                                        url=url_document,
                                        order=order,
                                        user_id=user_authenticated_id)
                    document.save()
    else:
        print("Faltan las credenciales de AWS")

    DBManager.commitSession()

    orderSerialized = order.serialize()

    if orderSerialized:
        new_order_mail(order.helper, order)
    #Añadir los documentos al objeto
    orderSerialized["documents"] = list(
        map(lambda document: document.serialize(), order.documents))
    return jsonify({"status": "ok", "order": orderSerialized})
Example #5
0
def investing(request):
  # Handle file upload
  file_form = FileForm(request.POST)
  form = DocumentForm(request.POST, request.FILES)
  
  
  if request.method == 'POST' and "uploadFile" in request.POST:
    # Upload
    if form.is_valid():
      newdoc = Document(docfile = request.FILES['docfile'])
      newdoc.save()
  
      # Redirect to the document list after POST
      return HttpResponseRedirect(reverse('dataloader.views.investing'))
  elif request.method == 'POST' and "invest" in request.POST:  
    # Make Investments
    if file_form.is_valid():
      file_name = file_form.cleaned_data['file_input']
      print "### FILE FOR INVESTMENTS: " + file_name
      file_path = settings.MEDIA_ROOT + "/" + file_name
      print file_path
      
      cr = csv.reader(open(file_path))    
      # Starting from second row
      
      for row in cr:
        if row[0] == 'fund' or row[0] == 'individual':
          investment_manager.fund(row)
        elif row[0] == 'buy':
          investment_manager.buy(row)
        elif row[0] == 'sell':
          investment_manager.sell(row)
        elif row[0] == 'sellbuy':
          investment_manager.sellbuy(row)
                        
      
      
      return HttpResponseRedirect(reverse('dataloader.views.investing'))

  elif request.method == 'POST' and "clear" in request.POST:   
    # Clear Investments
    print "### This should clear everything"
    Activity.objects.all().delete()
    StakeHold.objects.all().delete()
    Port_Indi.objects.all().delete()
    print "### OK check porfolio page"
    
    
  else:
      form = DocumentForm() # A empty, unbound form
      file_form = FileForm()

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

  return render_to_response(
       'nav/investing.html',
       {'documents': documents, 'form': form, 'file_form':file_form},
       context_instance=RequestContext(request)
   )
def encode(request):

    if request.method == 'POST' and request.FILES['image']:
        form = Document()
        form.Image = request.FILES['image']
        form.save()
        text = request.POST['data']
        img = Image.open(settings.MEDIA_ROOT + '/' + form.Image.name)
        encoded_file = "enc" + form.Image.name
        img_encoded = encode_image(img, text)

        if img_encoded:
            img_encoded.save(encoded_file)
            print "Message Encoded! "
            os.startfile(encoded_file)
            response = HttpResponse(content_type='application/force-download')
            response[
                'Content-Disposition'] = 'attachment; filename=%s' % smart_str(
                    encoded_file)

        else:
            print "FAIL!!!!!"
        return redirect('home')

    else:
        print "FORM FAIL"
    return render(request, 'send.html')
Example #7
0
def uploadAFile(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        some_file = File(request.FILES['docfile'])

        # import pdb
        # pdb.set_trace()
        # print averageMinuteFileContent
        if form.is_valid():
            path = default_storage.save('averaging.txt',
                                        ContentFile(some_file.read()))

            averageFileName = averaging(path, some_file.name)

            averageMinuteFile = averageFileName + '_minute.csv'
            averageHourFile = averageFileName + '_hour.csv'
            averageDailyFile = averageFileName + '_daily.csv'

            fileHandlerMinute = open(averageMinuteFile, 'rb')
            fileHandlerHour = open(averageHourFile, 'rb')
            fileHandlerDay = open(averageDailyFile, 'rb')

            averageMinuteFileHandle = File(fileHandlerMinute)
            averageHourFileHandle = File(fileHandlerHour)
            averageDayFileHandle = File(fileHandlerDay)

            # print averageMinuteFileHandle.__dict__
            # print some_file.__dict__
            newdoc = Document(
                podId=request.POST['podId'],
                location=request.POST['location'],
                startDate=request.POST['startDate'],
                endDate=request.POST['endDate'],
                podUseType=request.POST['podUseType'],
                pollutantOfInterest=request.POST['pollutantOfInterest'],
                podUseReason=request.POST['podUseReason'],
                projectName=request.POST['projectName'],
                mentorName=request.POST['mentorName'],
                school=request.POST['school'],
                userName=request.user.first_name,
                docfile=some_file,
                averageMinuteFile=averageMinuteFileHandle,
                averageHourFile=averageHourFileHandle,
                averageDayFile=averageDayFileHandle
                # averageMinuteFile=averageMinuteFileHandle
            )

            # print request.FILES['docfile']
            newdoc.save()
            os.remove(averageMinuteFile)
            os.remove(averageHourFile)
            os.remove(averageDailyFile)

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('uploadedFiles'))
    else:
        form = DocumentForm()  # A empty, unbound form
    # Render list page with the documents and the form
    return render(request, 'upload.html', {'form': form})
Example #8
0
def index(request):
    if request.method == "POST":
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()
            question = form.cleaned_data['question']
            renderthis = process(newdoc.docfile.name, question)
            imageurlcontainer = renderthis[0]
            anstemp = renderthis[1]
            anstemp = anstemp.split("\n")
            print anstemp
            ans = anstemp[-2].strip()
            return render(
                request, 'polls/showimg.html', {
                    "imageurlcontainer": imageurlcontainer,
                    "ans": ans,
                    "question": question
                })
        else:
            return HttpResponse("Error brah")
    else:
        system("pwd")
        form = DocumentForm()
        documents = Document.objects.all()
        return render(request, 'polls/index.html', {"form": form})
Example #9
0
def create_order():
    user_authenticated_id = get_jwt_identity()
    helper_id = request.form.get('helper_id')
    description = request.form.get('description')
    long_description = request.form.get('long_description')

    order = Order(description=description,
                  long_description=long_description,
                  helper_id=helper_id,
                  status_id=1)
    order.save()

    documentURL = request.form.get('files')
    if documentURL:
        filename = 'Documents URL'
        document = Document(name=filename,
                            url=documentURL,
                            order=order,
                            user_id=user_authenticated_id)
        document.save()

    DBManager.commitSession()

    orderSerialized = order.serialize()
    if orderSerialized:
        new_order_mail(order.helper, order)
    # Añadir los documentos al objeto
    orderSerialized["documents"] = list(
        map(lambda document: document.serialize(), order.documents))
    return jsonify({"status": "ok", "order": orderSerialized})
Example #10
0
def executeUpload(request):
    # Save the files
    form = DocumentForm(request.POST, request.FILES)
    
    file_new = request.FILES['docfile']
    
    if form.is_valid():
        #Save temporary file
        newdoc = Document(docfile = file_new)
        newdoc.save()
    
        fn = file_new.name
        fn = fn.replace (" ", "_")
    
        #Move the file to the new folder
        src = os.path.join(django_settings.FILE_UPLOAD_TEMP_DIR, 'uploads', fn)
        file_upload = src
        path = os.path.join(request.session['projectPath'],'Uploads')
        target = os.path.join(path, fn)
        if os.path.exists(target):
            os.remove(target)
        shutil.move(src, path)
        
        #Delete the temporary file
        newdoc.delete()
Example #11
0
def executeUpload(request):
    # Save the files
    form = DocumentForm(request.POST, request.FILES)

    file_new = request.FILES['docfile']

    if form.is_valid():
        #Save temporary file
        newdoc = Document(docfile=file_new)
        newdoc.save()

        fn = file_new.name
        fn = fn.replace(" ", "_")

        #Move the file to the new folder
        src = os.path.join(django_settings.FILE_UPLOAD_TEMP_DIR, 'uploads', fn)
        file_upload = src
        path = os.path.join(request.session['projectPath'], 'Uploads')
        target = os.path.join(path, fn)
        if os.path.exists(target):
            os.remove(target)
        shutil.move(src, path)

        #Delete the temporary file
        newdoc.delete()
Example #12
0
def save_video(id):
    user_authenticated_id = get_jwt_identity()
    order = Order.query.get(id)

    if os.environ.get('AWS_S3_BUCKET_NAME'):
        files = request.files
        print("files", files)
        for key in files:

            file = files[key]

            if file:
                url_document = upload_file_to_s3(
                    file, os.environ.get('AWS_S3_BUCKET_NAME'))

                if url_document:
                    document = Document(name=file.filename,
                                        url=url_document,
                                        order=order,
                                        user_id=user_authenticated_id)
                    document.save()
    else:
        print("Faltan las credenciales de AWS")

    DBManager.commitSession()
    order_new_data_mail(order)

    return jsonify(order.serializeForEditView()), 200
Example #13
0
def upload(request):
    name = ""
    if request.method == 'POST' and request.POST.get('search', "") == "":
        context = {}
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newDoc = Document(docfile=request.FILES.get('docfile', ""))
            name = form.cleaned_data['docfile'].name
            newDoc.save()
        documents = Document.objects.all()
        if name != "":
            location = "../media/uploads/" + name
            s = convert_video_to_frame(cwd + "/media/uploads/" + name)
            sorted_inverted = model_to_inverted_index(s)
            print sorted_inverted
            convert_from_mili(sorted_inverted)
            val = 1
            if len(Index.objects.filter()) > 0:
                val = len(Index.objects.filter()) + 1
            b = Index(invertedIndex=json.dumps(sorted_inverted),
                      name=name,
                      video_id=val,
                      images=json.dumps(s))
            vid_id = b.video_id
            b.save()
            return redirect("/video/%s" % vid_id)
        return render(request, 'home.html', context)

    if request.method == 'GET':
        return render(request, 'upload.html')
def cargar_mod(request):

    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.name)
            manejo_mods.insmod('/home/pi/SO2TP3PerezFederico/PaginaTP3/media/'+newdoc.docfile.name)

            archivo = open('salida.txt','r')

            lista = []

            for linea in archivo:
                lista.append(linea)


            return render_to_response(
            'list.html',
            {'documents': lista},
            context_instance=RequestContext(request))

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

    # Render list page with the documents and the form
    return render_to_response(
        'list.html',
        {'form': form},
        context_instance=RequestContext(request)
    )
Example #15
0
def save_document(request_file, content_subdir, related_obj, ashash=True):
    uploadedfile = UploadedFile(request_file)
    file_content = uploadedfile.read()
    doc_obj = Document()
    doc_obj.filehash = md5(file_content).hexdigest()
    doc_obj.urlencfilename = quote(uploadedfile.name)
    doc_obj.filename = uploadedfile.name
    doc_obj.content_type = uploadedfile.file.content_type
    if ashash:
        doc_obj.filepath = settings.BASE_DIR + content_subdir + doc_obj.filehash
    else:
        doc_obj.filepath = settings.BASE_DIR + content_subdir + doc_obj.filename
    if related_obj.__class__.__name__.lower() == "queryset":
        if len(related_obj) == 1:
            setattr(doc_obj, related_obj[0].__class__.__name__.lower(),
                    related_obj[0])
        else:
            print "ERROR: The queryset object had %s elements to it" % str(
                len(related_obj))
    else:
        setattr(doc_obj, related_obj.__class__.__name__.lower(), related_obj)
    doc_obj.save()

    wfile = open(doc_obj.filepath, "w")
    wfile.write(file_content)
    wfile.close()
Example #16
0
 def post(self, request, format=None):
     my_file = request.FILES['file']
     file_name = str(uuid.uuid1())+'.dcm'
     print(file_name)
     with open(file_name, 'wb+') as temp_file:
         temp_file.write(my_file.read())
     print(file_name)
     ds = dicom.read_file(file_name)
     document = Document()
     document.date_time = datetime.datetime.now()
     document.doc_file = request.FILES['file']
     document.save()
     print(document.doc_id)
     for ke in ds.dir():
         if ke == 'PixelData':
             continue
         prop = DICOMProperty()
         prop.prop_key = ke;
         prop.prop_value = str(getattr(ds, ke, ''))
         prop.doc_id = document
         print(prop)
         prop.save()
     print(Document.objects.all())
     documents = Document.objects.all()
     serializer = DocumentListSerializer(documents)
     print(serializer.data)
     #return Response(status=status.HTTP_200_OK, data=serializer.data)
     return HttpResponseRedirect("/static/header.html")
Example #17
0
 def post(self, request, format=None):
     my_file = request.FILES['file']
     file_name = str(uuid.uuid1()) + '.dcm'
     print(file_name)
     with open(file_name, 'wb+') as temp_file:
         temp_file.write(my_file.read())
     print(file_name)
     ds = dicom.read_file(file_name)
     document = Document()
     document.date_time = datetime.datetime.now()
     document.doc_file = request.FILES['file']
     document.save()
     print(document.doc_id)
     for ke in ds.dir():
         if ke == 'PixelData':
             continue
         prop = DICOMProperty()
         prop.prop_key = ke
         prop.prop_value = str(getattr(ds, ke, ''))
         prop.doc_id = document
         print(prop)
         prop.save()
     print(Document.objects.all())
     documents = Document.objects.all()
     serializer = DocumentListSerializer(documents)
     print(serializer.data)
     #return Response(status=status.HTTP_200_OK, data=serializer.data)
     return HttpResponseRedirect("/static/header.html")
Example #18
0
def index(request):
    # Handle file upload
    context = {}
    if request.method == 'POST':
        form = SearchForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                newdoc = Document(docfile=request.FILES['docfile'])
                newdoc.save()
                query = str(newdoc.docfile)
            except:
                query = str(Document.objects.all().order_by('-id')[0].docfile)
            limit = form.cleaned_data['search_limit']
            search_method = form.cleaned_data['search_by']
            distance_model = form.cleaned_data['distance_model']
            if search_method == 'sift':
                results = subprocess.Popen('python sift_feature/search.py -v sift_feature/vocabulary.npy -i sift_feature/index.csv -q media/%s -l %s -d %s' % (query, limit, distance_model), shell=True, stdout=subprocess.PIPE).stdout.read()  # noqa
            else:
                results = subprocess.Popen('python color_feature/search.py -i color_feature/index.csv -q media/%s -l %s -d %s' % (query, limit, distance_model), shell=True, stdout=subprocess.PIPE).stdout.read()  # noqa
            print results
            context['results'] = results.split('\n')[:-1]
            context['query'] = query

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

    context['form'] = form
    # Render list page with the documents and the form
    return render_to_response(
        'index.html',
        context,
        context_instance=RequestContext(request)
    )
Example #19
0
def __process_Document(entry, obj, g):
    name = __valid_document_entry(entry)
    if not name:
        return None

    file_name = 'gedcom/%s' % name
    known = Document.objects.filter(docfile=file_name)

    if len(known) > 0:
        m = known[0]
    else:
        kind = __child_value_by_tags(entry, 'TYPE')
        m = Document(gedcom=g, kind=kind)
        m.docfile.name = file_name
        if kind == 'PHOTO':
            try:
                make_thumbnail(name)
                thumb = path.join('default/thumbs', name)
            except:
                print '  Warning: failed to make or find thumbnail: %s' % name
                return None  # Bail on document creation if thumb fails
        else:
            thumb = None
        if thumb is not None:
            m.thumb.name = thumb
        m.save()

    if isinstance(obj, Person) and \
            not m.tagged_people.filter(pointer=obj.pointer).exists():
        m.tagged_people.add(obj)
    elif isinstance(obj, Family) and \
            not m.tagged_families.filter(pointer=obj.pointer).exists():
        m.tagged_families.add(obj)

    return m
Example #20
0
def upload_document_with_type(request, document_type_id, multiple=True):
    check_permissions(request.user, "documents", [PERMISSION_DOCUMENT_CREATE])

    document_type = get_object_or_404(DocumentType, pk=document_type_id)
    local_form = DocumentForm(prefix="local", initial={"document_type": document_type})
    if USE_STAGING_DIRECTORY:
        staging_form = StagingDocumentForm(prefix="staging", initial={"document_type": document_type})

    if request.method == "POST":
        if "local-submit" in request.POST.keys():
            local_form = DocumentForm(
                request.POST, request.FILES, prefix="local", initial={"document_type": document_type}
            )
            if local_form.is_valid():
                try:
                    if (not UNCOMPRESS_COMPRESSED_LOCAL_FILES) or (
                        UNCOMPRESS_COMPRESSED_LOCAL_FILES
                        and not _handle_zip_file(request, request.FILES["local-file"], document_type)
                    ):
                        instance = local_form.save()
                        _handle_save_document(request, instance, local_form)
                        messages.success(request, _(u"Document uploaded successfully."))
                except Exception, e:
                    messages.error(request, e)

                if multiple:
                    return HttpResponseRedirect(request.get_full_path())
                else:
                    return HttpResponseRedirect(reverse("document_list"))
        elif "staging-submit" in request.POST.keys() and USE_STAGING_DIRECTORY:
            staging_form = StagingDocumentForm(
                request.POST, request.FILES, prefix="staging", initial={"document_type": document_type}
            )
            if staging_form.is_valid():
                try:
                    staging_file = StagingFile.get(staging_form.cleaned_data["staging_file_id"])
                    if (not UNCOMPRESS_COMPRESSED_STAGING_FILES) or (
                        UNCOMPRESS_COMPRESSED_STAGING_FILES
                        and not _handle_zip_file(request, staging_file.upload(), document_type)
                    ):
                        document = Document(file=staging_file.upload(), document_type=document_type)
                        document.save()
                        _handle_save_document(request, document, staging_form)
                        messages.success(
                            request, _(u"Staging file: %s, uploaded successfully.") % staging_file.filename
                        )

                    if DELETE_STAGING_FILE_AFTER_UPLOAD:
                        staging_file.delete()
                        messages.success(request, _(u"Staging file: %s, deleted successfully.") % staging_file.filename)
                except Exception, e:
                    messages.error(request, e)

                if multiple:
                    return HttpResponseRedirect(request.META["HTTP_REFERER"])
                else:
                    return HttpResponseRedirect(reverse("document_list"))
Example #21
0
 def test_model_document(self):
     """Test Document Model"""
     folder = Folder(name='test')
     folder.save()
     obj = Document(title='test', folder=folder)
     obj.save()
     self.assertEquals(folder, obj.folder)
     self.assertNotEquals(obj.id, None)
     obj.delete()
Example #22
0
def create_document(request):
    now = datetime.datetime.now()

    document = Document()
    document['title'] = 'New document for %s'%now.strftime('%d/%m/%Y at %H:%M')
    document['content'] = 'This is a new document created to test our persistence framework'
    document.save()

    return HttpResponseRedirect('/my-documents/')
Example #23
0
def fileuploader(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()
            return HttpResponseRedirect('/docViewer/confirmation/')
    else:
        form = UploadFileForm()
    return render_to_response('fileuploader.html', {'form': form})
Example #24
0
def fileuploader(request):
	if request.method == 'POST':
		form = UploadFileForm(request.POST, request.FILES)
		if form.is_valid():
			newdoc = Document(docfile = request.FILES['docfile'])
			newdoc.save()
			return HttpResponseRedirect('/docViewer/confirmation/')
	else:
		form = UploadFileForm()
	return render_to_response('fileuploader.html', {'form':form})
def save_video(id):
    user_authenticated_id = get_jwt_identity()
    video = request.json.get('video', None)
    order = Order.query.get(id)
    
    document = Document(name="Video", url=video, order=order, user_id=user_authenticated_id)
    document.save()

    DBManager.commitSession()
    return jsonify(order.serializeForEditView()), 200
Example #26
0
def _doc_get_or_create(eid):
	try:
		doc = Document.objects.get(eid=eid)
	except Document.DoesNotExist:
		try:
			doc = Document(eid=eid)
			doc.save()
		except IntegrityError:
			doc = Document.objects.get(eid=eid)
	return doc
Example #27
0
def upload_file(request):
    if not request.user.is_authenticated():
        return HttpResponse('fail unlogin')
    try:
        upload_file = request.FILES['file']
        doc = Document(owner = request.user, public = False, doc_name = upload_file.name, doc_file = upload_file)
        doc.save()
    except:
        return HttpResponse('fail upload fail')
    else:
        return HttpResponseRedirect('/homepage/')
Example #28
0
def new(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        body = request.POST.get('body')

        document = Document(title=title, body=body)
        document.save()

        return redirect('reading:index')

    return render(request, 'reading_assist/new.html', {})
Example #29
0
def suggestions(request, sample_id=1):
    
    try:
        suggestions_doc = Document.objects.get(title="Feature Suggestions")
    except Document.DoesNotExist:
        suggestions_doc = Document()
        suggestions_doc.title = "Feature Suggestions"
        suggestions_doc.save()

    page_context = { }
    page_context["object"] = suggestions_doc
    return render(request, 'suggestions.html', page_context)
Example #30
0
def suggestions(request, sample_id=1):

    try:
        suggestions_doc = Document.objects.get(title="Feature Suggestions")
    except Document.DoesNotExist:
        suggestions_doc = Document()
        suggestions_doc.title = "Feature Suggestions"
        suggestions_doc.save()

    page_context = {}
    page_context["object"] = suggestions_doc
    return render(request, 'suggestions.html', page_context)
Example #31
0
def upload_file(request):
    documents = Document.objects.all()
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(name = request.POST['name'], label = request.POST['label'], docfile = request.FILES['docfile'])
            newdoc.save()
            return redirect('/docs')
    else:
        form = DocumentForm()

    documents = Document.objects.all()
    return render(request, 'network/docs.html', {'documents': documents, 'form': form})
Example #32
0
def add_clue(request):
    if request.method == 'POST':
        newdoc = Document(docfile=request.FILES.get('file', False))
        if newdoc.docfile:
            newdoc.id = str(request.FILES.get('file').name)
            newdoc.save()
            request.session['file'] = newdoc

        return render_to_response(
            'clue.html',
            {'image': request.session.get('file')},
            context_instance=RequestContext(request)
        )
Example #33
0
def create_document(request, name, text, priv=False):
    if request and request.user.is_anonymous():
        priv = False
    logger.info("Creating document " + name + ' in private mode: ' + str(priv))
    document = Document(name=name)
    document.last_change = datetime.datetime.now()
    document.text = text
    document.priv = priv
    document.save()
    if priv == True:
        user = request.user
        user.user_permissions.append(document.to_dbref())
        user.save()
    logger.info("Document created with id: " + str(document.id))
    return document.id
Example #34
0
def build_scenario(project_name, translate=False):
    text_path, my_map, root = build_paths(project_name)
    with open(my_map, 'r') as file:
        dico = json.load(file)
    dico = {**dico, **{k.replace('€', '§'): '§' + v for k, v in dico.items()}}
    document = Document(text_path,
                        project_name,
                        dico=dico,
                        translate=translate)
    tex_filename = '{}.tex'.format(project_name)
    pdf_filename = '{}.pdf'.format(project_name)
    document.save(tex_filename)
    os.system("pdflatex {}".format(tex_filename))
    os.system("mv {} {}".format(pdf_filename, os.path.join(root)))
    os.system("rm *.log *.aux *.tex")
def decode(request):

    if request.method == 'POST' and request.FILES['image']:
        form = Document()
        form.Image = request.FILES['image']
        form.save()
        img = Image.open(settings.MEDIA_ROOT + '/' + form.Image.name)
        hidden_text = decode_image(img)
        messages.info(request, 'The Secret Message is:' + hidden_text)
        print hidden_text
        msg = 'The Secret Message is:' + hidden_text
        return render(request, 'retrieve.html', {"message": msg})
    else:
        print "FORM FAIL"
        return render(request, 'retrieve.html', {"message": ''})
Example #36
0
def upload_document_with_type(request, document_type_id, multiple=True):
    check_permissions(request.user, 'documents', [PERMISSION_DOCUMENT_CREATE])
            
    document_type = get_object_or_404(DocumentType, pk=document_type_id)
    local_form = DocumentForm(prefix='local', initial={'document_type':document_type})
    if USE_STAGING_DIRECTORY:
        staging_form = StagingDocumentForm(prefix='staging', 
            initial={'document_type':document_type})
    
    if request.method == 'POST':
        if 'local-submit' in request.POST.keys():
            local_form = DocumentForm(request.POST, request.FILES,
                prefix='local', initial={'document_type':document_type})
            if local_form.is_valid():
                try:
                    if (not UNCOMPRESS_COMPRESSED_LOCAL_FILES) or (UNCOMPRESS_COMPRESSED_LOCAL_FILES and not _handle_zip_file(request, request.FILES['local-file'], document_type)):
                        instance = local_form.save()
                        _handle_save_document(request, instance, local_form)
                        messages.success(request, _(u'Document uploaded successfully.'))
                except Exception, e:
                    messages.error(request, e)

                if multiple:
                    return HttpResponseRedirect(request.get_full_path())
                else:
                    return HttpResponseRedirect(reverse('document_list'))
        elif 'staging-submit' in request.POST.keys() and USE_STAGING_DIRECTORY:
            staging_form = StagingDocumentForm(request.POST, request.FILES,
                prefix='staging', initial={'document_type':document_type})
            if staging_form.is_valid():
                try:
                    staging_file = StagingFile.get(staging_form.cleaned_data['staging_file_id'])
                    if (not UNCOMPRESS_COMPRESSED_STAGING_FILES) or (UNCOMPRESS_COMPRESSED_STAGING_FILES and not _handle_zip_file(request, staging_file.upload(), document_type)):
                        document = Document(file=staging_file.upload(), document_type=document_type)
                        document.save()
                        _handle_save_document(request, document, staging_form)
                        messages.success(request, _(u'Staging file: %s, uploaded successfully.') % staging_file.filename)
           
                    if DELETE_STAGING_FILE_AFTER_UPLOAD:
                        staging_file.delete()
                        messages.success(request, _(u'Staging file: %s, deleted successfully.') % staging_file.filename)
                except Exception, e:
                    messages.error(request, e)

                if multiple:
                    return HttpResponseRedirect(request.META['HTTP_REFERER'])
                else:
                    return HttpResponseRedirect(reverse('document_list'))                
Example #37
0
def list(request):
    # Handle file upload
    # del request.session['file']
    # Document.objects.all().delete()
    if request.method == 'POST':
        # request.session['file'] = request.FILES.get('file', False)
        newdoc = Document(docfile=request.FILES.get('file', False))
        if newdoc.docfile:
            newdoc.id = str(request.FILES.get('file').name)
            newdoc.save()
            request.session['file'] = newdoc

        # # Redirect to the document list after POST
        matches = get_matches(str(request.FILES.get('file').name))
        if len(matches)>20:
            matches = matches[:20]
        matched_images = []
        matched_image_names = []
        for im_name in matches:
            matched_images.append(Image.objects.get(pk=im_name))
            matched_image_names.append(im_name)

        request.session['matches'] = matched_images
        store_location_information(request, matched_image_names)
        return HttpResponseRedirect(reverse('contextslices.photo.views.search'))


    if request.method == 'GET':
        matched_images = []
        if request.session.get('file'):
            matches = get_matches(request.session.get('file').id)

            if len(matches) > 20:
                matches = matches[:20]
                matched_images = []
                matched_image_names = []
                for im_name in matches:
                    matched_images.append(Image.objects.get(pk=im_name))
                    matched_image_names.append(im_name)
                request.session['matches'] = matched_images
                store_location_information(request, matched_image_names)

        return render_to_response(
            'results.html',
            {'file': request.session.get('file'), 'matches': matched_images, 'num_results': len(matched_images)},
            context_instance=RequestContext(request)
        )
def listdocs(request):
    if request.method == 'GET':
        # retrieve and display all documents
        all_docs = Document.objects.filter(
            user_name=request.user).order_by('doc_ul_date')
        return render_to_response(
            'jobtracker/listdocums.html', {
                'all_docs': all_docs,
                'username': request.user.username
            },
            context_instance=RequestContext(request))

#   posting corresponds to uploading a document
    elif request.method == 'POST':

        # all fields must have been entered
        try:
            newdoc = Document()
            newdoc.doc_descr = request.POST['doc_descr']
            newdoc.doc_type = request.POST['doc_type']
            newdoc.the_doc = request.FILES['the_doc']
            newdoc.doc_mime = request.FILES['the_doc'].content_type

        except:
            # display the error
            all_docs = Document.objects.filter(
                user_name=request.user).order_by('doc_ul_date')
            return render_to_response(
                'jobtracker/listdocums.html', {
                    'all_docs': all_docs,
                    'username': request.user.username,
                    'error_message': "You did not enter all required data"
                },
                context_instance=RequestContext(request))

        else:
            curruser = User.objects.get(username=request.user.username)
            newdoc.user_name = curruser

            newdoc.save()

            all_docs = Document.objects.filter(
                user_name=request.user).order_by('doc_ul_date')
            return redirect('/document/')

    else:
        raise Http404
def upload(request):
    form = DocumentForm()
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            data = form.cleaned_data
            api_key = data['apikey']
            if not os.path.exists(os.path.join(MEDIA_ROOT, api_key)):
                return HttpResponse("Invalid api key.")
            doc = request.FILES['image']
            from django.core.exceptions import ValidationError
            if not doc.content_type.startswith('image'):
                return HttpResponse('Unsupported file extension.')
            newdoc = Document(path=api_key, image=doc)
            newdoc.save()
            return redirect(reverse('upload'))
    return render(request, 'upload.html', {'form': form})
Example #40
0
def _handle_zip_file(request, uploaded_file, document_type):
    filename = getattr(uploaded_file, 'filename', getattr(uploaded_file, 'name', ''))
    if filename.lower().endswith('zip'):
        zfobj = zipfile.ZipFile(uploaded_file)
        for filename in zfobj.namelist():
            if not filename.endswith('/'):
                zip_document = Document(file=SimpleUploadedFile(
                    name=filename, content=zfobj.read(filename)),
                    document_type=document_type)
                zip_document.save()
                _handle_save_document(request, zip_document)
                messages.success(request, _(u'Extracted file: %s, uploaded successfully.') % filename)
        #Signal that uploaded file was a zip file
        return True
    else:
        #Otherwise tell parent to handle file
        return False
Example #41
0
def list_documents(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()
            #try:
            parse_excel(newdoc)
            #except:
            #print "FXCK"
            # Redirect to the document list after POST
            return HttpResponseRedirect(
                reverse('exceltoldap.views.list_documents'))
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list_documents page
    try:
        documents = Document.objects.all()
        last_document = Document.objects.latest('uploaded')
    except:
        last_document = None
    # Render list_documents page with the documents and the form
    places = EpicPlace.objects.all()
    vehicles = EpicVehicle.objects.all()
    users = EpicUser.objects.all()
    dev_places = EpicDevice.objects.exclude(place=None)
    dev_vehicles = EpicDevice.objects.exclude(vehicle=None)
    dev_users = EpicDevice.objects.exclude(owner=None)
    devices = EpicDevice.objects.all()
    mission = last_document.missionName
    return render_to_response('list_documents.html', {
        'documents': documents,
        'last_document': last_document,
        'form': form,
        'places': places,
        'vehicles': vehicles,
        'users': users,
        'devices_places': dev_places,
        'devices_vehicles': dev_vehicles,
        'devices_users': dev_users,
        'devices': devices
    },
                              context_instance=RequestContext(request))
Example #42
0
def _handle_zip_file(request, uploaded_file, document_type):
    filename = getattr(uploaded_file, "filename", getattr(uploaded_file, "name", ""))
    if filename.lower().endswith("zip"):
        zfobj = zipfile.ZipFile(uploaded_file)
        for filename in zfobj.namelist():
            if not filename.endswith("/"):
                zip_document = Document(
                    file=SimpleUploadedFile(name=filename, content=zfobj.read(filename)), document_type=document_type
                )
                zip_document.save()
                _handle_save_document(request, zip_document)
                messages.success(request, _(u"Extracted file: %s, uploaded successfully.") % filename)
        # Signal that uploaded file was a zip file
        return True
    else:
        # Otherwise tell parent to handle file
        return False
Example #43
0
def save_order_files(id):
    user_authenticated_id = get_jwt_identity()
    order = Order.query.get(id)
    body = request.get_json()

    filename = 'Order #' + str(order.id) + ' files'
    document = Document(name=filename,
                        url=body['files'],
                        order=order,
                        user_id=user_authenticated_id)

    document.save()
    DBManager.commitSession()

    order_new_data_mail(order)

    return jsonify(order.serializeForEditView()), 201
Example #44
0
def list(request):
    Data_pre = []
    form = []
    # Handle file upload
    #file_name='heocon'
    if request.method == 'POST':
        file = request.FILES['docfile']
        newdoc = Document(docfile=file.read())
        #print file
        newdoc.save()

        # Redirect to the document list after POST
    else:
        form = DocumentForm()

    can = CandidateMovementModel(file)
    model = can.createCandidateMovementModel()

    test_data = "data/test/sample_test_2.csv"
    file_save = "data/result_prediction.csv"
    predict = CandidateMovementPrediction(model, test_data, file_save)
    data, data_csv = predict.calProbMovementPrediction()
    #
    parsedData = Convert_csv_json(data_csv, 'pretty')
    Data_prediction = json.loads(parsedData)
    #
    #
    #
    #
    for data in Data_prediction:
        userData = {}
        userData['candidate_id'] = data['candidate_id']
        userData['Employer'] = data['Employer']
        userData['Moving'] = data['Moving']
        userData['Predicted'] = data['Predicted']
        Data_pre.append(userData)

    # Load documents for the list page
    documents = Document.objects.all()
    return render(request,
                  'predict/profile.html', {
                      'data': Data_pre,
                      'form': form
                  },
                  context_instance=RequestContext(request))
 def test_transmute(self):
     
     doctype = DocumentType.objects.create(name='transmuted')
     doc = Document(
         document_type = doctype,
     )
     doc.save()
     uf = UploadedFile.transmute_document(
         doc,
         uploader=self.test_user,
     )
     uf.save()
     self.assertEqual(uf.document_ptr_id, doc.id)
     self.assertEqual(uf.document_ptr, doc)
     self.assertEqual(uf.document_type, doc.document_type)
     self.assertEqual(doc.uploadedfile, uf)
     
     self.assertRaises(ValueError, UploadedFile.transmute_document, doc, uploader=self.test_user)
Example #46
0
def list(request):
    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()

    documents = Document.objects.all()

    return render_to_response(
        'uploader/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
Example #47
0
def upload(request):
	# Handle file upload
	if request.method == 'POST':

		username = request.POST['username']
		password = request.POST['password']
		user = authenticate(username=username,password=password)
    	timestampMap = ast.literal_eval(request.POST['timestampMap'])

    	qs = Document.objects.filter(user=user)
    	qs_list = list(qs)
    	for k in request.FILES:

    		whatFilenameWouldBe = str(user)+'/'+k

    		fileFound=False
    		for xx in qs: 
    			fileNameOnSystem = str(xx.docfile.name)
    			if fileNameOnSystem == whatFilenameWouldBe and int(float(timestampMap.get(k))) == xx.timestamp:
    				# File exists, and does not need to be updated
    				# Remove from query set so it does not get deleted
    				qs_list.remove(xx)
    				fileFound = True
    				break
    			elif fileNameOnSystem == whatFilenameWouldBe and int(float(timestampMap.get(k))) > xx.timestamp:
    				xx.docfile.delete()
    				xx.delete()
    				qs_list.remove(xx)
    				actualFile=request.FILES[k]
    				timestamp = int(float(timestampMap.get(k)))


    				newdoc=Document(user=user, timestamp=timestamp,localpath=k,docfile=actualFile)
    				newdoc.save()
    				fileFound=True
    				break
    			

    		if fileFound==False:
    			timestamp=int(float(timestampMap.get(k)))
    			newdoc = Document(user=user, timestamp=timestamp,localpath=k, docfile=request.FILES[k])
    			newdoc.save()
    	logger.info(username + " uploaded files")
    	return HttpResponse("Files uploaded")
Example #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()

            # 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, 'first_app/list.html', {
        'documents': documents,
        'form': form
    })
Example #49
0
def cupload(request):
    print "1"
    from pdfviewer.models import Document
    from django.core.files import File
    print "2"
    import glob
    files= glob.glob("/home/esam/Dropbox/Public/*/*/*/*.pdf")
    print "3"
    print files
    try:
        for pdf in files:
            w=Document()
            print "pdf ",pdf
            #w.pdf_file=open("/home/esam/Downloads/79e4151366c15de4b2 (1).pdf","r")
            w.pdf_file=File(open(pdf))
            w.save()
    except:
        print "error at save file",pdf
    print "saved",pdf
Example #50
0
def index(request):
    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(request.META['HTTP_REFERER'])
    else:
        form = DocumentForm()  # A empty, unbound form

    documents = Document.objects.all()

    template = loader.get_template('prediction/index.html')
    return render(request, 'prediction/index.html', {
        'documents': documents,
        'form': form
    })
Example #51
0
def list(request):
    Data_pre=[]
    form=[]
    # Handle file upload
    #file_name='heocon'
    if request.method == 'POST':
        file=request.FILES['docfile']
        newdoc = Document(docfile=file.read())
        #print file
        newdoc.save()

            # Redirect to the document list after POST
    else:
        form=DocumentForm()


    can = CandidateMovementModel(file)
    model = can.createCandidateMovementModel()


    test_data = "data/test/sample_test_2.csv"
    file_save= "data/result_prediction.csv"
    predict = CandidateMovementPrediction(model,test_data,file_save)
    data,data_csv = predict.calProbMovementPrediction()
    #
    parsedData=Convert_csv_json(data_csv,'pretty')
    Data_prediction=json.loads(parsedData)
    #
    #
    #
    #
    for data in Data_prediction:
        userData={}
        userData['candidate_id'] = data['candidate_id']
        userData['Employer'] = data['Employer']
        userData['Moving'] = data['Moving']
        userData['Predicted'] = data['Predicted']
        Data_pre.append(userData)

    # Load documents for the list page
    documents = Document.objects.all()
    return render(request, 'predict/profile.html', {'data':Data_pre, 'form': form},context_instance=RequestContext(request))
def post_document():
    '''
    post a document for verification
    callers: all users
    '''
    data = request.form.to_dict()

    try:
        err, verified = is_legit(**data)
        if verified:
            document = Document()
            document.deserialize(json=data)
            document.save()
            return json.dumps(document.serialize()), 200
        else:
            return err, 422

    except Exception as e:
        traceback.print_exc()
        return str(e), 500
Example #53
0
def list(request):
    #File upload part
    if request.method == 'POST':
        #print request.FILES['docfile'].size
        #print request.FILES['docfile'].content_type
        #print
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()

            #redirect to document list after POST
            #print reverse('sampleproject.fileupload.views.list')
            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm() #handles empty form
        #load documents for the list page
        documents = Document.objects.all()
        # Render the list page with document and form
        return render(request, 'list.html', {'documents': documents, 'form': form})
Example #54
0
def index(request):
    if request.method == "POST":
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'])
            newdoc.save()
            greyscale = form.cleaned_data['greyscale']
            smoothen = form.cleaned_data['smoothen']
            binarythreshold = form.cleaned_data['binarythreshold']
            resize = form.cleaned_data['resize']
            histogram = form.cleaned_data['histogram']
            edgedetection = form.cleaned_data['edgedetection']
            sobelfilter = form.cleaned_data['sobelfilter']
            foregroundextract = form.cleaned_data['foregroundextract']
            stufftodo = []
            if (greyscale == True):
                stufftodo.append("greyscale")
            if (smoothen == True):
                stufftodo.append("smoothen")
            if (binarythreshold == True):
                stufftodo.append("binarythreshold")
            if (resize == True):
                stufftodo.append("resize")
            if (histogram == True):
                stufftodo.append("histogram")
            if (edgedetection == True):
                stufftodo.append("edgedetection")
            if (sobelfilter == True):
                stufftodo.append("sobelfilter")
            if (foregroundextract == True):
                stufftodo.append("foregroundextract")
            imageurlcontainer = process(request, newdoc.docfile.name,
                                        stufftodo)
            return render(request, 'polls/showimg.html',
                          {"imageurlcontainer": imageurlcontainer})
        else:
            return HttpResponse("Error brah")
    else:
        form = DocumentForm()
        documents = Document.objects.all()
        return render(request, 'polls/index.html', {"form": form})
Example #55
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'],owner=request.user)
            newdoc.save()

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

    # Load documents for the list page
    documents=None
    if request.user.is_active:
        documents = Document.objects.filter(owner=request.user)

    # Render list page with the documents and the form
    return render_to_response('list.html', locals(), context_instance=RequestContext(request)
    )
Example #56
0
def index(request):
	if request.method=="POST":
		form = DocumentForm(request.POST, request.FILES)
		if form.is_valid():
			newdoc = Document(docfile = request.FILES['docfile'])
			newdoc.save()
			greyscale = form.cleaned_data['greyscale']
			smoothen = form.cleaned_data['smoothen']
			binarythreshold = form.cleaned_data['binarythreshold']
			resize = form.cleaned_data['resize']
			histogram = form.cleaned_data['histogram']
			edgedetection = form.cleaned_data['edgedetection']			
			sobelfilter = form.cleaned_data['sobelfilter']			
			foregroundextract = form.cleaned_data['foregroundextract']
			stufftodo=[]
			if(greyscale==True):
				stufftodo.append("greyscale")
			if(smoothen==True):
				stufftodo.append("smoothen")			
			if(binarythreshold==True):
				stufftodo.append("binarythreshold")
			if(resize==True):
				stufftodo.append("resize")
			if(histogram==True):
				stufftodo.append("histogram")
			if(edgedetection==True):
				stufftodo.append("edgedetection")				
			if(sobelfilter==True):
				stufftodo.append("sobelfilter")				
			if(foregroundextract==True):
				stufftodo.append("foregroundextract")				
			imageurlcontainer = process(request,newdoc.docfile.name,stufftodo)		
			return render(request,'polls/showimg.html',{"imageurlcontainer":imageurlcontainer})	
		else:
			return HttpResponse("Error brah")		
	else:
		form = DocumentForm()
		documents = Document.objects.all()				
		return render(request,'polls/index.html',{"form":form})
Example #57
0
def upload_file(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 upload view after POST
            return HttpResponseRedirect('testMongo.testMongo.views.upload_file')
    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(
        'testMongo/upload.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
Example #58
0
def index(request):
    # Handle file upload
    context = {}
    if request.method == "POST":
        form = SearchForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                newdoc = Document(docfile=request.FILES["docfile"])
                newdoc.save()
                query = str(newdoc.docfile)
            except:
                query = str(Document.objects.all().order_by("-id")[0].docfile)
            limit = form.cleaned_data["search_limit"]
            search_method = form.cleaned_data["search_by"]
            distance_model = form.cleaned_data["distance_model"]
            if search_method == "sift":
                results = subprocess.Popen(
                    "python sift_feature/search.py -v sift_feature/vocabulary.npy -i sift_feature/index.csv -q media/%s -l %s -d %s"
                    % (query, limit, distance_model),
                    shell=True,
                    stdout=subprocess.PIPE,
                ).stdout.read()  # noqa
            else:
                results = subprocess.Popen(
                    "python color_feature/search.py -i color_feature/index.csv -q media/%s -l %s -d %s"
                    % (query, limit, distance_model),
                    shell=True,
                    stdout=subprocess.PIPE,
                ).stdout.read()  # noqa
            print results
            context["results"] = results.split("\n")[:-1]
            context["query"] = query

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

    context["form"] = form
    # Render list page with the documents and the form
    return render_to_response("index.html", context, context_instance=RequestContext(request))
Example #59
0
def add_file(request, chat_id):
	if request.method == 'POST':
		form = DocumentForm(request.POST, request.FILES)
		if form.is_valid():
			try:
				chat = Chat.objects.get(id = chat_id)
				newdoc = Document(docfile = request.FILES['docfile'])
				newdoc.save()
				text = newdoc.docfile
				message = Message(
					chat_id = chat,
					user_id = request.user,
					message = text,
					post_time = timezone.now(),
					_type = 3,
					)
				message.save()
				return HttpResponse(request.FILES['docfile'].name)
			except:
				return HttpResponse('bad')
	else:
		form = DocumentForm()
		return render(request, 'add_file.html', {'form': form } )