def upload(userid): user = User.objects(id=userid).first() image = request.files.get("image") if image: if not image.filename.endswith(tuple([".jpg", ".png"])): return jsonify({"error": "Image is not valid"}), 409 # Generate random filename filename = str(uuid.uuid4()).replace("-", "") + "." + image.filename.split(".")[-1] if not os.path.isdir(config.image_upload_folder): os.makedirs(config.image_upload_folder) image.save(os.path.join(config.image_upload_folder, filename)) img = Img( url=filename, user=user ).save() else: filename = None return jsonify({ "message": 'OK', "data": img.to_public_json() })
async def upgrade_db(self, iniciator): from models import Img processed = 0 imgs = Img.where_null('resource_id').order_by_raw('RAND()').limit( 5).get() while imgs and processed < 100: await self.send_media_group(imgs, iniciator) processed += len(imgs) await asyncio.sleep(2.5) imgs = Img.where_null('resource_id').order_by_raw('RAND()').limit( 5).get() return processed
def saves_the_checked_file_to_database(sent_file): """Сохраняет проверенный файл в базу данных, парсит данные в json, дополнительно выполняя проверку имени файла, присваивает файлу уникальное имя и возвращает ответ в json формате""" sent_filename = sent_file.filename path_to_picture = os.path.join(app.config['UPLOAD_FOLDER'], sent_filename) picture_name = secure_filename(str(sent_filename)) file_data = Img(picture_name=picture_name, path_to_picture=path_to_picture) try: database.session.add(file_data) database.session.commit() image_database = Img.query.order_by(Img.date).all() with open('parse database/image_database.json', 'w') as image_base_to_json: json.dump(str(image_database), image_base_to_json, indent=-2, ensure_ascii=False) response = jsonify({'result': 'success', 'filename': sent_filename, 'id': file_data.image_id, 'description': 'the file is saved and ready for processing'}) return response, 202 except Exception: response = jsonify({'result': 'error', 'description': 'error adding to database'}) return response, 499
def upload_image(): if request.method == "POST": if request.files: image = request.files["image"] if not image: print("No image uploaded") return redirect('/') mimetype = image.mimetype if not mimetype: print("Bad mimetype!") return redirect('/') if image.filename == "": print("Image must have a filename") return redirect('/') if not allowed_image(image.filename): print("That image extension is not allowed") return redirect('/') else: filename = secure_filename(image.filename) image.save(os.path.join(app.config["IMAGE_UPLOADS"], filename)) image = Img(name=filename, mimetype=mimetype) db.session.add(image) db.session.commit() print("Image saved") return redirect('/') return render_template("form.html")
def create(): if request.method == 'POST': img_form = request.files['filename'] # get form filename if img_form: filename = str(time.time()) + "_" + secure_filename( img_form.filename) # change filename times = datetime.datetime.now().strftime( "%d-%m-%y %H:%M") # get current time upload_result = upload(img_form) # upload image to cloudinary response = requests.get( upload_result['url']) # get image url from upload result img_file = Image.open(io.BytesIO( response.content)) # get image from cloudinary text = pytesseract.image_to_string( img_file) # convert image to text try: # save to postgres res = Img(path=upload_result['url'], description=text, created_at=times) db.session.add(res) db.session.commit() # return jsonify( status = 'OK', # msg = 'Saved', # error = None # ), 201 return render_template('upload.html') except Exception as e: return (str(e)) return render_template('upload.html') return render_template('upload.html')
def make_collage(self): l_margin = pinproperties.L_MARGIN.value v_gap = pinproperties.V_GAP.value h_gap = pinproperties.H_GAP.value header_font_size = pinproperties.HEADER_FONT_SIZE.value t_margin = int(header_font_size / 2.3) pinproperties.T_MARGIN._value_ = t_margin ImageProcess.calculation_img_prop(self.imgs) img_grp = Pin.img_matrix(all_imgs=self.imgs, matrix_dim=self.matrix_dim) pin_width, pin_height = self.pin_size_calculation( img_grp, header_font_size=header_font_size) pin_img = Img.make_blank_img(img_size=(pin_width, pin_height), folder_path='/tmp/', color=(255, 255, 255)) txt_img = Img.make_blank_img(img_size=(pin_width, pin_height), folder_path='/tmp/', transparent=True) header_max_height = self.write_heading_to_pin( txt_img, fontsize=header_font_size, top_margin=t_margin, font_index=Pin.font_index) y_next = getattr(self, "start_p") print("start_p", y_next) for grp in img_grp: x_next = l_margin for im in grp.img_grp: img = im.thumbnail_img pin_img.merge_imgs(img, pin_loc=(x_next, y_next)) y_text = y_next + grp.max[1] + h_gap if pinproperties.WRITE_TXT.value: img.txt.draw_text(img=txt_img, color=pinproperties.FONT_COLOR.value, loc=(x_next, y_text)) x_next = x_next + v_gap + img.width y_next += grp.max[1] + grp.max_grp_txt_height( grp.img_grp) + v_gap * 2 pin_img.obj = pin_img.obj.convert('RGBA') blend_image: Img = pin_img.blend_imgs(txt_img) blend_image.write_img() return blend_image
def add_img(request): user = request.user state = None if request.method == 'POST': try: new_img = Img( name=request.POST.get('name', ''), description=request.POST.get('description', ''), img=request.FILES.get('img', ''), book=Book.objects.get(pk=request.POST.get('book', '')) ) new_img.save() except Exception, e: state = 'error' print e else: state = 'success'
def my_blob(self, img): loc = img.find('http:') if loc < 0 or loc > 6: if img[0] != '/': img = '%s/1%s' % (self.url, img) else: #img = '%s%s' % (self.url, img) loc2 = img.find('//') if loc2 < 0: img = '%s%s' % (self.url, img) else: img = 'http://google.com/%s/%s' % (self.url.split('//')[1].split('/'), img) test = getImg(img) if not test: store = Img(url=img) store.picture = db.Blob(urlfetch.Fetch(img).content) store.put() pass_on = 'image?img=%s' % img return pass_on
def my_blob(self, img): loc = img.find('http:') if loc < 0 or loc > 6: if img[0] != '/': img = '%s/1%s' % (self.url, img) else: #img = '%s%s' % (self.url, img) loc2 = img.find('//') if loc2 < 0: img = '%s%s' % (self.url, img) else: img = 'http://google.com/%s/%s' % ( self.url.split('//')[1].split('/'), img) test = getImg(img) if not test: store = Img(url=img) store.picture = db.Blob(urlfetch.Fetch(img).content) store.put() pass_on = 'image?img=%s' % img return pass_on
def get_images(userid): user = User.objects(id=userid).first() collect = request.args.get("collect") if collect == 'true': imgs = Img.objects(Q(user=user) & Q(is_collected=True)) elif collect == 'false': imgs = Img.objects(user=user) page = int(request.args.get("page")) per_page = int(request.args.get("per_page")) paginated_imgs = imgs.skip((page - 1) * per_page).limit(per_page) return jsonify({ "message": 'OK', "data": { "total_count": imgs.count(), "page": page, "per_page": per_page, "results": paginated_imgs.to_public_json() } })
def upload(): pic = request.files['pic'] if not pic: return 'No pic uploaded', 400 filename = secure_filename(pic.filename) mimetype = pic.mimetype img = Img(img=pic.read(), mimetype=mimetype, name=filename) db.session.add(img) db.session.commit() return 'Img has been uploaded!', 200
def collectImage(userid, imageId): print(request.method) if request.method == 'PUT': img = Img.objects(id=imageId).first() img.is_collected = request.json.get('collect') img.save() return jsonify({ "message": 'OK', "data": { "id": str(img.id), "collect": img.is_collected } }) elif request.method == 'DELETE': img = Img.objects(id=imageId).first() img.delete() return jsonify({ "message": 'OK', "data": { "id": str(img.id), "collect": img.is_collected } })
def upload(): pic = request.files['pic'] if not pic: return 'No pic uploaded!', 400 filename = secure_filename(pic.filename) mimetype = pic.mimetype if not filename or not mimetype: return 'Bad upload!', 400 img = Img(img=pic.read(), name=filename, mimetype=mimetype) db.session.add(img) db.session.commit() return 'Img Uploaded!', 200
def upload(): models.Img.query.delete() pic = request.files['pic'] if not pic: return 'No pic uploaded!', 400 filename = secure_filename(pic.filename) mimetype = pic.mimetype if not filename or not mimetype: return 'Bad upload!', 400 img = Img(img=pic.read(), name=filename, mimetype=mimetype) pic.seek(0) pic.save(os.path.join(app.config['UPLOAD_FOLDER'], 'image.jpg')) db.session.add(img) db.session.commit() # return 'Img Uploaded!', 200 return redirect('/detect?preview', code=302)
async def take_image(message: types.Message): from models import Img def try_parse_int(s, base=10, val=False): try: return int(s, base) except ValueError: return val ln = 2 if message.get_args(): args = message.get_args().split() if len(args) != 0 and try_parse_int(args[0]): ln = int(args[0]) if not 1 <= ln <= 10: await message.reply( 'Количество изображений может быть в диапазоне от 1 до 10') return m = False i = 0 max_tries = 3 while not m and i < max_tries: try: imgs = Img.normal().order_by_raw('RAND()').limit(ln).get() media_group = [ types.InputMediaPhoto( img.resource_id if img.resource_id else img.file_url, caption= f'Author: {img.author} | Rating: {img.rating}\nTags: {" ".join(img.tags)}' ) for img in imgs ] m = await message.answer_media_group(media_group) for each, img in zip(m, imgs): if not img.resource_id and each.photo[0].file_id: img.resource_id = each.photo[0].file_id img.save() except: i += 1 if i == max_tries: await message.answer('Произошла ошибка, попробуйте позже') await asyncio.sleep(1)
def picture_to_db(filename): """Получает имя файла, путь к файлу, сохраняет его в базе данных, сериализует данные из неё в json и отображает имя и id файла пользователю""" file = request.files['file'] imgI = io.open("uploads/" + file.filename, 'rb') name = filename.rsplit('/', 1)[-1] path = imgI.name image = Img(name=name, path=path) try: db.session.add(image) db.session.commit() database = Img.query.order_by(Img.date).all() with open('tasks/database.json', 'w') as f: json.dump(str(database), f, indent=-2, ensure_ascii=False) f.close() return render_template('/uploads.html', image=image) except Exception: return "error adding to database"
def uploader(legajo): if request.method == 'POST': # obtenemos el archivo del input "archivo" f = request.files['pic'] filename = secure_filename(f.filename) # Guardamos el archivo en el directorio f.save(os.path.join('C:/Cursos/Flask/CapitalHumanoFlask/FotosEmpleados', filename)) pic = request.files['pic'] if not pic: return 'No pic uploaded!', 400 filename = secure_filename(pic.filename) mimetype = pic.mimetype if not filename or not mimetype: return 'Bad upload!', 400 img = Img(name=filename, mimetype=mimetype, emp_legajo=legajo) db.session.add(img) db.session.commit() return "<h1>Archivo subido exitosamente</h1>" return render_template('cargarImagen.html')
def upload(): pic = request.files['pic'] pic2= request.files['pic2'] if not pic: return 'No archivo', 400 filename = secure_filename(pic.filename) mimetype = pic.mimetype #img = Img(img=pic.read(), mimetype=mimetype, name=filename) #db.session.add(img) #db.session.commit() #read image file string data npimg = np.fromfile(pic, np.uint8) # convert numpy array to image gray1 = cv2.imdecode(npimg, cv2.IMREAD_COLOR) gray = cv2.cvtColor(gray1, cv2.COLOR_BGR2GRAY) #gray = cv2.imdecode(imgcv2, cv2.COLOR_BGR2GRAY) auxFrame = gray.copy() faces = faceClassif.detectMultiScale(gray, 1.3, 5) print(faces) for (x, y, w, h) in faces: rostro = auxFrame[y:y+h, x:x+w] rostro = cv2.resize(rostro, (150, 150), interpolation=cv2.INTER_CUBIC) result = emotion_recognizer.predict(rostro) if method == 'LBPH': if result[1] < 70: img = Img(img=pic2.read(), mimetype=mimetype, name=filename) db.session.add(img) db.session.commit() return jsonify({"Emocion": imagePath[result[0]],"Error":False,"Errormsg":""}) # image = emotionImage(imagePath[result[0]]) # nFrame = cv2.hconcat([frame,image3]) else: img = Img(img=pic2.read(), mimetype=mimetype, name=filename) db.session.add(img) db.session.commit() return jsonify({"Emocion": "","Error":True,"Errormsg":"Emocion desconcida"}) # nFrame = cv2.hconcat([frame,np.zeros((480,300,3),dtype=np.uint8)]) if method == 'FisherFaces': if result[1] < 500: img = Img(img=pic2.read(), mimetype=mimetype, name=filename) db.session.add(img) db.session.commit() return jsonify({"Emocion": imagePath[result[0]],"Error":False,"Errormsg":""}) # image = emotionImage(imagePath[result[0]]) # nFrame = cv2.hconcat([frame,image3]) else: img = Img(img=pic2.read(), mimetype=mimetype, name=filename) db.session.add(img) db.session.commit() return jsonify({"Emocion": "","Error":True,"Errormsg":"Emocion desconcida"}) if method == 'EigenFaces': if result[1] < 5700: img = Img(img=pic2.read(), mimetype=mimetype, name=filename) db.session.add(img) db.session.commit() return jsonify({"Emocion": imagePath[result[0]],"Error":False,"Errormsg":""}) # image = emotionImage(imagePath[result[0]]) # nFrame = cv2.hconcat([frame,image3]) else: img = Img(img=pic2.read(), mimetype=mimetype, name=filename) db.session.add(img) db.session.commit() return jsonify({"Emocion": "","Error":True,"Errormsg":"Emocion desconcida"}) # print(pic.read()) return jsonify({"Emocion": "","Error":True,"Errormsg":"No se encontro ningun rostro"})
def make_Img_obj(imgs: list): return [p if type(p) == Img else Img(p) for p in imgs]
def home(): if request.method == 'POST': pic = request.files['pic'] if not pic: session["noPic"] = True return redirect(url_for("home")) filename = secure_filename(pic.filename) mimetype = pic.mimetype if not filename or not mimetype: session["badPic"] = True return redirect(url_for("home")) img = Img(img=pic.read(), name=filename, mimetype=mimetype) db.session.add(img) db.session.commit() session["id"] = img.id return redirect(url_for("home")) else: context = {} flag = True id = 1 if session.get("id"): id = session["id"] img = Img.query.get(id) if not img: context["badImg"] = True img = Img.query.get(1) flag = False if img: curImg, imgNp = imgConversion(img.img) context["imgin"] = curImg #print(imgNp) # imgNp is the np array from the image ############################################# # Fill in prediction stuff # # img.img is the image object in blob form # input_img = preprocess(imgNp) prediction = gen(input_img, training=False).numpy()[0] question, answer = postprocess(imgNp, prediction) #cv2.imshow("input",question) #cv2.waitKey(1) #cv2.imshow("output",answer) #cv2.waitKey(1) outImg = cv2.imencode('.jpg', answer)[1].tobytes() outImg, _ = imgConversion(outImg) context["imgout"] = outImg ############################################# if session.get("noPic"): context["noImg"] = True session.pop("noPic") return render_template("index.html", context=context) if session.get("badPic"): context["badImg"] = True session.pop("badPic") return render_template("index.html", context=context) ## Deleting the picture from db after usage if flag and id != 1: delImg = Img.query.get(id) db.session.delete(delImg) db.session.commit() return render_template("index.html", context=context)
while True: misc_images = glob('assets/commons/*') news_images = [ p for p in glob('{}/data/_images/*'.format(config.REALITY_PATH)) if p not in g_ids ] logger.info('news images: {}, misc images: {}'.format( len(news_images), len(misc_images))) paths = random.sample(news_images, config.SAMPLE[0]) + random.sample( misc_images, config.SAMPLE[1]) images = [] for path in paths: try: images.append(Img(path)) except OSError: continue logger.info('images: {}'.format(len(images))) logger.info('filtering similar images...') images = compare.filter_similar(images, config.IMAGE_SIM_THRESH) logger.info('remaining images: {}'.format(len(images))) faces, objects = {}, {} for img in images: faces.update(img.faces) objects.update(img.objects) logger.info('faces: {}'.format(len(faces))) logger.info('objects: {}'.format(len(objects)))
async def save(self, array: list, initiator) -> int: from models import Img c = 0 last_ten = [] for item in array: if 'id' not in item: continue if item['file_ext'] not in ['png', 'jpg']: continue img = Img() img.id = item['id'] img.tags = item['tag_string'].split(' ') img.author = item['tag_string_artist'] img.source = item['source'] img.file_url = item['file_url'] img.score = item['score'] img.rating = item['rating'] img.is_rating_locked = item['is_rating_locked'] img.has_children = item['has_visible_children'] if img.save(): c += 1 last_ten.append(img) if len(last_ten) == 10: await self.send_media_group(last_ten, initiator) await asyncio.sleep(3) last_ten = [] await self.send_media_group(last_ten, initiator) return c