Esempio n. 1
0
def index():
    form = URLForm()
    timg = Image(False, "", "", "")
    botError = BotError(False, "")
    if form.validate_on_submit():

        url = form.query.data

        try:
            # resize image to 32x32 pixel image
            procImage = allcnn_predict.processImage(url)
            # transform to 32,32,3 matrix, feed to model
            category, prob = allcnn_predict.predictImage(procImage)

            timg = Image(True, url, category, prob)
            timg.toString()
        except ValueError as e:
            print(e)
            botError = BotError(True, e)
        except urllib.error.HTTPError as e:
            print(e.msg)
            botError = BotError(True, e.msg)

        return render_template("index.html",
                               title='VisionBot',
                               form=form,
                               botError=botError,
                               image=timg)

    return render_template("index.html",
                           title='VisionBot',
                           form=form,
                           botError=botError,
                           image=timg)
Esempio n. 2
0
def article_add_confirm():
	# print(request.files)
	user_id = session["current_user"]
	type_id=request.form.get("type_id")
	image_file_1=request.files.get("image")
	image_file_2=request.files.get("image_2")
	image_file_3=request.files.get("image_3")
	image_file_4=request.files.get("image_4")
	size=request.form.get("size")
	color=request.form.get("color")
	material=request.form.get("material")
	notes=request.form.get("notes")
	is_private=request.form.get("is_private")
	is_loanable=request.form.get("is_loanable")
	is_giveaway=request.form.get("is_giveaway")

	bool_convert = {"True": True, "False": False}
	article = Article(
				owner_id=user_id,
				type_id=type_id,
				size=size,
				color=color,
				material=material,
				notes=notes,
				is_private=bool_convert[is_private],
				is_loanable=bool_convert[is_loanable],
				is_giveaway=bool_convert[is_giveaway]
				)

	#check if images are there
	img_1 = upload_to_s3(image_file_1)
	image = Image (img_url=img_1)
	article.images.append(image)
	
	#check if images exist and if yes add them to the database
	img_in_form = [image_file_2, image_file_3, image_file_4]
	for img_file in img_in_form:
		if img_file != None:
			img = upload_to_s3(img_file)
			image = Image (img_url=img)
			article.images.append(image)

	
	db.session.add(article)
	db.session.commit()
	
	flash('New article added.')
	return redirect('/my_closet')
 def scryfall_cards_crawl(self, context):
     local_session = Session()
     futur_cards = scryfall.get_futur_cards()
     for futur_card in futur_cards:
         if not futur_card.get("id") in self.scryfall_futur_cards_id:
             config.bot_logger.info(
                 f"New card detected from scryfall: {futur_card.get('name')}"
             )
             # New card detected, add it to scryfall list
             self.scryfall_futur_cards_id.append(futur_card.get("id"))
             # Try to see if it has already been spoiled
             for i_url in scryfall.get_image_urls(futur_card):
                 im = Image(location=i_url,
                            descr=im_utils.descript_image(i_url))
                 if not self.sd.is_duplicate(
                         im, [s.image.descr for s in self.spoiled]):
                     # card not recognize as a duplicate, save then publish it
                     local_session.add(im)
                     sp = Spoiler(url=scryfall.get_card_url(futur_card),
                                  source=SpoilerSource.SCRYFALL.value,
                                  source_id=futur_card.get("id"),
                                  found_at=datetime.now(),
                                  set_code=futur_card.get("set_code", None))
                     sp.image = im
                     local_session.add(sp)
                     self.spoiled.append(sp)
                     sp.set = local_session.query(Set).filter(
                         Set.code == futur_card.get("set_code")).first()
                     self.send_spoiler(sp, context)
     local_session.commit()
Esempio n. 4
0
def add_image_to_db(image_url):
    """Add images from static folder to the database."""

    image = Image(image_url=image_url)

    db.session.add(image)
    db.session.commit()
 def mythicspoiler_crawl(self, context):
     local_session = Session()
     cards = self.ms.get_cards_from_news()
     for page, image_url, card_set in cards:
         if image_url not in self.mythicspoiler_futur_cards_url:
             config.bot_logger.info(
                 f"New card detected from mythicspoiler: {page}")
             # New card detected on mythic spoiler, save it
             self.mythicspoiler_futur_cards_url.append(image_url)
             # Try to see if it has already been spoiled
             im = Image(location=image_url,
                        descr=im_utils.descript_image(image_url))
             if not self.sd.is_duplicate(
                     im, [s.image.descr for s in self.spoiled]):
                 # card not recognize as a duplicate, save then publish it
                 local_session.add(im)
                 sp = Spoiler(url=page,
                              source=SpoilerSource.MYTHICSPOILER.value,
                              source_id=SpoilerSource.MYTHICSPOILER.value,
                              found_at=datetime.now(),
                              set_code=card_set)
                 sp.image = im
                 sp.set = local_session.query(Set).filter(
                     Set.code == card_set).first()
                 local_session.add(sp)
                 self.spoiled.append(sp)
                 self.send_spoiler(sp, context)
     local_session.commit()
Esempio n. 6
0
def create_image(title, url_path, uuid, width, height, file_size, date_added,
                 status):
    """Create images"""
    if height == width:
        shape = "square"
    elif height > width:
        shape = "portrait"
    else:
        shape = "landscape"

    mp_size = round(((int(height) * int(width)) / 1000000), 2)

    image = Image(title=title,
                  url_path=url_path,
                  uuid=uuid,
                  width=width,
                  height=height,
                  file_size=file_size,
                  date_added=date_added,
                  status=status,
                  shape=shape,
                  mp_size=mp_size)
    db.session.add(image)
    db.session.commit()

    return image
Esempio n. 7
0
def add_image(image_name, neighborhood_id):
    """Add image and its neighborhood_id to db"""

    image = Image(image_name=image_name, neighborhood_id=neighborhood_id)

    db.session.add(image)
    db.session.commit()
Esempio n. 8
0
def convert_resize_image(img_url, privacy):
    """Convert image to greyscale and resize before adding to db"""
    baseheight = 720
    img = PILimage.open(img_url).convert('L')
    height_percent = (baseheight / float(img.size[1]))
    width_size = int((float(img.size[0]) * float(height_percent)))
    #If image is over 480px in width after scaling, crop width to 480px
    if width_size > 480:
        width_size = 480
    img = img.resize((width_size, baseheight), PILimage.ANTIALIAS)
    img.save(img_url)

    if privacy == 'private':
        private = True
    else:
        private = False

    if 'user_id' in session:
        user_id = session['user_id']
    else:
        user_id = None

    # Check if img_url in database, if not, add image to table
    db_img = Image.query.filter(Image.img_url == img_url).first()
    if not db_img:
        new_img = Image(img_url=img_url,
                        user_id=user_id,
                        private=private)
        db.session.add(new_img)
        db.session.commit()
        return new_img
    else:
        return db_img
Esempio n. 9
0
 def task_link(self, grab, task):
     for image in grab.doc.select('//img'):
         try:
             if (self.result_counter >= self.total):
                 self.result_status = 'success'
                 self.info = 'All images grabbed'
                 self.request_item.status = self.result_status
                 self.request_item.info = self.info
                 db.session.commit()
                 with app.app_context():
                     socketio.emit('finish', 'finish', namespace='/main')
                 eventlet.sleep(0)
                 self.stop()
                 return
             src = image.attr('src')
             res = urllib.urlopen(src)
             http_message = res.info()
             if self.image_type != 'all' and self.image_type != http_message.type:
                 continue
             hash = os.urandom(16).encode('hex')
             filename = hash + src.split('/')[-1]
             self.downloader.retrieve(src, 'app/static/images/' + filename)
             self.result_counter += 1
             image_item = Image(self.request_item, src, filename)
             db.session.add(image_item)
             with app.app_context():
                 socketio.emit('grabed_count',
                               self.result_counter,
                               namespace='/main')
             eventlet.sleep(0)
         except Exception as e:
             continue
Esempio n. 10
0
    def test_product_type(self):
        image_url = """https://images.asos-media.com/products/"""
        """vestido-largo-y-plisado-de-dama-de-honor-en-rosa-exclusivo-de-tfnc/"""
        """13955198-2?$XXL$&wid=513&fit=constrain"""
        product_url = """https://www.asos.com/es/tfnc/"""
        """vestido-largo-y-plisado-de-dama-de-honor-en-rosa-exclusivo-de-tfnc/"""
        """prd/13955198?clr=rosa&colourWayId=16579390&SearchQuery=&cid=17245"""
        description = "Vestido largo y plisado de dama de honor en rosa exclusivo de TFNC"
        images = [Image(url=image_url) for x in range(5)]  # 5 fake images
        product = Product(uid="sku1000",
                          images=images,
                          gender="female",
                          product_url=product_url,
                          price=82.99,
                          category="dress",
                          size="M",
                          description=description)

        self.assertTrue(hasattr(product, "uid"))
        self.assertTrue(hasattr(product, "images"))
        self.assertTrue(hasattr(product, "gender"))
        self.assertTrue(hasattr(product, "product_url"))
        self.assertTrue(hasattr(product, "price"))
        self.assertTrue(hasattr(product, "size"))
        self.assertTrue(hasattr(product, "category"))
        self.assertTrue(hasattr(product, "description"))

        self.assertIsInstance(product.images, list)
        self.assertIsInstance(product.gender, str)
        self.assertIsInstance(product.product_url, str)
        self.assertIsInstance(product.price, float)
        self.assertIsInstance(product.size, str)
        self.assertIsInstance(product.category, str)
        self.assertIsInstance(product.description, str)
Esempio n. 11
0
def process_canvas():
    """Convert and Analyze image from Canvas, add to DB"""
    img = request.files['myFileName']
    privacy = request.form["privacy"]

    if 'user_id' in session:
        user_id = session['user_id']
    else:
        user_id = None

    # Add DB record with dummy URL
    new_img_record = Image(user_id=user_id,
                           img_url="")
    db.session.add(new_img_record)
    db.session.commit()
    # Set the filename
    new_img_id = new_img_record.img_id
    filename = "image_" + str(new_img_id) + '.jpg'
    img_path = UPLOAD_FOLDER + filename
    # Save img to folder
    img.save(img_path)
    # Update DB with real URL
    new_img_record.img_url = img_path
    db.session.commit()
    # Convert and Resize Image and Analyze Pixels
    upload = convert_resize_image(img_path, privacy)
    img_id = upload.img_id
    img_url = upload.img_url
    results = {"id": img_id, "url": img_url}
    pillow_analyze_image(img_path)

    # Return results
    return jsonify(results)
Esempio n. 12
0
 def get(self, image_id):
     try:
         return Image(image_id,
                      open(os.path.join(self.directory, image_id)).read())
     except IOError:
         logger.warn('Unable to open image')
         return None
Esempio n. 13
0
def add_image(picfile):
	"""
	Add a event to the database
	"""
	image = Image(filename=picfile)
	session.add(image)
	session.commit()
Esempio n. 14
0
def load_images():
    """Load images from image_test_data into database."""

    print "Images"

    for i, row in enumerate(open("seed_data/image_id_and_label.csv")):
        row = row.rstrip()
        image_id, label = row.split(",")
        image_id = image_id.strip()

        try:
           image_id = int(image_id)
        except ValueError:
           pass      # or whatever

        image = Image(id=image_id,
                    image_label=label)

        # We need to add to the session or it won't ever be stored
        db.session.add(image)

        # provide some sense of progress
        if i % 100 == 0:
            print i

    # Once we're done, we should commit our work
    db.session.commit()
Esempio n. 15
0
def report_lost():
    """adds new item to losts"""

    title = request.form.get('title')
    description = request.form.get('description')
    location = request.form.get('location')
    reward = request.form.get('reward')

    print(reward)

    if not reward or reward == 'undefined':
        reward = None

    geocoding_info = get_geocoding(location)

    location_id = get_location_id(geocoding_info['lat'], geocoding_info['lng'])

    if not location_id:
        new_location = Location(address1=geocoding_info['street'],
                                city=geocoding_info['city'],
                                zipcode=geocoding_info['zipcode'],
                                state=geocoding_info['state'],
                                lat=geocoding_info['lat'],
                                lng=geocoding_info['lng'])

        db.session.add(new_location)

        # location_id = get_location_id(lat, lng)
        db.session.flush()
        location_id = new_location.location_id

    #add item to found database
    new_lost = Lost(title=title,
                    description=description,
                    location_id=location_id,
                    user_id=session['user_id'],
                    time=datetime.now(),
                    reward=reward)
    db.session.add(new_lost)

    db.session.flush()

    new_lost_id = new_lost.lost_id

    #if an image was uploaded, store it in the database
    if 'file' in request.files:
        file = request.files['file']

        img_name = 'l' + str(new_lost_id) + file.filename

        new_image = Image(img_name=img_name,
                          img_data=file.read(),
                          lost_id=new_lost_id)

        db.session.add(new_image)

    db.session.commit()

    return redirect('/lost')
Esempio n. 16
0
def create_image(image_url, owner, permission="PRIVATE"):
    """Create and return a new image."""

    image = Image(image_url=image_url, owner=owner, permission=permission)

    db.session.add(image)
    db.session.commit()
    return image
def create_image(name, path, for_user, published=False):
    image = Image(name=name,
                  s3_path=path,
                  user_id=for_user,
                  published=published)
    db.session.add(image)
    db.session.commit()
    return image
Esempio n. 18
0
 def test_image_type(self):
     image_url = """https://images.asos-media.com/products/"""
     """vestido-largo-y-plisado-de-dama-de-honor-en-rosa-exclusivo-de-tfnc/"""
     """13955198-2?$XXL$&wid=513&fit=constrain"""
     for etag in ["xx", None]:
         image = Image(url=image_url, etag=etag)
         self.assertTrue(hasattr(image, "etag"))
         self.assertIsInstance(image.etag, (str, type(None)))
Esempio n. 19
0
def create_image(image_filename, image_description, image_url):
    """Create new image to be stored"""

    image = Image(image_filename=image_filename,
                  image_description=image_description,
                  image_url=image_url)

    db.session.add(image)
    db.session.commit()
def save_image_to_db(filename, user_id):
    """Save image to databade"""

    s3_path = f"https://shopifyimagerepository.s3-us-west-1.amazonaws.com/{filename}"

    image = Image(user_id=user_id, name=filename, s3_path=s3_path)
    db.session.add(image)
    db.session.commit()
    return image.image_id
Esempio n. 21
0
def create_image(image_url):
    """Create and return a new image."""

    image = Image(image_url=image_url)

    db.session.add(image)
    db.session.commit()

    return image
Esempio n. 22
0
def load_example_images():
	"""Load a few example images into the database."""

	print("Images")

	Image.query.delete()

	images = [
    	Image(filesize=800, xdim=1200, ydim=1080, imgtype='jpg', uploaded=datetime.datetime.now(), url='https://res.cloudinary.com/demo/image/upload/Sample.jpg'),
    	Image(filesize=400, xdim=300, ydim=200, imgtype='jpg', uploaded=datetime.datetime.now(), url='http://cdn3.craftsy.com/blog/wp-content/uploads/2015/03/Coneflower.png'),
    	Image(filesize=1000, xdim=1600, ydim=1280, imgtype='png', uploaded=datetime.datetime.now(), url='https://winblogs.azureedge.net/devices/2012/09/808sample.jpg'),
	    Image(filesize=600, xdim=800, ydim=600, imgtype='jpg', uploaded=datetime.datetime.now(), url='http://a4.pbase.com/g9/34/632434/2/150123376.gdGIYwbh.jpg')
	]

	for image in images:
		db.session.add(image)
		db.session.flush()

	db.session.commit()
Esempio n. 23
0
def create_image(user_id, image_title, artist, location, image_url):
    """Creates and returns image"""
    image = Image(user_id=user_id,
                  image_title=image_title,
                  artist=artist,
                  location=location,
                  image_url=image_url)
    db.session.add(image)
    db.session.commit()
    return image
Esempio n. 24
0
 def get(self, image_id):
     sql = "SELECT * FROM images WHERE name=%s"
     with self.get_cursor() as cur:
         cur.execute(sql, (image_id, ))
         if cur.rowcount < 1:
             return None
         else:
             row = cur.fetchone()
             img = Image(row['name'], bytes(row['payload']))
             return img
Esempio n. 25
0
def create_image(image_name, image_description, image_url):
    """Creates new image in database to add to library"""

    image = Image(image_name=image_name,
                  image_description=image_description, image_url=image_url)

    db.session.add(image)
    db.session.commit()

    return image
Esempio n. 26
0
def load_popos():
    """Load Privately-Owned Public Open Space (POPOS) data from popos.csv into database."""

    print "Privately-Owned Public Open Space"

    # Read popos.csv file and parse data
    for row in open("seed_data/popos.csv"):
        row = row.rstrip()

        name, address, latitude, longitude, subj, popos_type = row.split(
            ",")[1:7]
        # restroom, description, seats, hours_type, mapid = row.split(",")[-5:]
        # seating = row.split(",")[14]

        # if name != address:
        #     name = '\n'.join([name, address])

        # if restroom != 'Y':
        #     restroom = 'N'

        image_url = get_image(name, latitude, longitude, address)
        # print name, image_url

        park = Park(park_type='popos',
                    name=name,
                    latitude=float(latitude),
                    longitude=float(longitude))

        # Add popos data to the parks db session & commit session to db
        db.session.add(park)
        db.session.commit()

        popos = Popos(park_id=park.park_id,
                      address=address,
                      popos_type=popos_type)

        # TODO: add additional POPOS info
        # restroom=restroom,
        # description=description,
        # seating=seating.capitalize(),
        # hours=hours_type.capitalize()

        # Add popos data to the popos db session & commit session to db
        db.session.add(popos)
        db.session.commit()

        image = Image(img_park_id=park.park_id, image_url=image_url)

        # Add image_url to the image db session & commit session to db
        db.session.add(image)
        db.session.commit()

    print "Committed to DB"
Esempio n. 27
0
def post_project_db_update(project, notes, status, image, user, progress):
    """ update a project in the db and ravelry site """

    project.notes = notes
    project.progress = progress
    if status:
        project.status_id = int(status)
    project.updated_at = datetime.datetime.now()
    if image:
        photo = Image(url=image, project_id=project.project_id)
        db.session.add(photo)
    db.session.commit()
Esempio n. 28
0
def load_image(valid_exercises_id_list):
    image_result_list = call_api('exerciseimage')
    for result_dict in image_result_list:
        exercise_image = result_dict['image']
        exercise_id = result_dict['exercise']

        if exercise_id not in valid_exercises_id_list:
            continue

        image = Image(image_link=exercise_image, exercise_id=exercise_id)
        db.session.add(image)
    db.session.commit()
Esempio n. 29
0
def create_image(user_id, image_name, tag1, tag2, tag3):
    """Create an Image object."""

    image = Image(user_id=user_id,
                  image_name=image_name,
                  tag1=tag1,
                  tag2=tag2,
                  tag3=tag3)

    db.session.add(image)
    db.session.commit()

    return image
Esempio n. 30
0
def add_video_process():
    """add video link"""
    album_name = request.form.get("Videoname")
    image = request.form.get("Videolink")
    profile = get_profile()
    new_video = Image(album_name=album_name,
                      image=image,
                      profile_id=profile.profile_id,
                      image_type="video")
    db.session.add(new_video)
    db.session.commit()

    return redirect("/videos")