def test_upload_item(client): # test create imgs1 = [DataURI.from_file(f'tests/images/{i}.jpg') for i in range(1, 2)] imgs2 = [DataURI.from_file(f'tests/images/{i}.jpg') for i in range(7, 8)] imgs3 = [DataURI.from_file(f'tests/images/{i}.jpg') for i in range(13, 14)] item = { "category": 1, "currency": "GHS", "images": imgs1, "tags": ["1", "2", "3", "4"], "options": [{ "name": "opt1", "required": True, "values": [{ "images": imgs2, }, { "images": imgs3, }] }] } payload = { "111": { "upload_item": { "item_details": item, "seller_id": 1 }, "000": ["upload_item"] }, "000": ["111"] } login = Logins.select().order_by(Logins.id.desc()).get() headers = { 'Authorization': login.token, 'Account-ID': login.user.email, 'Device-ID': login.device_hash } response = client.simulate_post('/action', body=json.dumps(payload), headers=headers) assert response.json["111"]["upload_item"]["status"]
def post(self, request, *args, **kwargs): pjName = request.POST['pjName'] test_list = request.FILES['test'] #偵測圖片 fs = FileSystemStorage() imgname = fs.save(test_list.name, test_list) test_list_url = fs.url(imgname) result = join_faceRecognition(pjName, test_list_url) result = DataURI.from_file(result) return Response({'result': result}, status=status.HTTP_201_CREATED) # class GoogleLogin(TokenObtainPairView): # permission_classes = (AllowAny, ) # AllowAny for login # serializer_class = SocialLoginSerializer # def post(self, request): # serializer = self.get_serializer(data=request.data) # if serializer.is_valid(raise_exception=True): # user = serializer.save() # return Response(get_tokens_for_user(user)) # else: # raise ValueError('Not serFLAGS.output)
def uploadRestore(request): img = request.POST.get('img') mask = request.POST.get('mask') fname = datetime.datetime.now().strftime("%Y%m%d%H%M%S") user_folder = 'media' src = f'{user_folder}/input/{fname}.png' maskdir = f'{user_folder}/input/m-{fname}.png' dest = f'{user_folder}/output/o-{fname}.png' uri = DataURI(img) fd = open(src, 'wb') fd.write(uri.data) fd.close() uri = DataURI(mask) fd = open(maskdir, 'wb') fd.write(uri.data) fd.close() cp.saveCompressed(src) rs.restore(src, maskdir, dest) output_uri = b64encode(DataURI.from_file(dest).data) os.remove(src) os.remove(maskdir) os.remove(dest) return HttpResponse(output_uri)
def get_file(request): file_name = request.GET["song_id"] file_full_path = default_storage.path('tmp/' + file_name) with open(file_full_path, 'rb+') as f: data = f.read() dataURI = DataURI.from_file(file_full_path) return HttpResponse(dataURI)
def load_logo(name): """ Load a logo from package data. Parameters ---------- name : str The theme name. Returns ------- datauri.DataURI A str based object for the data URI. """ filename = os.path.join("data", "logos", f"{name}.svg") if not resource_exists(filename): LOG.debug(f"A logo for the theme '{name}' was not found") return None filename = resource_filename(filename) from datauri import DataURI return DataURI.from_file(filename)
def retrieve(media_id, client, is_device): try: media = db.session.query(Media).filter(Media.id == media_id).first() if media is None or media.uploaded is False: raise e_media.MediaNotFound if not (not is_device and media.can_be_accessed_by_user(client)) and \ not (is_device and media.can_be_accessed_by_device(client)): raise e_media.ForbiddenAccess if not media.file_exist(): raise e_media.MediaNotFoundInSystem data_uri = DataURI.from_file(media.get_full_path()) response = { "data": { "success": True, "data": data_uri }, "status_code": 200 } except e_media.MediaException as exception: response = { "data": { "success": False, "message": exception.message }, "status_code": exception.status_code } return response
def generateURI(filepath): png_uri = DataURI.from_file(filepath) png_uri.mimetype 'image/png' png_uri.data #the data URI is png_uri #print(png_uri); return png_uri
def imageTransition(): id = request.form["id"] filter = request.form["filter"] image_length = int(request.form["image_length"]) input_images_dataURI = [ DataURI(request.form[f"image{i}"]).data for i in range(image_length) ] # # FIXME: uuid-인덱스 로 이미지 저장 user_uuid = uuid.uuid4() os.makedirs(f'./{user_uuid}/before') os.makedirs(f'./{user_uuid}/after') for idx in range(image_length): im = Image.open(BytesIO(input_images_dataURI[idx])) im = im.convert('RGB') im.save(f'{user_uuid}/before/image{idx}.jpg') # TODO: 이미지 변환 from whitebox import cartoonize model_path = 'saved_models' location = f'{user_uuid}' cartoonize.cartoonize(location, model_path) from model import gallery output_images_dict = {} for idx in range(image_length): # FIXME: 이미지를 datauri로 변경 translated_image = DataURI.from_file( f'./{user_uuid}/after/image{idx}.jpg') # FIXME: 회원일 경우 이미지를 개인 갤러리에 저장 if id != 'Not User': gallery.imageSave(id, filter, translated_image) # FIXME: 변환된 이미지를 클라이언트에게 보내기 위해.. output_images_dict[f'image{idx}'] = translated_image os.remove(f'./{user_uuid}/before/image{idx}.jpg') os.remove(f'./{user_uuid}/after/image{idx}.jpg') # FIXME: 저장된 이미지 삭제 os.rmdir(f'./{user_uuid}/before') os.rmdir(f'./{user_uuid}/after') os.removedirs(f'./{user_uuid}') # FIXME: 이미지들 전송 return jsonify( result="OK", imageLength=image_length, cartoonImages=output_images_dict, )
def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() result = postModels(request) if request.POST['modelName'] == 'YOLOv3': result = DataURI.from_file(os.path.join(result)) return Response({'result': result}, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, *args, **kwargs): file_serializer = ganSerializer(data=request.data) if file_serializer.is_valid(): filename = file_serializer.save().file.name model = request.POST['category'] filename = filename.split('/')[1] print(filename) output = 'output' + str(random.randint(0, 99)) ganConvert(model, filename, output) result = DataURI.from_file(os.path.join('./GANresult/' + output)) return Response({'result': result}, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def main(): if len(sys.argv) < 2 or not os.path.exists(sys.argv[1]): raise ValueError(INPUT_ERROR_MESSAGE) input_path = sys.argv[1] input_name = os.path.basename(input_path).rsplit(".", 1)[0] input_dirname = os.path.dirname(input_path) try: output_path = sys.argv[2] except: output_path = os.path.join(input_dirname, input_name + ".dot") try: output_svg_path = sys.argv[3][:-4] if sys.argv[3].endswith(".svg") else sys.argv[3] except: output_svg_path = os.path.join(input_dirname, input_name) output_dirname = os.path.dirname(output_path) output_svg_dirname = os.path.dirname(output_svg_path) if len(sys.argv) == 5 and sys.argv[4] not in ("LR", "TB"): raise ValueError("Rankdir must be 'LR' or 'TB'") rankdir = sys.argv[4] if len(sys.argv) == 5 else "LR" if output_dirname and not os.path.exists(output_dirname): raise ValueError(INPUT_ERROR_MESSAGE) if output_svg_dirname and not os.path.exists(output_svg_dirname): raise ValueError(INPUT_ERROR_MESSAGE) convert(input_path, output_path, output_svg_path, rankdir=rankdir) with open("static/template.html") as fp: template = fp.read().replace("{{ svg_file }}", str(DataURI.from_file(output_svg_path + ".svg"))) with open(os.path.join(output_svg_dirname, input_name + ".html"), "w") as fp: fp.write(template) result_static_path = os.path.join(output_svg_dirname, "static") if output_svg_dirname.replace(".", ""): copy_tree("static", result_static_path) os.remove(os.path.join(result_static_path, "template.html"))
def test_set_entries(client): """ :kwargs: excel file """ file = DataURI.from_file('tests/files/md.csv') payload = { "111": { "set_entries": { "file": file }, "000": ["set_entries"] }, "000": [ "111", ] } response = client.simulate_post('/action', body=json.dumps(payload)) assert response.json["111"]["set_entries"]["status"]
def post(self, request, *args, **kwargs): train_list = request.FILES.getlist('train') #訓練的圖片陣列 print(train_list) test_list = request.FILES['test'] #偵測圖片 print(test_list) fs = FileSystemStorage() train_list_url = [] namelist = [] for img in train_list: imgname = fs.save(img.name, img) train_list_url.append(fs.url(imgname)) namelist.append(img.name.split('.')[0]) imgname = fs.save(test_list.name, test_list) test_list_url = fs.url(imgname) print(namelist) name_list = namelist result = FaceRecognition(train_list_url, name_list, test_list_url) result = DataURI.from_file(result) return Response({'result': result}, status=status.HTTP_201_CREATED)
def load_datauri(loader, node): return DataURI.from_file(node.value)
def test_no_wrap(self): filename = os.path.join(TEST_DIR, 'test_long_file.txt') parsed = DataURI.from_file(filename) self.assertFalse("\n" in str(parsed))
def test_from_file(self): filename = os.path.join(TEST_DIR, 'test_file.txt') parsed = DataURI.from_file(filename) self.assertEqual(parsed.data, b'This is a message.\n') self.assertEqual(parsed.charset, None)
def imageUrl(src): png_uri = DataURI.from_file(src) mt = png_uri.mimetype return png_uri
def uploadFilesAndAdjustXMLImageRefs(jobDir, schemaId, xmlId, runCtx): imageFiles = [ ] # track image files uploaded -- which go into default bucket (returned id is substituted back into XML) # all other files go into 'curateinput' bucket with filename {schemaId}/{xmlId}/filename (returned ID is not stored) # for now let exceptions bubble up to handler in caller restbase = runCtx['restbase'] webbase = runCtx['webbase'] curateFilesUrl = restbase + '/nmr/blob/create' blobs = [] datasetId = runCtx['datasetId'] # get a list of all files in jobDir and upload them dataFiles = os.listdir(jobDir) for f in dataFiles: fn = jobDir + '/' + f # changed following check to save imageFiles into curateinput bucket as well since not doing so causes downstream issue if os.path.isfile( fn ): ## and f not in imageFiles: # make sure it's a regular file and wasn't already uploaded as an image dataUri = DataURI.from_file(fn) dataUri = dataUri.replace("\n", "") # remove line feeds ## objFN = schemaId + '/' + xmlId + '/' + f # change to datasetid/xmlid/filename ## objFN = datasetId + '/' + xmlId + '/' + f objFN = f # curatefiledata = '{"filename":"'+ objFN + '","bucketName":"curateinput", "dataUri":"' + dataUri + '"}' curatefiledata = '{"filename":"' + objFN + '","dataUri":"' + dataUri + '","originalDatasetId":"' + datasetId + '"}' # logging.debug(curatefiledata + ' len is: ' + str(len(curatefiledata))) curatefiledata = json.loads(curatefiledata) rq = urllib.request.Request(curateFilesUrl) logging.debug('request created using createFilesUrl') rq.add_header('Content-Type', 'application/json') nmCurateFiles = nm_rest(logging, runCtx['sysToken'], runCtx['curateApiToken'], runCtx['curateRefreshToken'], rq) r = nmCurateFiles.urlopen( json.dumps(curatefiledata).encode("utf8")) if r.getcode() == 201: uploadId = json.loads(r.read().decode("utf-8"))['data']['id'] logging.debug('uploaded file ID: ' + uploadId) content_type = mime.Types.of(objFN)[0].content_type blob_info = { 'type': 'blob', 'id': uploadId, 'metadata': { 'filename': objFN, 'contentType': content_type } } if runCtx['excelTemplateName'] == objFN: blob_info['metadata']['is_completed_pnc_template'] = True blobs.append(blob_info) ## testing - raise ValueError('Upload of input successful. returned id: ' + uploadId) ## for testing else: raise ValueError('Unexpected return code from file upload (' + objFN + '): ' + str(r.getcode())) # TODO remove this block after testing #xmlTitleRe = re.compile('^[A-Z]([0-9]+)[_][S]([0-9]+)[_][\S]+[_]\d{4}([.][Xx][Mm][Ll])?$') #reMatch = xmlTitleRe.match(xmlId) ## TODO handle invalid title i.e. reMatch == None #if reMatch == None: # logging.error('xmlId (title) does not match expected format: ' + xmlId + ' (match was None)') #datasetId = reMatch.group(1) xmlName = jobDir + '/xml/' + xmlId + '.xml' xmlTree = etree.parse(xmlName) updatedXml = False for f in xmlTree.findall('.//MICROSTRUCTURE/ImageFile/File'): fn = f.text.split('/')[-1] blob = None for b in blobs: bfn = b['metadata']['filename'] if bfn == fn: blob = b if blob == None: raise ValueError('Unable to match xml: ' + xmlId + ' MICROSTRUCTURE image filename: ' + fn + ' with an uploaded image name.') else: imageRef = webbase + '/nmr/blob?id=' + blob['id'] logging.debug('new image value for XML: ' + imageRef) f.text = imageRef # update XML node with new image reference ## testing -- raise ValueError('Upload successful. returned id: ' + uploadId) ## for testing updatedXml = True if updatedXml == True: # update the XML in the file xmlTree.write(xmlName) return blobs
def uploadFilesAndAdjustXMLImageRefs(jobDir, schemaId, xmlId): imageFiles = [ ] # track image files uploaded -- which go into default bucket (returned id is substituted back into XML) # all other files go into 'inputfiles' bucket with filename {schemaId}/{xmlId}/filename (returned ID is not stored) # for now let exceptions bubble up to handler in caller restbase = os.environ['NM_LOCAL_REST_BASE'] webbase = os.environ['NM_WEB_BASE_URI'] curateFilesUrl = restbase + '/nmr/blob' sysToken = os.environ['NM_AUTH_SYSTEM_TOKEN'] curateApiToken = os.environ['NM_AUTH_API_TOKEN_CURATE'] curateRefreshToken = os.environ['NM_AUTH_API_REFRESH_CURATE'] xmlName = jobDir + '/xml/' + xmlId + '.xml' xmlTree = ET.parse(xmlName) updatedXml = False for f in xmlTree.findall('.//MICROSTRUCTURE/ImageFile/File'): fn = f.text.split('/')[-1] imageFiles.append(fn) fullImageFileName = jobDir + '/' + fn logging.debug('uploading: ' + fullImageFileName) dataUri = DataURI.from_file(fullImageFileName) dataUri = dataUri.replace("\n", "") # remove line feeds ## logging.debug('dataUri: ' + dataUri) curatefiledata = '{"filename":"' + fn + '","dataUri":"' + dataUri + '"}' # logging.debug(curatefiledata + ' len is: ' + str(len(curatefiledata))) curatefiledata = json.loads(curatefiledata) rq = urllib2.Request(curateFilesUrl) logging.debug('request created using createFilesUrl') rq.add_header('Content-Type', 'application/json') nmCurateFiles = nm_rest(logging, sysToken, curateApiToken, curateRefreshToken, rq) r = nmCurateFiles.urlopen(json.dumps(curatefiledata).encode("utf8")) if r.getcode() == 201: uploadId = json.loads(r.read())['data']['id'] imageRef = webbase + '/nmr/blob?id=' + uploadId logging.debug('new image value for XML: ' + imageRef) f.text = imageRef # update XML node with new image reference ## testing -- raise ValueError('Upload successful. returned id: ' + uploadId) ## for testing updatedXml = True else: raise ValueError('Unexpected return code from image upload (' + fn + '): ' + str(r.getcode())) if updatedXml == True: # update the XML in the file xmlTree.write(xmlName) # get a list of all files in jobDir and upload them dataFiles = os.listdir(jobDir) for f in dataFiles: fn = jobDir + '/' + f if os.path.isfile( fn ) and f not in imageFiles: # make sure it's a regular file and wasn't already uploaded as an image dataUri = DataURI.from_file(fn) dataUri = dataUri.replace("\n", "") # remove line feeds objFN = schemaId + '/' + xmlId + '/' + f curatefiledata = '{"filename":"' + objFN + '","bucketName":"curateinput","dataUri":"' + dataUri + '"}' # logging.debug(curatefiledata + ' len is: ' + str(len(curatefiledata))) curatefiledata = json.loads(curatefiledata) rq = urllib2.Request(curateFilesUrl) logging.debug('request created using createFilesUrl') rq.add_header('Content-Type', 'application/json') nmCurateFiles = nm_rest(logging, sysToken, curateApiToken, curateRefreshToken, rq) r = nmCurateFiles.urlopen( json.dumps(curatefiledata).encode("utf8")) if r.getcode() == 201: uploadId = json.loads(r.read())['data']['id'] logging.debug('uploaded file ID: ' + uploadId) ## testing - raise ValueError('Upload of input successful. returned id: ' + uploadId) ## for testing else: raise ValueError('Unexpected return code from file upload (' + objFN + '): ' + str(r.getcode()))
def send(): paisuser = paises[current_user.pais] numeros = [] asignaciones = Asignacion.query.filter_by(user_id=current_user.id).all() enviados = Enviado.query.filter_by(user=current_user.username).all() if enviados: for mensaje in enviados: if mensaje.numero not in numeros: numeros.append(mensaje.numero) lineas = [] for asig in asignaciones: agreg = Linea.query.get(asig.linea_id) lineas.append(agreg) if request.method == 'POST': instancia = random.choice(lineas) numero = str(request.form.get("phone")) prefijo = str(request.form.get("selectorflags")) cliente = request.form.get("cliente") phone = prefijo + numero if cliente: body = cliente instancias = str(instancia.api_url) tokens = str(instancia.token) url = f'{instancias}message?token={tokens}' data = ({"phone": phone, "body": body}) res = requests.post(url, json=data, timeout=2000) if res.status_code != 200: raise Exception("ERROR: API request unsuccessful.") nuevo = Enviado(user=current_user.username, linea=instancia.name, numero=numero, prefijo=prefijo, mensaje=body) db.session.add(nuevo) db.session.commit() archivo = request.files["archivo"] if archivo.filename: instancias = str(instancia.api_url) tokens = str(instancia.token) mensaje = request.form.get("mensaje") if mensaje: if current_user.mensajeoculto: f = open('mensaje.txt', encoding='latin-1') mensajeoculto = f.read() mensaje = f'''{mensaje}\n\n\n{mensajeoculto}''' url = f'{instancias}message?token={tokens}' data = ({"phone": phone, "body": mensaje}) res = requests.post(url, json=data, timeout=2000) if res.status_code != 200: raise Exception("ERROR: API request unsuccessful.") nuevo = Enviado(user=current_user.username, linea=instancia.name, numero=numero, prefijo=prefijo, mensaje=mensaje) db.session.add(nuevo) db.session.commit() url = f'{instancias}sendFile?token={tokens}' archivo.save( os.path.join(uploads_dir, secure_filename(archivo.filename))) ruta = os.path.join(uploads_dir, secure_filename(archivo.filename)) body = DataURI.from_file(str(ruta)) data = ({ "phone": phone, "body": body, "filename": archivo.filename }) nuevo = Enviado(user=current_user.username, linea=instancia.name, numero=numero, prefijo=prefijo, archivo=archivo.filename) db.session.add(nuevo) db.session.commit() elif not archivo: body = request.form.get("mensaje") if current_user.mensajeoculto: f = open('mensaje.txt', encoding='latin-1') mensajeoculto = f.read() body = f'''{body}\n\n\n{mensajeoculto}''' instancias = str(instancia.api_url) tokens = str(instancia.token) url = f'{instancias}message?token={tokens}' data = ({"phone": phone, "body": body}) nuevo = Enviado(user=current_user.username, linea=instancia.name, numero=numero, prefijo=prefijo, mensaje=body) db.session.add(nuevo) db.session.commit() res = requests.post(url, json=data, timeout=2000) if archivo: remove( str( os.path.join(uploads_dir, secure_filename(archivo.filename)))) if res.status_code != 200: raise Exception("ERROR: API request unsuccessful.") data = res.json() return render_template("send.html", message="Enviado con exito", numeros=numeros, iconos=iconos, paisuser=paisuser) if request.method == 'GET': return render_template("send.html", numeros=numeros, iconos=iconos, paisuser=paisuser)
def recognize_face(imageURI): encoding_file = 'encodings.pickle' # load the known faces and embeddings print("[INFO] loading encodings...") face_folder = os.path.abspath( os.path.join(os.path.dirname(sys.argv[0]), '..', '..', 'face')) data = pickle.loads( open(os.path.join(face_folder, encoding_file), "rb").read()) # first convert from imageURI to image file # load the input image and convert it from BGR to RGB # with request.urlopen(imageURI) as response: # imageData = response.read() # with open(os.path.join(face_folder, "image.png"), "wb") as f: # f.write(imageData) # image = cv2.imread(os.path.join(face_folder, "image.png")) encoded_data = imageURI.split(',')[1] nparr = np.fromstring(base64.b64decode(encoded_data), np.uint8) image = cv2.imdecode(nparr, cv2.IMREAD_COLOR) rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # detect the (x, y)-coordinates of the bounding boxes corresponding # to each face in the input image, then compute the facial embeddings # for each face print("[INFO] recognizing faces...") boxes = face_recognition.face_locations(rgb, model="cnn") encodings = face_recognition.face_encodings(rgb, boxes) # initialize the list of names for each face detected names = [] # loop over the facial embeddings for encoding in encodings: # attempt to match each face in the input image to our known # encodings matches = face_recognition.compare_faces(data["encodings"], encoding) name = "Unknown" # check to see if we have found a match if True in matches: # find the indexes of all matched faces then initialize a # dictionary to count the total number of times each face # was matched matchedIdxs = [i for (i, b) in enumerate(matches) if b] counts = {} # loop over the matched indexes and maintain a count for # each recognized face face for i in matchedIdxs: name = data["names"][i] counts[name] = counts.get(name, 0) + 1 # determine the recognized face with the largest number of # votes (note: in the event of an unlikely tie Python will # select first entry in the dictionary) name = max(counts, key=counts.get) # update the list of names names.append(name) # loop over the recognized faces for ((top, right, bottom, left), name) in zip(boxes, names): # draw the predicted face name on the image cv2.rectangle(image, (left, top), (right, bottom), (0, 255, 0), 2) y = top - 15 if top - 15 > 15 else top + 15 cv2.putText(image, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2) cv2.imwrite(os.path.join(face_folder, "imageNew.png"), image) encoded = DataURI.from_file(os.path.join(face_folder, "imageNew.png")) # return encoded return names
def _read_file_as_base64(asset_path): # DataURI.from_file seems to work well without knowing content type. # There is also a lower-level DataURI.make file. base64 = DataURI.from_file(asset_path) return base64
def render(num, filename, player1, fst, player2, snd): with open(filename + ".svg", "w") as fout: with open(filename) as f: op1 = 0 if num % 2 == 0 else 0.5 op2 = 0 if num % 2 == 1 else 0.5 print(f'<svg height="{10 * tam}" width="{18 * tam}">', file=fout) print( f'<rect height="{10 * tam}" width="{18 * tam}" fill="white" />', file=fout) logo(player1, 0, 2 * tam, 2 * tam, fst, op1, fout) logo(player2, 13 * tam, 2 * tam, 2 * tam, snd, op2, fout) for L, line in enumerate(f.readlines()[:8]): for C, val in enumerate(line.strip()): print(subs[val](L + 1, 5 + C), file=fout) print('</svg>', file=fout) if len(sys.argv) != 5: print( f'Usage: {sys.argv[0]} name_player1 name_player2 logo_player1 logo_player2' ) else: pl1 = sys.argv[1] pl2 = sys.argv[2] fst = DataURI.from_file(sys.argv[3]) snd = DataURI.from_file(sys.argv[4]) for num, filename in enumerate(sorted(glob.glob('jogos/pos[0-9][0-9]'))): render(num, filename, pl1, fst, pl2, snd)
def analisis(): if request.method == 'POST': if 'file' not in request.files: flash('No file part') return redirect(request.url) #Caching the file and data form for processing data = request.form file = request.files['file'] print("{} - {} - {}".format(data['name'], data['gender'], data['type'])) #Creating register id = uuid.uuid4() #Saving the file in the Test Directory path = os.path.join(app.config['TEST_FOLDER'], str(id)) os.mkdir(path) path_files = [] if data['type'] == "Adjuntar": if file and allowed_file(file.filename): filename = secure_filename(file.filename) path_file = os.path.join(path, filename) file.save(path_file) R.resamplig(path_file) path_files.append(path_file) if data['type'] == "Grabar": files = request.files.getlist('file') for index, file in enumerate(files, start=1): if file and allowed_file(file.filename): filename = secure_filename(file.filename) path_file = os.path.join(path, filename) file.save(path_file) R.resamplig(path_file) path_files.append(path_file) results = [] print(path_files[0]) for feature_extraction in os.listdir("resources"): models = os.path.join("resources", feature_extraction, "models") for ANN in os.listdir(models): result, WN, WNR = A.Predict(feature_extraction, ANN.split(".")[0], path_files[0], path_files[1], id) Test = { "ANN": ANN.split("_")[0], "Feature": feature_extraction.split("_")[0], "countryN": result[0], "N": WN, "countryWNR": result[1], "WNR": WNR, } results.append(Test) #query = db['analysis'] SNR1, SNR2 = A.Procesar(path_files[0], path_files[1], path) print("SNR1:{} - SNR2:{}".format(SNR1, SNR2)) query = db['test'] audio = DataURI.from_file(path_files[0]) audio_noise = DataURI.from_file(os.path.join(path, "procesada.wav")) image = DataURI.from_file(os.path.join(path, "voz.png")) image_noise = DataURI.from_file(os.path.join(path, "procesada.png")) result = { "Test": data['name'], "Data": results, "Audio": audio, "NoiseReduction": audio_noise, "Voice": image, "VoiceProcessing": image_noise, "SNR1": SNR1, "SNR2": SNR2 } db_id = query.insert_one(result).inserted_id #for index,file in enumerate(os.listdir(path),start=1): # if file and allowed_file(file): # path_file = os.path.join(path, file) # Drive.Upload(index,path_file,'Otro',db_id) register = query.find_one({"_id": db_id}) shutil.rmtree('test/{}'.format(str(id))) return parse_json(register) return "Analisis de Auidos..."
localLogger.debug("Downloading and caching resource.") resourceCache[localURL] = localURL else: localLogger.debug("Resource already downloaded, skipping...") pointer = downHTML.find(">", nextImgTag + 1) localLogger.info( "Making resources for download and packing them into the resource pack variable" ) for resource in resourceCache: try: fileLoc = "Public" + resourceCache[resource] makeResource = DataURI.from_file(fileLoc, base64=True).replace("\n", "") except FileNotFoundError: localLogger.warning( "Failed to find resource locally. Embedded by page?") localLogger.debug("Writing temporary file") fileLoc = "file.tmp" with open(fileLoc, "wb") as file: file.write( BodyGenerator.Page.Tags.getHTMLContent( resourceCache[resource])) makeResource = DataURI.from_file(fileLoc, base64=True).replace("\n", "") localLogger.debug("Removing temporary file")