def translateLetters(): try: data = request.get_json()['image'] with open("input_data/plate.png", "wb") as fh: fh.write(base64.b64decode(data)) flag = image_segmentation() # true if given image segmented correctly if (flag == True): result = {} classify_letters = brahmi_classifier.classify_letters() result['letter'] = classify_letters test_path = os.path.join(segmented_letters) segmented_images = [] for img in tqdm(os.listdir(test_path)): if filetype.is_image(os.path.join(test_path, img)): image_path = os.path.join(test_path, img) pil_img = Image.open(image_path, mode='r') byte_arr = io.BytesIO() pil_img.save(byte_arr, format='PNG') encoded_img = encodebytes( byte_arr.getvalue()).decode('ascii') segmented_images.append(encoded_img) os.remove(os.path.join(test_path, img)) result['images'] = segmented_images response = make_response(result, True, 200) os.remove("input_data/plate.png") return Response(response=response, status=200, mimetype='application/json') else: test_path = os.path.join(segmented_letters) for img in tqdm(os.listdir(test_path)): if filetype.is_image(os.path.join(test_path, img)): os.remove(os.path.join(test_path, img)) os.remove("input_data/plate.png") response = make_response("Too much noise in image", True, 200) return Response(response=response, status=200, mimetype='application/json') except Exception as e: # print(e) response = make_response('Something went wrong', False, 404) return Response(response=response, status=404, mimetype='application/json')
async def avatar(self, ctx, *, avatar=None): """Sets or removes a splinter's avatar.""" if ctx.message.attachments: fp = io.FileIO(ctx.message.attachments[0].filename, "w+") try: await ctx.message.attachments[0].save(fp, use_cached=True) except discord.errors.HTTPException: await ctx.message.attachments[0].save(fp) if not filetype.is_image(fp): await ctx.send(inline("The attached file must be an image.")) return fp.seek(0) ctx.spec.avatar = await rpadutils.saveimg(fp) elif avatar is None: await ctx.send(ctx.spec.avatar or inline("You do not have an avatar set.")) return elif avatar.lower() in ["clear", "none", "remove"]: ctx.spec.avatar = None else: async with aiohttp.ClientSession() as session: try: async with session.get(avatar) as resp: if not resp.content_type.split("/")[0] == "image": await ctx.send(inline("The attatched link must be an image.")) return fp = io.FileIO("image."+resp.content_type.split("/")[1], "w+") fp.write(await resp.read()) fp.seek(0) ctx.spec.avatar = await rpadutils.saveimg(fp) except (aiohttp.InvalidURL, AssertionError): await ctx.send(inline("That's an invalid URL.")) return await ctx.send(inline("Done"))
async def isimage(att: discord.Attachment): fp = io.FileIO(att.filename, "w+") try: await att.save(fp, use_cached=True) except discord.errors.HTTPException: await att.save(fp) return filetype.is_image(fp)
def add_a_tag(link, name, cat, count): str_is = '' if filetype.is_image(link): str_is = ''' <div id = "''' + count + '''" class="col-lg-3 col-md-6 col-sm-6 all_files ''' + str( cat).lower() + '''"> <div class="card card-block card-stretch card-height"> <div class="card-body image-thumb"> <div class="mb-4 text-center p-3 rounded iq-thumb"> <div class="iq-image-overlay"></div> <a href="{}" data-title="Mobile-plan.pdf" data-load-file="file" data-load-target="#resolte-contaniner" data-url="{}" data-toggle="modal" data-target="#exampleModal"><img src="{}" class="img-fluid" alt="image1"></a> </div> <p>{}</p> <button type="button" class="btn btn-link delete_button" value='{}' >Delete</button> </div> </div> </div> '''.format(link, link, link, name, link) if filetype.is_archive(link): str_is = ''' <div id = "''' + count + '''" class="col-lg-3 col-md-6 col-sm-6 all_files ''' + str( cat).lower() + '''"> <div class="card card-block card-stretch card-height"> <div class="card-body image-thumb"> <div class="mb-4 text-center p-3 rounded iq-thumb"> <div class="iq-image-overlay"></div> <a href="{}" data-title="Mobile-plan.pdf" data-load-file="file" data-load-target="#resolte-contaniner" data-url="{}" data-toggle="modal" data-target="#exampleModal"> <img src="/static/assets/images/layouts/page-1/pdf.png" class="img-fluid" alt="image1"></a> </div> <p>{}</p> <button type="button" class="btn btn-link delete_button" value='{}' >Delete</button> </div> </div> </div> '''.format(link, link, link, name, link) if '.csv' in name or '.xlsx' in name: str_is = ''' <div id = "''' + count + '''" class="col-lg-3 col-md-6 col-sm-6 all_files ''' + str( cat).lower() + ''''"> <div class="card card-block card-stretch card-height"> <div class="card-body image-thumb"> <div class="mb-4 text-center p-3 rounded iq-thumb"> <div class="iq-image-overlay"></div> <a href="{}" data-title="Mobile-plan.pdf" data-load-file="file" data-load-target="#resolte-contaniner" data-url="{}" data-toggle="modal" data-target="#exampleModal"> <img src="/static/assets/images/layouts/page-1/xlsx.png" class="img-fluid" alt="image1"></a> </div> <p>{}</p> <button type="button" class="btn btn-link delete_button" value='{}' >Delete</button> </div> </div> </div> '''.format(link, link, link, name, link) return str_is
async def guesstype(self, ctx): for att in ctx.message.attachments: fp = io.FileIO("file", "w+") try: await att.save(fp, use_cached=True) except discord.errors.HTTPException: await att.save(fp) ft = filetype.is_image(fp) await ctx.send(ft)
def browse_pic(self): self.listCascade.clear() photo = QtWidgets.QFileDialog.getOpenFileName( self, 'Open file', 'D:\\Python\\KG', "Image files (*.jpg *.gif, *.bmp, *.png, *.jpeg)")[0] if photo: self.image = cv.imread(photo) self.path = photo scale_percent = 40 width = int(self.image.shape[1] * scale_percent / 100) height = int(self.image.shape[0] * scale_percent / 100) dim = (width, height) resized = cv.resize(self.image, dim, interpolation=cv.INTER_AREA) cv.imwrite("tmp\\original.bmp", resized) if self.mode == 'detection': if filetype.is_image(photo): self.listCascade.addItem( QListWidgetItem( 'Файл успешно прочитан как изображение')) CatDetector(photo, self) else: self.listCascade.addItem( QListWidgetItem('Файл не является изображением')) elif self.mode == 'points': if filetype.is_image(photo): self.listCascade.addItem( QListWidgetItem( 'Файл успешно прочитан как изображение. Выбирайте каскад' )) self.listCascade.addItem(QListWidgetItem('Original')) self.listCascade.addItem(QListWidgetItem('OpenCV Cascade')) self.listCascade.addItem( QListWidgetItem('OpenCV Cascade Extended')) self.listCascade.addItem(QListWidgetItem('My Cascade')) self.listCascade.addItem(QListWidgetItem('Glitch Cascade')) else: self.listCascade.addItem( QListWidgetItem('Файл не является изображением'))
def is_image(given_argv = None): """! @fn is_image @brief Returns True if given argument is a valid readable image, False otherwise @param[in] given_argv Given argument @return True if given_argv is a valid readable image, False otherwise """ # Check if given argument is an existing and readable file image if os.path.isfile(given_argv) and os.access(given_argv, os.R_OK) and filetype.is_image(given_argv): # Return True statement return True # Return False statement return False
def openFile(self): """ Открытие файла """ # На случай, если в списке уже есть элементы self.listWidget.clear() fileName = QtWidgets.QFileDialog.getOpenFileName(self, "Выберите файл")[0] if fileName: self.image = cv2.imread(fileName) if filetype.is_image(fileName): self.listWidget.addItem(QListWidgetItem('Файл успешно прочитан как изображение')) railWayAnalyzer(fileName, self) else: self.listWidget.addItem(QListWidgetItem('Файл не является изображением'))
def classify_letters(): test_path = os.path.join(segmented_letters) testing_results = {} results = [] for img in tqdm(os.listdir(test_path)): if filetype.is_image(os.path.join(test_path, img)): prediction = loaded_model.predict( [prepare(os.path.join(test_path, img))]) testing_results[img] = CATEGORIES[int(np.argmax(prediction))] for x in testing_results: results.append(testing_results[x]) return results
async def upload_controller(src_folder: Path, dst_url: str): if not src_folder.exists(): raise FileNotFoundError('Folder you specified does not exist') image_files = filter( lambda path: Path.is_file(path) and filetype.is_image(str(path)), src_folder.rglob('*')) loop = asyncio.get_event_loop() semaphore = asyncio.Semaphore(value=MAX_CONCURRENT_FILES_PROCESSED) async with aiohttp.ClientSession() as session: tasks = [ loop.create_task(upload_task(session, path, dst_url, semaphore)) for path in image_files ] for task in tqdm(asyncio.as_completed(tasks), total=len(tasks)): await task
def get_all_images(self): images = [] root_path_dirs = os.path.normpath(self.source_path).split(os.path.sep) for (dir_path, _, file_names) in os.walk(self.source_path): for file_name in file_names: full_path = os.path.join(dir_path, file_name) if (filetype.is_image(full_path)): image_path_dirs = os.path.normpath(dir_path).split( os.path.sep) dirs = set(image_path_dirs) - set(root_path_dirs) images.append(File(file_name, full_path, dirs)) return images
def translateLetters(): try: image = request.files["image"] image_name = image.filename image.save(os.path.join(os.getcwd(), image_name)) if filetype.is_image(os.path.join(os.getcwd(), image_name)): result = {'letter': [1,2,3,4,5]} response = make_response(result,True,200) os.remove(os.path.join(os.getcwd(), image_name)) return Response(response=response, status=200, mimetype='application/json') else: response = make_response('The file is NOT an Image', False, 200) return Response(response=response, status=200, mimetype='application/json') except Exception as e: print(e) response = make_response('The file is NOT FOUND', False, 404) return Response(response=response, status=404, mimetype='application/json')
async def upload_image(image: UploadFile = File(...)): with open("image.png", "wb") as buffer: shutil.copyfileobj(image.file, buffer) if not filetype.is_image("image.png"): os.remove("image.png") raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Please upload an image file format.", ) try: success = utility_functions.detect_face("image.png") emotion, value = predict_fer.predict_facial_expression("image.png") return {"emotion": emotion, "prediction_value": value} except Exception as e: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) finally: os.remove("image.png")
def upload_photo(self, request, **kwargs): # pragma: no cover file = request.FILES.get("file") serializer = UserPhotoSerializer(data=request.data) serializer.is_valid(raise_exception=True) if filetype.is_image(file): user = self.request.user user.photo = file user.save(update_fields=["photo"]) # Update avatar on integrations celery_app.send_task("update_user_photo", args=[user.email, self._get_photo_url(user)]) # Update avatar in all rocket chat registered for authorization in user.authorizations_user.all(): for project in authorization.organization.project.all(): for service_status in project.service_status.filter( service__service_type=Service.SERVICE_TYPE_CHAT): upload_photo_rocket( server_rocket=service_status.service.url, jwt_token=self.request.auth, avatar_url=user.photo.url, ) return Response({"photo": user.photo.url}) try: raise UnsupportedMediaType( filetype.get_type(file.content_type).extension, detail=_( "We accept images only in the formats: .png, .jpeg, .gif"), ) except Exception: raise UnsupportedMediaType( None, detail=_( "We accept images only in the formats: .png, .jpeg, .gif"), )
def question(update, context): chat_id = update.message.chat_id category = update.message.text.split()[-1].lower() question_requested: bool = False if category not in os.listdir('questions'): text = "Не смог найти такую категорию вопросов" else: if given_questions.search((where('chat_id') == chat_id) & (where('category') == category)): text = "Уже выдал вам задачу на эту категорию" else: text = f"Вот вопрос на {category}" question_requested = True context.bot.send_message(chat_id=chat_id, text=text) if not question_requested: return filename = f"questions/{category}/" + choice( os.listdir(f'questions/{category}/')) print(filename) with open(filename, 'rb') as doc: if category not in quiet_categories: for admin in admins_table.all(): context.bot.send_message( chat_id=admin['chat_id'], text= f'User {update.message.from_user} (category: {category}):') context.bot.send_document(chat_id=admin['chat_id'], document=doc) doc.seek(0) given_questions.insert({'chat_id': chat_id, 'category': category}) if filetype.is_image(filename): context.bot.send_photo(chat_id=chat_id, photo=doc) else: context.bot.send_document(chat_id=chat_id, document=doc)
ProcessingTime = (datetime.now() - ProcessStart).total_seconds() print("%s/%s %s : Allready in database %s, %s, %s" % (LocalProcessedFiles, FilesCount, threading.current_thread().name, str(file.Filename), round(file.HashTime, 2), round(ProcessingTime, 2))) log.write("Allready in database %s\n" % str(file.Filename)) # Load up a queue with your data. This will handle locking q = queue.Queue() print("Scanning files...") for path, dirs, files in os.walk(source): for filename in files: import filetype if filename[0] != "." and ( filetype.is_image(os.path.join(path, filename)) or filetype.is_video(os.path.join(path, filename))): FilesCount = FilesCount + 1 file = os.path.join(path, filename) print("%s : %s" % (FilesCount, file)) q.put(file) print("%s Files found." % FilesCount) print("Finished scanning...") for i in range(thread_count): t = threading.Thread(target=worker, args=(q, )) t.start() q.join() mydb.close()
PREFIX = opts.prefix SIGMA_S = opts.sigma_s SIGMA_R = opts.sigma_r SHADE_FACTOR = opts.shade real_path = os.path.realpath(source) if 0 < SIGMA_S > 100: raise RuntimeError("Sigma_S value between 0-100") if 0 < SIGMA_R > 0.1: raise RuntimeError("Sigma_R value between 0-0.1") if 0 < SHADE_FACTOR > 0.1: raise RuntimeError("Shade factor value between 0-0.1") if not os.path.exists(real_path): raise RuntimeError(f"Source file does not exist: {real_path}") if not filetype.is_image(real_path): raise RuntimeError( f"{real_path} is not a valid image type. It could be damaged, corrupted or file is empty." ) base_name = os.path.basename(real_path) directory = os.path.dirname(real_path) sketch_filename = "{}_{}".format(PREFIX, base_name) sketch_path = os.path.join(directory, sketch_filename) cv2.namedWindow(sketch_filename, cv2.WINDOW_NORMAL) cv2.setWindowProperty(sketch_filename, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN) cv2.setWindowProperty(sketch_filename, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_NORMAL)
def check_image(filename): return filetype.is_image(filename)
# Getting the profile and frontal cascades from the cv2 library profileface_cascade = os.path.join(args.cv_path, "data\haarcascade_profileface.xml") frontalface_cascade = os.path.join(args.cv_path, "data\haarcascade_frontalface_alt.xml") # Creating two face detectors, one for detecting full frontal faces and one for profiles # For best result we combine results from both detectors to check for faces frontal_detector = fd.FaceDetector(frontalface_cascade) profile_detector = fd.FaceDetector(profileface_cascade) # Only sort files that are images print("Identifying images...") images = [ image for image in images if image.is_file() and ft.is_image(image.path) ] if not images: # Exit the program if no images are found print("No Images found in the given folder.") exit() for image in tqdm(images, desc="Sorting pictures"): try: cv_image = cv.imread(image.path) except: continue # In case of an error in reading the picture we just skip sorting the picture if frontal_detector.contains_face( cv_image) or profile_detector.contains_face(cv_image): dest_path = os.path.join(faces_folder, image.name)
def real_upload(params, fileobj): try: data = yun.runtime.tokenizer.unpack(params['token']) except VerificationError: return DATA_INVALID_TOKEN else: phone = data.split('&')[0] mydb, user_id = get_userdb_by_phone(phone) userspace = get_userspace_by_phone(phone)[0] cr = mydb.cursor() pid = params['pid'] or ROOT if not user_id or fileobj is None: return {'code': 51, 'msg': '上传错误', 'data': []} create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S %f') filename = fileobj.filename res = cr.execute(('SELECT COUNT(*) FROM fs WHERE state=0 ' 'AND name="{}" AND parent="{}"').format(filename, pid)) if res.fetchone()[0] > 0: time_str = datetime.now().strftime('%Y%m%d_%H%M%S_%f') filename = '{}-{}'.format(time_str, filename) buf = BytesIO() while True: data = fileobj.read1(8192) buf.write(data) if buf.tell() > FILE_SIZE_BOUNDARY: break elif not data: fileobj.close() break if buf.tell() <= 0: return {'code': 52, 'msg': '上传错误', 'data': []} uuid_ = uuid4().hex path = '/' if pid != ROOT: path = cr.execute('SELECT path FROM fs WHERE state=0 AND uuid=?', (pid, )).fetchone()[0] if path == '/': path = '{}{}'.format(path, pid) else: path = '{}/{}'.format(path, pid) if buf.tell() <= FILE_SIZE_BOUNDARY: zero_blob = apsw.zeroblob(buf.tell()) hash_name = '' else: zero_blob = apsw.zeroblob(0) typeguess = filetype.guess(buf.getvalue()) extension, mime = '', '' if typeguess is None: if len(filename.split('.')) >= 2: extension = filename.split('.')[-1] mime = 'application/{}'.format(extension) else: mime = typeguess.mime extension = typeguess.extension is_image, thumb_zero_blob = False, apsw.zeroblob(0) if buf.tell() <= FILE_SIZE_BOUNDARY: if filetype.is_image(buf.getvalue()): is_image = True thumb_bytes = BytesIO() im = Image.open(buf) im.thumbnail((750, 750), Image.ANTIALIAS) im.save(thumb_bytes, 'png') thumb_zero_blob = apsw.zeroblob(len(thumb_bytes.getvalue())) else: os_path = os.path.join(userspace, uuid_[:2], uuid_[2:4]) try: fs.os.makedirs(os_path) except FileExistsError: pass os_path = os.path.join(os_path, uuid_) f = fs.open(os_path, 'w+b') f.write(buf.getvalue()) while True: data = fileobj.read1(8192) f.write(data) if not data: fileobj.close() break f.seek(0) bytesio = BytesIO(f.read()) if filetype.is_image(bytesio.read(64)): is_image = True thumb_bytes = BytesIO() im = Image.open(bytesio) im.thumbnail((750, 750), Image.ANTIALIAS) im.save(thumb_bytes, 'png') thumb_zero_blob = apsw.zeroblob(len(thumb_bytes.getvalue())) f.close() cr.execute( ('INSERT INTO fs (creator, phone, state, type, name, extension, mime,' ' size, blob, thumb, uuid, create_time, modify_time, parent, path)' ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'), (user_id, phone, 0, 2, filename, extension, mime, buf.tell(), zero_blob, thumb_zero_blob, uuid_, create_time, create_time, pid, path)) fid_ = None if is_image: fid_ = cr.execute( ('SELECT id FROM fs WHERE uuid="{}"'.format(uuid_))).fetchone()[0] blob = mydb.blobopen("main", "fs", "thumb", fid_, 1) blob.write(thumb_bytes.getvalue()) blob.close() if buf.tell() <= FILE_SIZE_BOUNDARY: if not fid_: fid_ = cr.execute( ('SELECT id FROM fs WHERE uuid="{}"'.format(uuid_) )).fetchone()[0] blob = mydb.blobopen("main", "fs", "blob", fid_, 1) blob.write(buf.getvalue()) blob.close() else: pass return DATA_OK
"## Command Arguments #################################################" ) print("\n".join("{}:{}".format(i, j) for i, j in args.items())) print( "######################################################################" ) return args if __name__ == '__main__': # Parsing command line arguments entered by user args = parse_args() # If File Path if os.path.isfile(args['input_path']): # Process a file if filetype.is_image(args['input_path']): ocr_img( # if 'search_str' in (args.keys()) else None img=None, input_file=args['input_path'], search_str=args['search_str'], highlight_readable_text=args['highlight_readable_text'], action=args['action'], show_comparison=args['show_comparison'], generate_output=args['generate_output']) else: ocr_file(input_file=args['input_path'], output_file=args['output_file'], search_str=args['search_str'] if 'search_str' in (args.keys()) else None, pages=args['pages'],