async def predict_image(model_name: str, input_data: UploadFile = File(...)): """ Draws bounding box(es) on image and returns it. :param model_name: Model name :param input_data: Image file :return: Image file """ try: output = await dl_service.run_model(model_name, input_data, draw=True, predict_batch=False) error_logging.info('request successful;' + str(output)) return FileResponse("/main/result.jpg", media_type="image/jpg") except ApplicationError as e: error_logging.warning(model_name + ';' + str(e)) return ApiResponse(success=False, error=e) except Exception as e: error_logging.error(model_name + ' ' + str(e)) return ApiResponse(success=False, error='unexpected server error')
async def default_page(request, call_next): response = await call_next(request) if response.status_code == 404: if STATIC_DIR: return FileResponse(path.join(STATIC_DIR, "index.html")) else: async with httpx.AsyncClient() as client: remote_resp = await client.get( str(request.url.replace(port=8080)), headers=dict(request.headers) ) return StreamingResponse( remote_resp.aiter_bytes(), headers=remote_resp.headers, status_code=remote_resp.status_code, media_type=remote_resp.headers.get("content-type"), ) return response
async def get_detour(file: UploadFile = File(...)): try: os.remove("output.png") except: pass img = Image.open(file.file) # img is from PIL.Image.open(path) img = img.convert('RGB') mask = infer(np.asarray(img), net) empty = Image.new("RGBA", img.size, 0) img_detour = Image.composite(img, empty, mask.convert("L")) img_detour.save("output.png") headers = { "Content-Type": 'image', "Content-Disposition": 'attachment; filename="{}"'.format("output.png") } response = FileResponse("output.png", headers=headers) return response
async def __call__(self, receive: Receive, send: Send) -> None: if self.check_directory is not None: await self.check_directory_configured_correctly() try: stat_result = await aio_stat(self.path) except FileNotFoundError: response = PlainTextResponse("Not Found", status_code=404) # type: Response else: mode = stat_result.st_mode if not stat.S_ISREG(mode): response = PlainTextResponse("Not Found", status_code=404) else: response = FileResponse(self.path, stat_result=stat_result) await response(receive, send)
async def download_product( product_slug: str, ext: str, user: User = Depends(get_current_user_by_cookie), db: Session = Depends(db_session) ) -> FileResponse: """Download a product file if user have bought it.""" # Check if product exists product = db.query(Product).filter(Product.slug == product_slug).first() if not product: raise HTTPException(status_code=404, detail="No product found") # Has the user bought it before? if product not in get_user_products(db, user): raise HTTPException(status_code=403, detail="Doesn't belong to you") return FileResponse(join(ROOT, product_slug, product_slug + "." + ext))
def file_response( self, full_path: str, stat_result: os.stat_result, scope: Scope, status_code: int = 200, ) -> Response: method = scope["method"] request_headers = Headers(scope=scope) response = FileResponse(full_path, status_code=status_code, stat_result=stat_result, method=method) if self.is_not_modified(response.headers, request_headers): return NotModifiedResponse(response.headers) return response
async def get_response(self, path: str, scope: Scope) -> Response: """ Returns an HTTP response, given the incoming path, method and request headers. """ if scope["method"] not in ("GET", "HEAD"): raise HTTPException(status_code=405) try: full_path, stat_result = await anyio.to_thread.run_sync( self.lookup_path, path) except PermissionError: raise HTTPException(status_code=401) except OSError: raise if stat_result and stat.S_ISREG(stat_result.st_mode): # We have a static file to serve. return self.file_response(full_path, stat_result, scope) elif stat_result and stat.S_ISDIR(stat_result.st_mode) and self.html: # We're in HTML mode, and have got a directory URL. # Check if we have 'index.html' file to serve. index_path = os.path.join(path, "index.html") full_path, stat_result = await anyio.to_thread.run_sync( self.lookup_path, index_path) if stat_result is not None and stat.S_ISREG(stat_result.st_mode): if not scope["path"].endswith("/"): # Directory URLs should redirect to always end in "/". url = URL(scope=scope) url = url.replace(path=url.path + "/") return RedirectResponse(url=url) return self.file_response(full_path, stat_result, scope) if self.html: # Check for '404.html' if we're in HTML mode. full_path, stat_result = await anyio.to_thread.run_sync( self.lookup_path, "404.html") if stat_result and stat.S_ISREG(stat_result.st_mode): return FileResponse( full_path, stat_result=stat_result, method=scope["method"], status_code=404, ) raise HTTPException(status_code=404)
def get_parcellation_map_for_space(atlas_id: str, space_id: str): """ Returns all parcellation maps for a given space id. """ validate_and_return_atlas(atlas_id) space = validate_and_return_space(space_id) valid_parcs = [p for p in siibra.parcellations if p.supports_space(space)] if len(valid_parcs) == 1: maps = [valid_parcs[0].get_map(space)] filename = get_file_from_nibabel(maps[0], 'maps', space) return FileResponse(filename, filename=filename) else: raise HTTPException( status_code=501, detail= f'space with id {space_id} has multiple parc, not yet implemented') maps = [p.get_map(space) for p in valid_parcs] files = [] mem_zip = io.BytesIO() label_index = 0 for map in maps: files.append( get_file_from_nibabel(map, 'map-{}'.format(label_index), space)) label_index = label_index + 1 with zipfile.ZipFile(mem_zip, mode="w", compression=zipfile.ZIP_DEFLATED) as zf: for f in files: zf.write(f) print(zf.namelist()) mem_zip.seek(0) response = StreamingResponse(iter([mem_zip.getvalue()]), media_type="application/x-zip-compressed") response.headers[ "Content-Disposition"] = 'attachment; filename=maps-{}.zip'.format( space.name.replace(' ', '_')) return response raise HTTPException( status_code=404, detail='Maps for space with id: {} not found'.format(space_id))
async def sign_pdf(filecert: UploadFile = File(...), filepdf: UploadFile = File(...), sigflags: str = Form(...), contact: str = Form(...), location: str = Form(...), reason: str = Form(...)): try: suffix = Path(filecert.filename).suffix with NamedTemporaryFile(delete=False, suffix=suffix) as tmp: shutil.copyfileobj(filecert.file, tmp) cert_tmp_path = Path(tmp.name) finally: filecert.file.close() try: suffix = Path(filepdf.filename).suffix with NamedTemporaryFile(delete=False, suffix=suffix) as tmp: shutil.copyfileobj(filepdf.file, tmp) pdf_tmp_path = Path(tmp.name) finally: filepdf.file.close() date = datetime.datetime.utcnow() - datetime.timedelta(hours=12) date = date.strftime('%Y%m%d%H%M%S+00\'00\'') dct = { 'sigflags': sigflags, 'contact': contact, 'location': location, 'signingdate': date, 'reason': reason, } with open(cert_tmp_path, 'rb') as fp: p12 = pkcs12.load_key_and_certificates(fp.read(), b'1234', backends.default_backend()) datau = open(pdf_tmp_path, 'rb').read() datas = cms.sign(datau, dct, p12[0], p12[1], p12[2], "sha256") with open(pdf_tmp_path, 'wb') as fp: fp.write(datau) fp.write(datas) return FileResponse(path=pdf_tmp_path, filename=pdf_tmp_path.name)
def get_annuluspressure_image(well: str, connection: str, cmap: str = 'inferno', vmin: float = None, vmax: float = None, api_key: APIKey = Depends(get_api_key)): sl = SimulationLoader(f'{simulation_dir}/{well}/{connection}') pressure_per_meter = sl.fluiddef().iloc[0][0] * 9.81 * 1e-5 data = relative_simulation_data(sl.well_path(), sl.annuluspressure().transpose(), pressure_per_meter) with tempfile.NamedTemporaryFile(mode='w+b', suffix='.png', delete=False) as image: plt.imsave(image.name, data, cmap=cmap, vmin=vmin, vmax=vmax) return FileResponse(image.name, media_type='image/png', headers={'Cache-Control': 'max-age=120'})
def show_attachment( account_name: str = fPath(..., regex=safe_account_name_regex), file_id: int = fPath(...), filename: Optional[str] = Query(None), ctx: Context = Depends(), ): userdir = FileSeries(attachments_dir / account_name) path = userdir.file_path(file_id) if path.exists(): media_type = guess_type(userdir.file_path(file_id).name)[0] return FileResponse( str(path), media_type=media_type, filename=filename, headers={'Cache-Control': f'max-age={7*24*3600}'}, ) else: raise HTTPException(status.HTTP_404_NOT_FOUND)
def download(request: Request, job_id: str, ordinal: int, file_path: str) -> FileResponse: """ Sends a file from given `file_path`. This path should come from results of one of the previous searches. This endpoint needs `job_id` that found the specified file, and `ordinal` (index of the file in that job), to ensure that user can't download arbitrary files (for example "/etc/passwd"). """ userid = request.client.host db.bump_quota(userid, RateLimitType.file_download, 1) if not db.job_contains(JobId(job_id), ordinal, file_path): raise NotFound("No such file in result set.") attach_name, ext = os.path.splitext(os.path.basename(file_path)) return FileResponse(file_path, filename=attach_name + ext + "_")
def get_todays_image(session: Session = Depends(generate_session), group_name: str = "Home"): """ Returns the image for todays meal-plan. """ group_in_db: GroupInDB = db.groups.get(session, group_name, "name") recipe = get_todays_meal(session, group_in_db) if recipe: recipe_image = recipe.image_dir.joinpath( image.ImageOptions.ORIGINAL_IMAGE) else: raise HTTPException(status.HTTP_404_NOT_FOUND) if recipe_image: return FileResponse(recipe_image) else: raise HTTPException(status.HTTP_404_NOT_FOUND)
def get_hd2_processed_files(num_of_files: int = Query( -1, description="Keep -1 to get all hd2/processed data", )): file_distributor = File_Distributor() file_response = file_distributor.get_hd2_processed( num_of_files=num_of_files) if file_response == -1: return Response(status_code=404, content="hd2/processed folder is empty") if file_response == 0: return Response(status_code=403, content="Invalid value for num_of_files") return FileResponse(file_response, media_type='application/octet-stream', filename=ntpath.basename(file_response))
async def get_data(file_id: int, db: Database = Depends()): query = """ select root_path || '/' || rel_path as file, size from file natural join file_location natural join file_storage_root where file_id = $1 """ file_rec = await db.fetch_one(query, [file_id]) filename = file_rec['file'] if not os.path.exists(filename): raise HTTPException(status_code=404, detail="File not found on disk") return FileResponse(file_rec['file'])
def display( self, request: Request, trans=DependsOnTrans, history_id: EncodedDatabaseIdField = HistoryIDPathParam, history_content_id: EncodedDatabaseIdField = DatasetIDPathParam, preview: bool = Query( default=False, description= ("Whether to get preview contents to be directly displayed on the web. " "If preview is False (default) the contents will be downloaded instead." ), ), filename: Optional[str] = Query( default=None, description="TODO", ), to_ext: Optional[str] = Query( default=None, description= ("The file extension when downloading the display data. Use the value `data` to " "let the server infer it from the data type.")), raw: bool = Query( default=False, description= ("The query parameter 'raw' should be considered experimental and may be dropped at " "some point in the future without warning. Generally, data should be processed by its " "datatype prior to display."), ), ): """Streams the preview contents of a dataset to be displayed in a browser.""" extra_params = get_query_parameters_from_request_excluding( request, {"preview", "filename", "to_ext", "raw"}) display_data, headers = self.service.display(trans, history_content_id, history_id, preview, filename, to_ext, raw, **extra_params) if isinstance(display_data, IOBase): file_name = getattr(display_data, "name", None) if file_name: return FileResponse(file_name, headers=headers) elif isinstance(display_data, ZipstreamWrapper): return StreamingResponse(display_data.response(), headers=headers) return StreamingResponse(display_data, headers=headers)
async def download_artifact(request): run_uuid = request.path_params["run_uuid"] filepath = request.query_params.get("path", "") stream = to_bool(request.query_params.get("stream"), handle_none=True) if not filepath: return Response( content="A `path` query param is required to stream a file content", status_code=status.HTTP_400_BAD_REQUEST, ) subpath = "{}/{}".format(run_uuid, filepath).rstrip("/") archived_path = await download_file(subpath=subpath) if not archived_path: return Response( content="Artifact not found: filepath={}".format(archived_path), status_code=status.HTTP_404_NOT_FOUND, ) if stream: return FileResponse(archived_path) return redirect(archived_path)
async def make( font_size: int = Form(6), text: str = Form("我喜欢你"), file: UploadFile = File(...), ): if file.content_type[:5] != "image": return {"msg": "请上传图片文件!"} contents = await file.read() img_path = "./imgs/%s.png" % repr(uuid.uuid4()) with open(img_path, 'wb') as f: f.write(contents) img_raw = Image.open(img_path) img_array = img_raw.load() img_new = Image.new("RGB", img_raw.size, (0, 0, 0)) draw = ImageDraw.Draw(img_new) font = ImageFont.truetype('./imgs/SIMKAI.TTF', font_size) def character_generator(text): while True: for i in range(len(text)): yield text[i] ch_gen = character_generator(text) for y in range(0, img_raw.size[1], font_size): for x in range(0, img_raw.size[0], font_size): draw.text((x, y), next(ch_gen), font=font, fill=img_array[x, y], direction=None) img_new.convert('RGB').save(img_path) # 先创建文件,返回成功后删除;未找到流式文件方法 async def rmf(): os.remove(img_path) return FileResponse(img_path, background=rmf)
async def download_file(history_id: str): if history_id in HistoriesCollection.get_ids(): filename = Repository.get_history_by_id(history_id).get('file_name') if filename not in os.listdir(CLEARED_DIR): file_uploader = FileUploader() if filename in file_uploader.list_blobs(): file_uploader.download_file(filename) else: return {'description': "File not found", 'result': True} shutil.move(filename, "app/disease_storage/") return FileResponse('app/disease_storage/' + filename, media_type='application/octet-stream', filename=filename) return {'description': 'Can\'n found history by this id', 'result': False}
async def get_file(q: List[str] = Query(None)): ''' Pass path to function. Returns folders and files. ''' query_items = {"q": q} if query_items["q"]: entry = PATH + "/".join(query_items["q"]) else: entry = PATH try: if os.path.isfile(entry): return FileResponse(entry) else: return "Not a file." except: return "Not a path."
def form_post(request: Request, num: int = Form(...), multiply_by_2: bool = Form(False), action: str = Form(...)): if action == 'convert': result = spell_number(num, multiply_by_2) return templates.TemplateResponse('download.html', context={ 'request': request, 'result': result, 'num': num }) elif action == 'download': # Requires aiofiles result = spell_number(num, multiply_by_2) filepath = save_to_text(result, num) return FileResponse(filepath, media_type='application/octet-stream', filename='{}.txt'.format(num))
async def download_trained_model_data(training_id: str): """ Allows user to download a .zip file containing a SavedModel object. This will have the trained weights from the remote training job, and the results may be loaded back into Tensorflow2. Only admins are able to download training results, regardless of who submits the training jobs initially. :param training_id: Training ID of job to download :return: application/octet-stream with .zip file containing SavedModel object """ result = get_training_result_by_training_id(training_id) if not result: return { 'status': 'failure', 'detail': 'Unable to find training result with specified ID.', 'training_id': training_id } if not result.save: return { 'status': 'failure', 'detail': 'No model files available. User did not request results saved in training request.', 'training_id': training_id } if not result.complete: return { 'status': 'success', 'detail': 'Training job is currently processing. Please check back later to download files.', 'training_id': training_id } if not os.path.exists('/app/training_results/' + training_id + '.zip'): return { 'status': 'failure', 'detail': 'Unable to locate trained model files.', 'training_id': training_id } return FileResponse('/app/training_results/' + training_id + '.zip', media_type='application/octet-stream', filename='Trained Model ' + training_id + '.zip')
def productsExportToPdf(response: Response, Authorze: AuthJWT = Depends()): Authorze.jwt_required() try: pdf = PdfMaker(format='A4') pdf.set_title("Products List") pdf.add_page() validatedObjects = get_all_prodcuts_for_fileUpload() pdf.makeData(validatedObjects) pdf.output("productslist.pdf") return FileResponse("productslist.pdf", media_type='application/octet-stream', filename="productslist.pdf") except Exception as exc: response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR ProjectUtils.print_log_msg(exc, ProjectUtils.EXCEPTION) return { Statuses.status_code: Statuses.HTTP_500_INTERNAL_SERVER_ERROR, Statuses.status: Statuses.exception, Statuses.description: str(exc) }
def archive_download( self, trans: ProvidesHistoryContext = DependsOnTrans, id: EncodedDatabaseIdField = HistoryIDPathParam, jeha_id: Union[EncodedDatabaseIdField, LatestLiteral] = JehaIDPathParam, ): """ See ``PUT /api/histories/{id}/exports`` to initiate the creation of the history export - when ready, that route will return 200 status code (instead of 202) and this route can be used to download the archive. """ jeha = self.service.get_ready_history_export(trans, id, jeha_id) media_type = self.service.get_archive_media_type(jeha) file_path = self.service.get_archive_download_path(trans, jeha) return FileResponse( path=file_path, media_type=media_type, filename=jeha.export_name, )
async def avatar(name: str, size: int = 64, background: str = None, color: str = None): """ Generate your image using your name and other attributes here. Size: Up to 1000, any more and you get defaulted to 64. Colors: Should be in hex codes, but without the #. """ task = BackgroundTask(store_hits_per_day) image = get_image(name, size, background, color) if type(image) is str: return FileResponse(image, media_type='image/png', background=task) else: return StreamingResponse(image, media_type='image/png', background=task)
async def index(request: Request, token: str = Depends(oauth2_scheme), file: UploadFile = File(...)): dir_path = "static/images/upload" output_path = "static/images/result" # Check the existence and format of the file if not file: print("File doesn't exist!") return if not allowed_file(file.filename): print(file.filename + ": File not allowed!") return # save file if os.path.isdir(dir_path): shutil.rmtree(dir_path) os.mkdir(dir_path) filename = secure_filename(file.filename) filepath = open(os.path.join(dir_path, filename), "wb+") fileobj = file.file shutil.copyfileobj(fileobj, filepath) # Yolo Config Dict config = { "weights": "weights/last.pt", "source": dir_path, "output": output_path, "img_size": 640, "conf_thres": 0.4, "iou_thres": 0.5, "device": "cpu", "view_img": False, "save_txt": "store_true", "classes": "", "agnostic_nms": "store_true", "augment": "store_true", "update": False, } # Yolo Detect Objects detect(config) return FileResponse(os.path.join(output_path, filename))
async def analyze(request): data = await request.form() contents = await data["upload_file"].read() root = json.loads(contents.decode('utf-8')) itemUrl = root["imagenUrl"] data_dir = await download_images(itemUrl) ''' data_path = path/'dataset_test.rar' await download_file(itemUrl, data_path) # download data from Dropbox Archive(data_path).extractall(".") #rar = rarfile.RarFile(data_path) #rar.extractall() # r=root, d=directory, f=files for r, d, f in os.walk(path/'reto_deep_learning'): for directory in d: if directory == 'train_img': data_dir = os.path.join(r, directory) ''' #print(learn) dataloaders_dict, class_to_idx, imgs_filename = dataLoaders( input_size, data_dir) predictions = test_model(learn[0], dataloaders_dict, learn[1], class_to_idx) #print(imgs_filename['test'].imgs) with open('output.csv', mode='w') as output_preds: output_preds = csv.writer(output_preds, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) output_preds.writerow(['image_id', 'label']) for i in range(1, len(predictions) + 1): output_preds.writerow([ os.path.split(str(imgs_filename['test'].imgs[i - 1][0]))[1], predictions[i - 1] ]) #return JSONResponse({'result': str(f'{len(predictions)} images were processed')}) return FileResponse(path='output.csv', filename='output.csv')
def returnFile(filename, model_dir, data_dir, isSavedModel=False): with zipfile.ZipFile(model_dir + '/retZip.zip', 'w') as zip: # If the return type is savedmodel, recursively add the files in the savedmodel directory. if (isSavedModel): for dirname, subdirs, files in os.walk(model_dir + '/' + filename): # We use relpath to remove the /tmp/xxxxx/ from the archive paths. zip.write(dirname, os.path.relpath(dirname, model_dir)) for filename in files: zip.write( os.path.join(dirname, filename), os.path.relpath(os.path.join(dirname, filename), model_dir)) else: zip.write(model_dir + '/' + filename, filename) zip.write(model_dir + '/labels.txt', 'labels.txt') global instanceReady instanceReady = True return FileResponse(model_dir + '/retZip.zip', media_type='application/octet-stream', filename='converted_model.zip')
async def download_asset(genome: str, asset: str, tag: str = None): """ Returns an archive. Requires the genome name and the asset name as an input. Optionally, 'tag' query parameter can be specified to get a tagged asset archive. Default tag is returned otherwise. """ tag = tag or rgc.get_default_tag(genome, asset) # returns 'default' for nonexistent genome/asset; no need to catch file_name = "{}__{}{}".format(asset, tag, ".tgz") if CFG_REMOTE_URL_BASE_KEY in rgc and rgc[CFG_REMOTE_URL_BASE_KEY] is not None: _LOGGER.info("remote url base: '{}'".format(rgc[CFG_REMOTE_URL_BASE_KEY])) asset_url = "{base}/{genome}/{file_name}".format(base=rgc[CFG_REMOTE_URL_BASE_KEY], genome=genome, file_name=file_name) _LOGGER.info("redirecting to URL: '{}'".format(asset_url)) return RedirectResponse(asset_url) asset_file = "{base}/{genome}/{file_name}".format(base=BASE_DIR, genome=genome, file_name=file_name) _LOGGER.info("serving asset file: '{}'".format(asset_file)) if os.path.isfile(asset_file): return FileResponse(asset_file, filename=file_name, media_type="application/octet-stream") else: msg = MSG_404.format("asset ({})".format(asset)) _LOGGER.warning(msg) raise HTTPException(status_code=404, detail=msg)
async def get_graph(graph_type: Types): data = None if graph_type == Types.age: data = agegraph() if graph_type == Types.gender: data = gendergraph() if graph_type == Types.marital: data = maritalgraph() if graph_type == Types.language: data = languagegraph() if graph_type == Types.state: data = stategraph() if graph_type == Types.country: data = countrygraph() if data is not None: filename = str(uuid4()) + ".png" data.savefig(os.path.join("graph_output", filename)) return FileResponse(os.path.join("graph_output", filename)) else: return {"message": "Something has went wrong"}