def image_endpoint(): """ returns an image """ # read file with open("image.png", "rb") as file: image_bytes = file.read() return StreamingResponse(io.BytesIO(image_bytes), media_type="image/png")
async def get_one_sample(): global PAYLOAD_QUEUE if len(PAYLOAD_QUEUE) == 0: return { 'events': [], 'file': None } last_sample = PAYLOAD_QUEUE[0] item_file = last_sample[FILE_PTR] return StreamingResponse(io.BytesIO(item_file), media_type="image/png")
async def heat(request): calor = await request.json() learner = int(calor['learner']) clase = int(calor['clase']) first = calor['first'] img_heat = heatmap(lista_learn[learner].learner, global_img, clase, first) with io.BytesIO() as contenido: img_heat.save(contenido, format="JPEG") crudo = contenido.getvalue() return StreamingResponse(BytesIO(crudo), media_type='image/jpeg')
def get_image(image_id: str, db=Depends(db)): try: record = db.images.find_one({'_id': ObjectId(image_id)}) except InvalidId: raise HTTPException(status_code=404, detail="Image not found. Id is not valid") if not record: raise HTTPException(status_code=404, detail="Image not found") return StreamingResponse(io.BytesIO(record['image']), media_type=record['content_type'])
async def resize_from_file( file: UploadFile = File(...), scale_pct: float = 50.0): image = await file.read() resized, headers = resize(image, scale_pct) headers.update({ "orig-filename": file.filename, "content-type": file.content_type, }) headers.update({k: str(v) for k, v in headers.items()}) return StreamingResponse(resized, media_type="image/png", headers=headers)
async def test_cache_response_get_instance_called(): with patch.object(CacheRedis, 'get_instance', return_value=mock_redis) as patched_get_instance: request = get_request_obj(hdr=[(b"accept", b"text/html")]) call_next = AsyncMock() call_next.return_value = StreamingResponse( generate_json({"foo": "bar"}), media_type="application/json") await cache_response(request, call_next) patched_get_instance.assert_called()
async def proxy_request(self, scope: Scope, receive, send, url: str): request = Request(scope, receive, send) func = getattr(self.session, request.method) downstream_resp = await func(url, data=request.stream()) req_resp = StreamingResponse( downstream_resp.aiter_bytes(), status_code=downstream_resp.status_code, headers=downstream_resp.headers, ) await req_resp(scope, receive, send)
async def app(scope, receive, send): def numbers(minimum, maximum): for i in range(minimum, maximum + 1): yield str(i) if i != maximum: yield ", " generator = numbers(1, 5) response = StreamingResponse(generator, media_type="text/plain") await response(scope, receive, send)
async def get_screenshot( identifier: str, object_store_service: ObjectStoreService = Depends(get_object_store_service), ): try: data = await object_store_service.fetch_object(f"{identifier}.png") document = io.BytesIO(data) return StreamingResponse(document, media_type="image/png") except ObjectNotFound: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
def serve_pil_image(img): buf = BytesIO() img.save(buf, 'png') buf.seek(0) headers = { "Cache-Control": "max-age=0, no-cache, no-store, must-revalidate" } return StreamingResponse(buf, headers=headers, media_type="image/png")
def get_schema_plot(): log_args(api="/api", kwargs=locals()) url = f"{api_url}/meta/schema" r = requests.get( url, params={"graphviz": True, "plot": True}, headers=api_request_headers, ) r.raise_for_status() return StreamingResponse(io.BytesIO(r.content), media_type="image/png")
async def call_next(request: Request) -> Response: app_exc: typing.Optional[Exception] = None send_stream, recv_stream = anyio.create_memory_object_stream() async def coro() -> None: nonlocal app_exc async with send_stream: try: await self.app(scope, request.receive, send_stream.send) except Exception as exc: app_exc = exc task_group.start_soon(coro) try: message = await recv_stream.receive() except anyio.EndOfStream: if app_exc is not None: raise app_exc raise RuntimeError("No response returned.") assert message["type"] == "http.response.start" async def body_stream() -> typing.AsyncGenerator[bytes, None]: async with recv_stream: async for message in recv_stream: assert message["type"] == "http.response.body" body = message.get("body", b"") if body: yield body if not message.get("more_body", False): break if app_exc is not None: raise app_exc response = StreamingResponse(status_code=message["status"], content=body_stream()) response.raw_headers = message["headers"] return response
async def search_api(body: JinaSearchRequestModel): """ Search API to search documents. :param body: search request. :return: Response of the results. """ bd = body.dict() return StreamingResponse(result_in_stream(request_generator(**bd)), media_type='application/json')
def download_dataset_collection( self, trans: ProvidesHistoryContext = DependsOnTrans, history_id: EncodedDatabaseIdField = HistoryIDPathParam, id: EncodedDatabaseIdField = HistoryHDCAIDPathParam, ): """Download the content of a history dataset collection as a `zip` archive while maintaining approximate collection structure. """ archive = self.service.get_dataset_collection_archive_for_download(trans, id) return StreamingResponse(archive.response(), headers=archive.get_headers())
async def temperature_history_api_jpeg(intval: IntervalParams): """Log of temperature of time interval as chart. """ loop = asyncio.get_running_loop() data = await loop.run_in_executor( app.ps_executor, create_temperature_history_chart, intval.begin, intval.end ) return StreamingResponse(data, media_type="image/jpeg")
def download_database(name) -> StreamingResponse: try: return StreamingResponse( content=io.BytesIO(read_database_file(name)), media_type="application/vnd.ms-access", headers={ "Content-Disposition": f"attachment; filename={name}", }, ) except FileNotFoundError: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
async def delete_api(body: JinaDeleteRequestModel): """ Delete API to delete documents. :param body: delete request. :return: Response of the results. """ bd = body.dict() return StreamingResponse(result_in_stream(request_generator(**bd)), media_type='application/json')
async def index_api(body: JinaIndexRequestModel): """ Index API to index documents. :param body: index request. :return: Response of the results. """ bd = body.dict() return StreamingResponse(result_in_stream(request_generator(**bd)), media_type='application/json')
async def draw_plates(image: bytes = File(...)): data, img = plate_localizer.load_image(image) conf, box = plate_localizer.predict(data) pred_bbox = plate_localizer.process_pred(box, conf, img.shape) plates = plate_localizer.crop_objects(img, pred_bbox, ['license_plate']) predictions = [plate_reader.read_plate(plate['img']) for plate in plates] license = [pred['plate'] for pred in predictions] img = plate_localizer.draw_bbox(img, pred_bbox, custom_labels=license) img = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2RGB) _, img = cv2.imencode('.png', img) return StreamingResponse(io.BytesIO(img.tobytes()), media_type="image/png")
async def info(path: str, service: Service, user: str = Depends(auth)): path = Path(TEMPDIR.name, path) # Create repo if does does not exist repo = Git(path) if path.exists() else Git.init(path) # Fetch inforefs data = repo.inforefs(service.value) media = f'application/x-{service.value}-advertisement' return StreamingResponse(data, media_type=media)
async def draw_image(): data = {'y': np.random.randn(10), 'z': np.random.randn(10)} df = pd.DataFrame(data, index=pd.period_range('1-2000', periods=10)) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) df.plot(ax=ax) buf = io.BytesIO() fig.savefig(buf, format='png') buf.seek(0) return StreamingResponse(buf, media_type='image/png')
async def service(path: str, service: Service, req: Request): path = Path(TEMPDIR.name, path) repo = Git(path) stream = req.stream() data = [data async for data in stream] data = b''.join(data) data = repo.service(service.value, data) media = f'application/x-{service.value}-result' return StreamingResponse(data, media_type=media)
async def create_image_resize(file: UploadFile = File(...), thumbnailHeight: int = 660, thumbnailWidth: int = 420, startPage: int = 1, endPage: int = 10): # convert pdf to images if file.content_type.lower() == "application/pdf": im = convert_from_bytes(file.file.read()) # images = convert_from_bytes(open('/home/belval/example.pdf', 'rb').read()) # im = Image.open(pdfImage) else: im = Image.open(file.file) # im = Image.open(file.file) # im = resize_image(im,thumbnailHeight, thumbnailWidth) print("CONTENT TYPE", file.content_type) fileFormat = mimeTypeDict.get( file.content_type).get("thumbnail-format").upper() print("FILE FORMAT", fileFormat) print( "*****************************************************************************" ) # b = io.BytesIO() b = [] if file.content_type.lower() == "application/pdf": for i, page in enumerate(im): # page.save("%s-page%d.jpg" % (pdf_file,pages.index(page)), "JPEG") if i >= startPage - 1 and i < endPage: #== 4: page = resize_image(page, thumbnailHeight, thumbnailWidth) b.append(io.BytesIO()) page.save( b[-1], format=fileFormat ) #page.save(b, format=fileFormat) #.save("page%d.png" % i) else: for i, page in enumerate(ImageSequence.Iterator(im)): if i >= startPage - 1 and i < endPage: #== 4: page = resize_image(page, thumbnailHeight, thumbnailWidth) b.append(io.BytesIO()) page.save( b[-1], format=fileFormat ) #page.save(b, format=fileFormat) #.save("page%d.png" % i) # im.save(b, format=fileFormat) #format="JPEG") #format="PNG") #format="JPEG") #"JPEG", quality=80) #"JPEG") # b.name = "hello.jpg" # return StreamingResponse(b, media_type="image/jpeg", # headers={'Content-Disposition': 'inline; filename="hello.jpg"'}) b[0].seek(0) #Important for streams to work return StreamingResponse( b[0], media_type=mimeTypeDict.get(file.content_type).get( "return-mime-type")) #media_type=file.content_type)
async def call_next(self, request: Request): import asyncio from starlette.responses import StreamingResponse inner = self.app(dict(request)) loop = asyncio.get_event_loop() queue = asyncio.Queue() # type: asyncio.Queue async def coro() -> None: try: await inner(request.receive, queue.put) finally: await queue.put(None) task = loop.create_task(coro()) message = await queue.get() if message is None: task.result() raise RuntimeError("No response returned.") scope = dict(request) if 'http.response.template' in scope.get("extensions", {}): if message["type"] == "http.response.template": await self._orig_send(message) message = await queue.get() assert message["type"] == "http.response.start", message['type'] async def body_stream(): while True: message = await queue.get() if message is None: break assert message["type"] == "http.response.body" yield message["body"] task.result() response = StreamingResponse(status_code=message["status"], content=body_stream()) response.raw_headers = message["headers"] return response
def transfer_event_source(request: Request): """ SSE (Server Sent Event) endpoint for transfer events. """ return StreamingResponse( Transfer.stream(request), media_type='text/event-stream', headers={ 'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no', }, )
async def tiles(fractal_type: FractalType, zoom: int, x: int, y: int): if zoom < 0 or any(i < 0 or i >= (pow(2, zoom)) for i in [x, y]): return img_buffer = get_fractal_tile(x, y, zoom, fractal_type) cache_task = BackgroundTask(save_tile, img_buffer, x, y, zoom, fractal_type) return StreamingResponse( img_buffer, media_type="image/png", headers={'Content-Disposition': 'inline; filename="tile.png"'}, background=cache_task)
async def tile(profile_name: str, z: int, x: int, y: int, supertile: Optional[int] = 0) -> StreamingResponse: tile_bytes = None if supertile == 1: tile_bytes = get_super_tile(profile_name, z, x, y) else: tile_bytes = get_tile_bytes(profile_name, z, x, y) return (StreamingResponse(io.BytesIO(tile_bytes), media_type="image/png") if tile_bytes else response_404)
async def show_pdf( self, trans: ProvidesUserContext = DependsOnTrans, id: EncodedDatabaseIdField = PageIdPathParam, ): """Return a PDF document of the last revision of the Page. This feature may not be available in this Galaxy. """ pdf_bytes = self.service.show_pdf(trans, id) return StreamingResponse(io.BytesIO(pdf_bytes), media_type="application/pdf")
async def delete_api(body: JinaDeleteRequestModel): """ Delete API to delete documents. :param body: delete request. :return: Response of the results. """ from .....clients import BaseClient bd = body.dict() bd['mode'] = RequestType.DELETE BaseClient.add_default_kwargs(bd) return StreamingResponse(result_in_stream(request_generator(**bd)))
async def search_api(body: JinaSearchRequestModel): """ Search API to search documents. :param body: search request. :return: Response of the results. """ from .....clients import BaseClient bd = body.dict() bd['mode'] = RequestType.SEARCH BaseClient.add_default_kwargs(bd) return StreamingResponse(result_in_stream(request_generator(**bd)))