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 test_wrap(self): t = 'data:text/plain;charset=utf-8;base64,VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu' parsed = DataURI(t) self.assertEqual( parsed.wrap(), """data:text/plain;charset=utf-8;base64,VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3Z lciB0aGUgbGF6eSBkb2cu""")
def RecipeAdd(request): if request.method=='POST': try: body = json.loads(request.body.decode('utf-8')) details = body['data']['details'] primaryType = PrimaryType.objects.get(name=details['primaryType']) secondaryType = SecondaryType.objects.get(name=details['secondaryType']) season = None if details['season'] : season = Season.objects.get(name=season) # create the recipe recipe = Recipe.objects.create(name=details['name'],description=details['description'],prepTime=details['prepTime'],cookTime=details['cookTime'],primaryType=primaryType,secondaryType=secondaryType,season=season) recipe.filename = '{0:08d}'.format(recipe.id) recipe.save() # save the image if 'pdf' in details: image = DataURI(details['image']) if(len(image.data) <= 1000000): with open(BASE_DIR+'/build/assets/resources/'+recipe.filename+'.jpg', 'wb+') as file: file.write(image.data) with open(BASE_DIR+'/public/assets/resources/'+recipe.filename+'.jpg', 'wb+') as file: file.write(image.data) # save the pdf if 'pdf' in details: pdf = DataURI(details['pdf']) if(len(pdf.data) <= 1000000): with open(BASE_DIR+'/build/assets/resources/'+recipe.filename+'.pdf', 'wb+') as file: file.write(pdf.data) with open(BASE_DIR+'/public/assets/resources/'+recipe.filename+'.pdf', 'wb+') as file: file.write(pdf.data) # grant access to this new recipe in this account only account = AccountUser.objects.get(user=request.user).account AccountRecipe.objects.create(account=account,recipe=recipe) # create ingredients for ingredient in body['data']['ingredients']: try: accing = AccountIngredient.objects.get(account=account,ingredient__name=ingredient['ingredient']) accing.fresh = ingredient['fresh'] accing.save() ing = Ingredient.objects.get(accountingredient__account=account,name=ingredient['ingredient']) except ObjectDoesNotExist: ing,created = Ingredient.objects.get_or_create(name=ingredient['ingredient']) AccountIngredient.objects.create(account=account,ingredient=ing,fresh=ingredient['fresh'],supermarketCategory=ing.supermarketCategory,pantryCategory=ing.pantryCategory,stockcode=ing.stockcode,cost=ing.cost) mea = Measure.objects.get(name=ingredient['measurement']) RecipeIngredient.objects.create(recipe=recipe,quantity=ingredient['two'],quantity4=ingredient['four'],quantityMeasure=mea,ingredient=ing) return JsonResponse(dict(id=recipe.id)) except Exception as e: raise e return JsonResponse({'status':'false','message':str(e)}, status=500) response = HttpResponse() response['allow'] = "post, options" return response
def test_parse_invalid_charset(self): with self.assertRaises(exceptions.InvalidCharset): DataURI.make( mimetype='text/plain', charset='*garbled*', base64=True, data= 'VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu')
def test_parse_invalid_datauri(self): t = 'data:*garbled*;charset=utf-8;base64,VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu' with self.assertRaises(exceptions.InvalidDataURI): DataURI(t) t = 'data:text/plain;charset=*garbled*;base64,VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu' with self.assertRaises(exceptions.InvalidDataURI): DataURI(t)
def test_url_is_valid(self): content = BytesIO(DataURI(DATA_URI).data) # mock the response with patch('requests.get') as m: content = BytesIO(DataURI(DATA_URI).data).read() m.return_value.content = content m.return_value.status_code = 200 self.assertTrue( is_uri_valid_favicon('http://example.com.com/favicon.ico'))
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 test_update_item(client): # test update imgs1 = [DataURI.from_file(f'tests/images/{i}.jpg') for i in range(3, 5)] imgs2 = [DataURI.from_file(f'tests/images/{i}.jpg') for i in range(9, 11)] imgs3 = [DataURI.from_file(f'tests/images/{i}.jpg') for i in range(15, 16)] item = { "category": 2, "currency": "GHS", "images": imgs1, "tags": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], "options": [{ "name": "opt1", "required": True, "values": [{ "images": imgs2, }, { "images": imgs3, }] }] } item_new = Items.select(Items.id).order_by(Items.id.desc()).get() payload = { "111": { "upload_item": { "item_details": item, "seller_id": 1, "update": True, "id": item_new.id }, "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 test_from_file_charset(self): filename = os.path.join(TEST_DIR, 'test_file.txt') parsed = DataURI.from_file(filename, charset='us-ascii') self.assertEqual(parsed.data, b'This is a message.\n') self.assertEqual(parsed.text, 'This is a message.\n') self.assertEqual(parsed.charset, 'us-ascii') filename = os.path.join(TEST_DIR, 'test_file_ebcdic.txt') parsed = DataURI.from_file(filename, charset='cp500') self.assertEqual( parsed.data, b'\xe3\x88\x89\xa2@\x89\xa2@\x81@\x94\x85\xa2\xa2\x81\x87\x85K%') self.assertEqual(parsed.text, 'This is a message.\n') self.assertEqual(parsed.charset, 'cp500')
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 check_add(self, item): if not 'file' in item: return if ';' in item['file']['mime']: item['file']['mime'] = item['file']['mime'].split(";")[0] story = { 'name' : item['title'], 'auth' : item['author'], 'tags' : item['tags'], 'desc' : item['desc'], 'ul_date' : item['uldate'], 'fname' : item['file']['name'], 'file' : DataURI.make(mimetype=item['file']['mime'], charset=None, base64=True, data=item['file']['file']), } # print(item['tags']) # print(item['file']) assert 'name' in story assert 'auth' in story assert 'fname' in story assert 'file' in story assert 'desc' in story assert 'tags' in story with app.app.test_request_context(): app.api_handlers.addStory({'story' : story})
def dynamic(command): if flag == 1: postData = request.form if command == "tts": response = ttsService.synthesize( postData["text"], accept='audio/mp3', voice=postData["lang"]).get_result() return jsonify({ "blobB64": "data:audio/mpeg;base64,{}".format( base64.b64encode(response.content).decode("utf-8")) }) elif command == "langlist": voices = ttsService.list_voices().get_result() result = [] for voice in voices["voices"]: result.append({ "text": voice["description"], "value": voice["name"] }) return jsonify(result) elif command == "modellist": models = sttService.list_models().get_result() result = [] for model in models["models"]: result.append({ "text": model["description"], "value": model["name"] }) return jsonify(result) elif command == "stt": uri = DataURI(postData["blobB64"]) response = sttService.recognize( audio=uri.data, content_type=uri.mimetype, word_alternatives_threshold=0.9, keywords=[ 'yes', 'no', 'option', 'one', 'two', 'three', 'four' ], keywords_threshold=0.9).get_result() if len(response['results']) > 0: return jsonify({ "text": response['results'][0]["alternatives"][0]["transcript"] }) else: return jsonify({"text": "nothing"}) elif command == "storylist": stories = glob.glob("stories/*.json") result = [] for story in stories: with open(story, "rb") as storyFile: storyJSON = json.load(storyFile) result.append({ "text": storyJSON["header"]["title"]["text"], "value": os.path.basename(story) }) return jsonify(result) else: return jsonify({"error": "keyError"})
def download_or_create_favicon(favicon: str, domain: str) -> Image: """ :param favicon: :param domain: :return: """ file_path = os.path.dirname(os.path.realpath(__file__)) generic_favicon = "{}/generic_favicon.png".format(file_path) # handle the case for data: URIs if favicon.startswith('data:image'): uri = DataURI(favicon) data = BytesIO(uri.data) # Favicon was determined to be missing, so use a generic icon elif favicon == 'missing': data = generic_favicon # Looks like a normal favicon url, lets go get it elif favicon.startswith('http'): r = download_remote_favicon(favicon) data = BytesIO(r) if r else generic_favicon # return make_image(domain) img = Image.open(data) img = img.convert('RGB') if img.mode == 'CMYK' else img return img
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 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 svg_marker(text, color='white', background_color='black', direction='se'): text_style = f'font-size:13px;font-family:Roboto;fill:{color};' text_width = int(round(_text_width(text, text_style))) rect_width = text_width + 24 rect_height = 26 translate_x, translate_y, arrow_width, origin_x, origin_y, arrow, = directions[direction](rect_width / 2, rect_width + 8) img_width = rect_width + 2 + arrow_width img_height = rect_height + 2 + 8 view_box = f'-{translate_x} -{translate_y} {img_width} {img_height}' image = ( f'<?xml version="1.0" ?>' f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="{view_box}" width="{img_width}px" height="{img_height}px" >' f'<rect width="{rect_width}" height="{rect_height}" rx="3" ry="3" fill="{background_color}"></rect>' f'<path d="{arrow}" fill="{background_color}"></path>' f'<text y="18" x="12" style="{text_style}">{text}</text>' f'</svg>' ) # NOQA E131 return { 'icon': { 'url': str(DataURI.make('image/svg+xml', charset='utf8', base64=True, data=image)), 'anchor': {'x': origin_x + 1, 'y': origin_y + 1}, }, 'shape': { 'type': 'rect', 'coords': (translate_x, translate_y, rect_width + translate_x, rect_height + translate_y), } }
def selenium_process_html(html_content, output): chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('headless') capabilities = { 'browserName': 'chrome', 'javascriptEnabled': True, } capabilities.update(chrome_options.to_capabilities()) driver = webdriver.Remote(settings.SELENIUM_URL, desired_capabilities=capabilities) calculated_print_options = { 'landscape': False, 'displayHeaderFooter': False, 'printBackground': True, 'preferCSSPageSize': True, } made = DataURI.make('text/html', charset='utf-8', base64=True, data=html_content) driver.get(made) result = send_devtools(driver, "Page.printToPDF", calculated_print_options) with open(output, 'wb') as file: file.write(base64.b64decode(result['data'])) driver.quit() return True
def test_valid_request(self): json_data = { 'device_token': self.tokenDevice, 'files': ["test_file.txt"], 'conversation_id': self.conversation.id } response = self.api.post('/device/message/send', data=json.dumps(json_data), content_type='application/json') response_json = json.loads(response.data) assert response.status_code == 200 assert response_json['success'] is True assert len(response_json['media_list']) == 1 headers = { 'content-type': 'multipart/form-data', 'Authorization': self.tokenDevice } data = {'file': (io.BytesIO(b"device sent a file"), 'test_file.txt')} media_id = response_json['media_list'][0]['id'] response = self.api.post('/media/upload/' + str(response_json['media_list'][0]['id']), data=data, headers=headers) response_json = json.loads(response.data) assert response_json["success"] is True assert os.path.exists('user_files' + os.path.sep + 'conversation_' + str(self.conversation.id) + os.path.sep) json_data = {"device_token": self.tokenDevice, "media_id": media_id} response = self.api.post('/media/retrieve', data=json.dumps(json_data), content_type='application/json') response_json = json.loads(response.data) response_file = DataURI(response_json['data']) assert response_json['success'] assert response_file.data == b"device sent a file"
def test_repr(self): t = 'data:text/plain;charset=utf-8;base64,VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu' uri = DataURI(t) self.assertEqual( repr(uri), "DataURI('data:text/plain;charset=utf-8;base64,VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu')" )
def get(self, request, pk, pointer, model_class=None, field_name=None): """ :param request: :param pk: the pk of the instance :param pointer: the json pointer of the image. Ex: "people/image", "people/0/image", etc. :param model_class: the model that holds the JSON field :param field_name: the JSON-field name :return: HttpResponse with the image Base view to serve an URI-stored (in a JSON field) image as a file. Example usage in urls.py: re_path( r"some/path/(?P<pk>\d+)/(?P<pointer>.+)/", URIImageAsFileView.as_view(), kwargs={"model_class": MyModel, "field_name": "my_json_field"}, ), """ obj = get_object_or_404(model_class or self.model_class, pk=pk) data = getattr(obj, field_name or self.field_name) pointer = "/{}".format(pointer) try: data = resolve_pointer(data, pointer) uri = DataURI(data) return HttpResponse(uri.data, content_type=uri.mimetype) except (InvalidDataURI, JsonPointerException): raise Http404("Image not found")
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 _localize_data_uri(self, locout, source, dest): """Localizes an entry where the source is a data: URI""" try: uri = DataURI(source) except ValueError: locout.write('Could not parse "{}" as a data URI: {}\n'.format( source, str(e))) return False try: with open(dest, 'w+', buffering=1) as destout: try: uri_data = uri.data.decode() except AttributeError: uri_data = uri.data destout.write(uri_data) locout.write('{}: wrote {} bytes\n'.format( dest, len(uri_data))) except IOError as e: locout.write('{}: I/O error({0}): {1}\n'.format( dest, e.errno, e.strerror)) return False except: locout.write('{}: unexpected error: {}\n'.format( sys.exc_info()[0])) return False return True
def get_speaker_image(self, data): image_b64 = data.get('image', None) if not image_b64: return None image = DataURI(image_b64) return NamedBlobImage(data=image.data, filename=image.name, contentType=image.mimetype)
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 post_sourceimage(request): data = json.loads(request.body.decode('utf-8') or "{}") uri = DataURI(data.pop('src')) f = ContentFile(uri.data, name=uri.name) si = SourceImage(uploaded_by=request.user) si.src.save(f.name, f) si.save() FILES = {'src': f} return JsonResponse({'sourceimage_id': si.id})
def test_url_is_valid(self): url = 'http://example.com.com/favicon.ico' # mock the response with patch('requests.get') as m: content = DataURI(DATA_URI).data m.return_value.content = content m.return_value.status_code = 200 image = self.favicon.download_remote_favicon(url) self.assertEqual(image, content)
def transcribe(uri): # Parses a URI and gets the encoded data string out data = DataURI(uri).data image = types.Image(content=data) response = client.document_text_detection(image) if response.text_annotations: return response.text_annotations[0].description.replace('\n', ' ') else: return "No Text"
def __init__(self, uri: PlasterURL): self.uri = uri self.data_uri = DataURI("data:" + uri.path) self.parser = DataUriConfigParser(self.data_uri) # if self.data_uri.co if self.data_uri.mimetype == "application/x-gzip": self.parser.read_string( gzip.decompress(self.data_uri.data).decode('utf-8')) else: self.parser.read_string( self.data_uri.data.decode(self.data_uri.charset or 'utf-8'))
def get_vitessce_conf(self, entity): if ('files' not in entity or 'data_types' not in entity): # Would a default no-viz config be better? return {} if self.is_mock: cellsData = json.dumps( {'cell-id-1': { 'mappings': { 't-SNE': [1, 1] } }}) cellsUri = DataURI.make('text/plain', charset='us-ascii', base64=True, data=cellsData) token = 'fake-token' return { 'description': 'DEMO', 'layers': [ { 'name': 'cells', 'type': 'CELLS', 'url': cellsUri, 'requestInit': { 'headers': { 'Authorization': 'Bearer ' + token } } }, ], 'name': 'Linnarsson', 'staticLayout': [ { 'component': 'scatterplot', 'props': { 'mapping': 'UMAP', 'view': { 'zoom': 4, 'target': [0, 0, 0] } }, 'x': 0, 'y': 0, 'w': 12, 'h': 2 }, ] } else: vitessce = Vitessce(entity=entity, nexus_token=self.nexus_token) return vitessce.conf
def parameters(self, line): self.driver.implicitly_wait(5) self.findbyxpath( '/html/body/div[2]/div/div[1]/ul/li[8]/a') # xpath para RAW button self.findbyxpath( '//*[@id="s1"]') # xpath para definir tamanho e cor button txtarea = self.driver.find_element_by_id('text') txtarea.clear() txtarea.send_keys(str(line).strip( )) # line: string - enviada a linha do arquivo texto para o campo # para geração do qr code na web tamanho_imagem = self.driver.find_element_by_id('qrsi') self.driver.execute_script("arguments[0].setAttribute('value','200')", tamanho_imagem) self.findbyxpath( '//*[@id="borderr"]/label[2]') # xpath para tamanho da fronteira self.findbyxpath( '//*[@id="errr"]/label[4]') # xpath para correcao de cor self.findbyxpath( '//*[@id="radiusr"]/label[2]') # xpath para tamanho do raio self.findbyxpath('//*[@id="s2"]') # xpath para definir logotipo self.findbyxpath( '//*[@id="labelmode"]/label[3]') # xpath para definir foto sel_photo = self.driver.find_element_by_id('image') sel_photo_path = 'C:/dev/qrcode/img/tabelionato_xisto.jpeg' sel_photo.send_keys(sel_photo_path) self.findbyxpath( '//*[@id="fontsize"]/label[4]') # xpath para dimensoes self.driver.implicitly_wait(5) imagem = (line.split('=')[1].strip() ) + '.png' # separando a URL e o numero para # o nome do arquivo de imagem(PNG) param = "arguments[0].setAttribute('download','" + imagem + "')" self.driver.implicitly_wait(5) baixa_qrcode = self.driver.find_element_by_id('dlbtn') self.driver.execute_script(param, baixa_qrcode) sleep(2) baixa_qrcode.click() """ Salva imagem com URI Basecode64.""" url = baixa_qrcode.get_property('href') uri = DataURI(url) with open("C:/dev/qrcode/qrcodes_imgs/" + imagem, 'wb') as f: f.write(uri.data)
def login(): if request.method == 'POST': img_data = request.json['data'] uri = DataURI(img_data) fd = open("tmp.png", 'wb') fd.write(uri.data) fd.close() res = pre('tmp.png') print(res) return jsonify({'p': str(res[0]), 'np': str(res[1])}) else: return "GET Eight"