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)
def upload(): if request.method == "GET": return render_template("upload.html") else: image = request.files['image'] new_img = ModelImage(data=image) new_img.save() return redirect("collection")
def post(self): "Upload via a multitype POST message" image_content = self.request.get("img") # always generate a thumbnail for use on the admin page thumb_content = images.resize(self.request.get("img"), 100, 100) if self.request.get('key'): image = db.get(self.request.get("key")) # create the image object else: image = Image() image.user = users.get_current_user() image.title = self.request.get('title') image.image = db.Blob(image_content) # we always store the original here in case of errors # although it's currently not exposed via the frontend image.thumb = db.Blob(thumb_content) # store the image in the datasore image.put() # refresh cache from frontend import get_image for property in ['image', 'thumb']: get_image(str(image.key()), property, force_run=True) # and redirect back to the admin page self.redirect('/')
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()
def get(self, url=''): if url == 'clearpic': pics = Image.all() for pic in pics: pic.delete() self.response.out.write('clear %s' % len(pics)) return if not url.endswith('.jpg'): self.set_status(404) return pic = url[:-4] page = get_img(pic) if page is None: item = get_value('pichost', 'http://pic.caatashoes.com') gourl = '%s/pic/%s' % (item, url) page = self.fetchurl(gourl) if page.status_code != 200: self.set_status(page.status_code) self.setHeader(page) self.response.out.write(page.content) return else: page = page.content put_img(pic, page) self.set_status(200) self.response.headers['content-type'] = 'image/jpeg' self.response.headers['cache-control'] = str(CACHETIME) a = datetime.today() a += timedelta(seconds=31104000) self.response.headers['expires'] = a.strftime('%a, %d %b %Y %X GMT') self.response.headers['accept-ranges'] = 'bytes' self.response.out.write(page)
def get_img(name): query = Image.gql("WHERE name = :name ", name=name) results = query.fetch(1) if len(results) == 0: return None else: return results[0].value
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 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()
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()
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
def parse_images(image_dict): if image_dict is not None: image_id = image_dict[ "imageId"] if "imageId" in image_dict else image_dict["id"] if image_id: image = Image(image_id) image.original_width = image_dict["originalWidth"] image.original_height = image_dict["originalHeight"] # This isn't working. # image.url = u"https://cdn-images-1.medium.com/fit/t/{width}/{height}/{id}" \ # .format(width=image.original_width, # height=image.original_height, # id=image.image_id) return to_dict(image) else: return None
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
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
def add_image(picfile): """ Add a event to the database """ image = Image(filename=picfile) session.add(image) session.commit()
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)
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
def upload_image(): """Process image upload from form""" user_id = session.get('userId') if user_id is None: flash('Login to upload images', 'warning') return redirect('/login') user = User.query.get(int(user_id)) title = request.form.get('title') description = request.form.get('description') if 'image' not in request.files: flash('No image part', 'danger') return redirect('/') image_file = request.files['image'] if image_file.filename == '': flash('No selected image', 'danger') return redirect('/') if not Image.is_allowed_file(image_file.filename): flash('Disallowed file type.', 'danger') return redirect('/') SourceImage.create(image_file, user, title, description) flash('Image uploaded successfully', 'info') # print '-----> /upload -> ', source_image return redirect('/')
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()
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')
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)))
def delete_all_images(): k = ndb.Key('Firm', 'frl') for img in Image.query(ancestor=k).iter(): print img.key.id() for bk in [img.small_blob_key, img.large_blob_key]: if BlobInfo.get(bk): BlobInfo.get(bk).delete() img.key.delete()
def add_image(sender_id, image_url): """Handles adding a image S3 and image url to the database.""" import boto3 import requests s3 = boto3.resource('s3') image = Image(user_id=sender_id, url=image_url, created_at='now') db.session.add(image) db.session.commit() try: image_response = requests.get(image_url) except: pass else: s3.Bucket('acraftybot-test').put_object(Key="{}.jpg".format(image.image_id), Body=image_response.content) image.url=' https://s3-us-west-2.amazonaws.com/acraftybot-test/{}.jpg'.format(image.image_id) db.session.commit() return image
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 delete_all_images(): k = ndb.Key("Firm", "frl") for img in Image.query(ancestor=k).iter(): print img.key.id() for bk in [img.small_blob_key, img.large_blob_key]: if BlobInfo.get(bk): BlobInfo.get(bk).delete() img.key.delete()
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
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
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
def test_image_creation_with_user(self): print '- test_image_creation_with_user' image_file = FileStorage( stream=open('fast_style_transfer/source-images/cape-flattery.jpg')) user = User.query.get(1) image = Image.create(image_file, user) self.assertEqual(image.user_id, 1) self.assertIsInstance(image.user, User) self.assertEqual(image.is_public, user.pref_is_public) print '+ passed'
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
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
def testAddImageToDb(self): it = ImageType(ImageType.TARGET_NONE) it.max_thumb_height = 50 it.max_thumb_width = 150 it.base_dir = 'b/a' it.transform_type = ImageTransform.STD session.add(it) img = Image(it) ret = img.uploadFromFile(fileInTestDir('img/test.jpg')) self.assert_(ret) session.add(img) session.commit() old_thumb_path = img.thumb_path old_image_path = img.image_path self.assert_(os.path.isfile(FileProcess.fullPath(img.thumb_path))) self.assert_(os.path.isfile(FileProcess.fullPath(img.image_path))) split_p = img.thumb_path.split(os.path.sep) self.assert_('b' in split_p) self.assert_('a' in split_p) self.assert_('img' in split_p) split_p = img.image_path.split(os.path.sep) self.assert_('b' in split_p) self.assert_('a' in split_p) self.assert_('img' in split_p) self.assert_(img.thumb_width <= 150) self.assert_(img.thumb_height <= 50) self.assertEquals(img.content_type, ImageInfo.JPEG) self.assertEquals(img.image_width, 418) self.assertEquals(img.image_height, 604) ret = img.uploadFromFile(fileInTestDir('img/test.jpg')) self.assert_(ret) self.assert_(not os.path.isfile(FileProcess.fullPath(old_thumb_path))) self.assert_(not os.path.isfile(FileProcess.fullPath(old_image_path))) session.delete(img) session.delete(it) session.commit()
def hierarchy(): firm_key = ndb.Key("Firm", "frl") projects = dict() for proj in Project.query(ancestor=firm_key): print proj.key.id() projects[proj.key.id()] = proj.to_dict() projects[proj.key.id()]["images"] = [] for img in Image.query(ancestor=firm_key).order(Image.key): print img.key.id() img_d = img.to_dict(exclude=["small_blob_key", "large_blob_key"]) projects[img.key.parent().id()]["images"].append(img_d) print json.dumps(projects)
def chart_directions(): # request the canvas image, the radio button selection, and the title text img_data = request.form.get("img") button_val = request.form.get("buttonVal") title = request.form.get("title") user = g.user user_id = user.id # create a new Image instance in the db image = Image(user_id=user_id, ws_rows=button_val, title=title) model.session.add(image) model.session.commit() model.session.refresh(image) # set the image to a unique filename based on its database id img_filename = image.filename() filepath = "./static/uploads/" + img_filename # decode the canvas image into a png file png_file = open(filepath, "wb") png_file.write(img_data[22:].decode("base64")) png_file.close() return img_filename
def process_hier(): firmid = 'frl' firm_key = ndb.Key('Firm', firmid) projects = dict() for proj in Project.query(ancestor=firm_key): projects[proj.key.id()] = proj.to_dict() projects[proj.key.id()]['images'] = [] for img in Image.query(ancestor=firm_key).order(Image.key): img_d = img.to_dict( exclude=['small_blob_key', 'large_blob_key'] ) projects[img.key.parent().id()]['images'].append( img_d ) fname = '/gs/frl-arch/' + firmid + '/json/proj-detailed.json' wfname = files.gs.create( fname, mime_type='application/javascript', acl='public-read') with files.open(wfname, 'a') as f: f.write( json.dumps(projects) ) files.finalize(wfname)
def get(self): "Responds to GET requets with the admin interface" # query the datastore for images owned by # the current user. You can't see anyone elses images # in the admin images = Image.all() images.filter("user ="******"-date") # we are enforcing loggins so we know we have a user user = users.get_current_user() # we need the logout url for the frontend logout = users.create_logout_url("/") # prepare the context for the template context = { "images": images, "logout": logout, } # calculate the template path path = os.path.join(os.path.dirname(__file__), 'templates', 'index.html') # render the template with the provided context self.response.out.write(template.render(path, context))
page.contents='<h1> Selamat datang di dunia python </h1>' page.is_homepage=True db.session.add(page) db.session.commit() # x1=page.query.filter_by(title='Hallo Dunia').first() # if x1 is None: # page.title='Hallo Dunia' # page.contents='<h1> Hallo Dunia ? apa kabar... </h1>' # page.is_homepage=False # page.url='page/hallo-dunia' # page.image_id=1 # db.session.add(page) # db.session.commit() gbr=Image() x=gbr.query.filter_by(path='beranda.jpeg').first() if x is None: gbr.path='beranda.jpeg' db.session.add(gbr) db.session.commit() role = Role() x=role.query.filter_by(name='admin').first() # db.session.delete(x) # db.session.commit() if x is None : role.name='admin' role.description='admin' db.session.add(role)
print("Update "+shareStr+" Images...") for user in os.listdir(dockletPath+"/images/"+shareStr): print("Update User: "******"/images/"+shareStr+user+"/" files = os.listdir(tmppath) images = [] for file in files: if file[0] == "." or file[-3] != ".": continue images.append(file[:-3]) for img in images: infofile = open(tmppath+"."+img+".info","r") imginfo = infofile.read().split('\n') infofile.close() desfile = open(tmppath+"."+img+".description","r") desinfo = desfile.read() dbimage = Image.query.filter_by(imagename=img,ownername=user).first() if dbimage is None: dbimage = Image(img,False,False,user,desinfo) dbimage.create_time = datetime.strptime(imginfo[0],timeFormat) if shareStr == 'public/': dbimage.hasPublic = True else: dbimage.hasPrivate = True try: db.session.add(dbimage) db.session.commit() except Exception as err: print(err) print("Finished!")
def save_img(): '''Saves user information to database; saves user created image to s3 and filepath url to database''' # Step1: get user information and save it to the database: name = request.form.get('name') company = request.form.get('company') email = request.form.get('email') user = User(name=name, company=company, email=email) user.save() # get current user's id (to use as foreign key in images table) user_id = user.id # Step 2: get user created image and save it: boto.set_stream_logger('boto') # create a connection to s3Connection object s3 = boto.connect_s3() # access secret keys AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] # create new bucket if named bucket does not exist and return exisiting bucket if it already exists bucket = s3.create_bucket('fractal-art') # get dataURL from draw_to_canvas.js and convert from unicode to string # split dataURL and ignore leading 'data:image/png;base64' _, b64data = str(request.form.get('imgData')).split(',') # decode base64 data string ensuring the length is a multiple of 4 bytes decoded_img = decode_img(b64data) path = 'https://s3.amazonaws.com/fractal-art/' # create unique file name for user image filename = str(uuid.uuid4()) + '.png' # create full filepath (a url) for user image fullpath = os.path.join(path, filename) # create a new s3 key/value pair key = bucket.new_key(filename) key.set_contents_from_string(decoded_img) # set access so image will be available for public display key.set_acl('public-read-write') # instantiate instance of Image class img = Image(fullpath, filename, user_id) # save image details to database img.save() # This feature has been removed because gmail has blocked the messages in an effort to prevent "unsolicited mail" # Step 3: send user an email with the image # msg = Message("Great Meeting You at Hackbright Demo Day!", # sender="*****@*****.**", # recipients=[email]) # msg.html = "<p>Hi " + name + "," + "<p> Thanks for chatting with me today! Here is the image we created with \ # <a href = 'https://github.com/sfalkoff/patterns'> Patterns</a> during our conversation. \ # I'm happy to answer any additional questions you may have for me! </p>" + "<img src=" + fullpath + ">" \ # + "<p> Thanks again! <br> Sara <br><br> </p>" # mail.send(msg) return 'successful upload'
def put_img(name, value): item = Image(name=name, value=value) item.put()