Initial commit
Browse filesFiles changed (8)
- app.pyAdded+96
- inference_pb2.pyAdded+30
- inference_pb2.pyiAdded+25
- inference_pb2_grpc.pyAdded+102
- input/1.pngAdded
- input/13.pngAdded
- input/zebra.jpegAdded
- requirements.txtAdded+5
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596import osfrom io import BytesIO
import gradio as grimport grpcfrom PIL import Imagefrom cachetools import LRUCacheimport hashlib
from protos.inference_pb2 import GuideAndRescaleRequest, GuideAndRescaleResponsefrom protos.inference_pb2_grpc import GuideAndRescaleServiceStub
def get_bytes(img): if img is None: return img
buffered = BytesIO() img.save(buffered, format="JPEG") return buffered.getvalue()
def bytes_to_image(image: bytes) -> Image.Image: image = Image.open(BytesIO(image)) return image
def resize(img): if img.size != (512, 512): img = img.resize((512, 512), Image.Resampling.LANCZOS)
return img
def edit(image, source_prompt, target_prompt, config, progress=gr.Progress(track_tqdm=True)): if not image or not source_prompt or not target_prompt: raise ValueError("Need to upload an image and enter init and edit prompts")
image_bytes = get_bytes(image) os.environ['SERVER'] = "0.0.0.0:50052" with grpc.insecure_channel(os.environ['SERVER']) as channel: stub = GuideAndRescaleServiceStub(channel)
output: GuideAndRescaleResponse = stub.swap( GuideAndRescaleRequest(image=image_bytes, source_prompt=source_prompt, target_prompt=target_prompt, config=config, use_cache=True) )
output = bytes_to_image(output.image) return output
def get_demo(): with gr.Blocks() as demo: gr.Markdown("## Guide-and-Rescale") gr.Markdown( '<div style="display: flex; align-items: center; gap: 10px;">' '<span>Official Guide-and-Rescale Gradio demo:</span>' '<a href="https://github.com/AIRI-Institute/Guide-and-Rescale"><img src="https://img.shields.io/badge/github-%23121011.svg?style=for-the-badge&logo=github&logoColor=white" height=22.5></a>' '<a href="https://colab.research.google.com/drive/1noKOOcDBBL_m5_UqU15jBBqiM8piLZ1O?usp=sharing"><img src="https://colab.research.google.com/assets/colab-badge.svg" height=22.5></a>' '</div>' ) with gr.Row(): with gr.Column(): with gr.Row(): image = gr.Image(label="Image that you want to edit", type="pil") with gr.Row(): source_prompt = gr.Textbox(label="Init Prompt", info="Describs the content on the original image.") target_prompt = gr.Textbox(label="Edit Prompt", info="Describs what is expected in the output image.") config = gr.Radio(["non-stylisation", "stylisation"], value='non-stylisation', label="Type of Editing", info="Selects a config for editing.") with gr.Row(): btn = gr.Button("Edit image") with gr.Column(): with gr.Row(): output = gr.Image(label="Result: edited image")
gr.Examples(examples=[["input/1.png", 'A photo of a tiger', 'A photo of a lion', 'non-stylisation'], ["input/zebra.jpeg", 'A photo of a zebra', 'A photo of a white horse', 'non-stylisation'], ["input/13.png", 'A photo', 'Anime style face', 'stylisation']], inputs=[image, source_prompt, target_prompt, config], outputs=output)
image.upload(fn=resize, inputs=[image], outputs=image)
btn.click(fn=edit, inputs=[image, source_prompt, target_prompt, config], outputs=output)
gr.Markdown('''To cite the paper by the authors ``` TODO: add cite ``` ''') return demo
if __name__ == '__main__': align_cache = LRUCache(maxsize=10) demo = get_demo() demo.launch(server_name="0.0.0.0", server_port=7860)123456789101112131415161718192021222324252627282930# -*- coding: utf-8 -*-# Generated by the protocol buffer compiler. DO NOT EDIT!# source: inference.proto# Protobuf Python Version: 5.26.1"""Generated protocol buffer code."""from google.protobuf import descriptor as _descriptorfrom google.protobuf import descriptor_pool as _descriptor_poolfrom google.protobuf import symbol_database as _symbol_databasefrom google.protobuf.internal import builder as _builder# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0finference.proto\x12\tinference\"x\n\x16GuideAndRescaleRequest\x12\r\n\x05image\x18\x01 \x01(\x0c\x12\x15\n\rsource_prompt\x18\x02 \x01(\t\x12\x15\n\rtarget_prompt\x18\x03 \x01(\t\x12\x0e\n\x06\x63onfig\x18\x04 \x01(\t\x12\x11\n\tuse_cache\x18\x05 \x01(\x08\"(\n\x17GuideAndRescaleResponse\x12\r\n\x05image\x18\x01 \x01(\x0c\x32g\n\x16GuideAndRescaleService\x12M\n\x04swap\x12!.inference.GuideAndRescaleRequest\x1a\".inference.GuideAndRescaleResponseb\x06proto3')
_globals = globals()_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'inference_pb2', _globals)if not _descriptor._USE_C_DESCRIPTORS: DESCRIPTOR._loaded_options = None _globals['_GUIDEANDRESCALEREQUEST']._serialized_start=30 _globals['_GUIDEANDRESCALEREQUEST']._serialized_end=150 _globals['_GUIDEANDRESCALERESPONSE']._serialized_start=152 _globals['_GUIDEANDRESCALERESPONSE']._serialized_end=192 _globals['_GUIDEANDRESCALESERVICE']._serialized_start=194 _globals['_GUIDEANDRESCALESERVICE']._serialized_end=297# @@protoc_insertion_point(module_scope)12345678910111213141516171819202122232425from google.protobuf import descriptor as _descriptorfrom google.protobuf import message as _messagefrom typing import ClassVar as _ClassVar, Optional as _Optional
DESCRIPTOR: _descriptor.FileDescriptor
class GuideAndRescaleRequest(_message.Message): __slots__ = ("image", "source_prompt", "target_prompt", "config", "use_cache") IMAGE_FIELD_NUMBER: _ClassVar[int] SOURCE_PROMPT_FIELD_NUMBER: _ClassVar[int] TARGET_PROMPT_FIELD_NUMBER: _ClassVar[int] CONFIG_FIELD_NUMBER: _ClassVar[int] USE_CACHE_FIELD_NUMBER: _ClassVar[int] image: bytes source_prompt: str target_prompt: str config: str use_cache: bool def __init__(self, image: _Optional[bytes] = ..., source_prompt: _Optional[str] = ..., target_prompt: _Optional[str] = ..., config: _Optional[str] = ..., use_cache: bool = ...) -> None: ...
class GuideAndRescaleResponse(_message.Message): __slots__ = ("image",) IMAGE_FIELD_NUMBER: _ClassVar[int] image: bytes def __init__(self, image: _Optional[bytes] = ...) -> None: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!"""Client and server classes corresponding to protobuf-defined services."""import grpcimport warnings
import inference_pb2 as inference__pb2
GRPC_GENERATED_VERSION = '1.65.1'GRPC_VERSION = grpc.__version__EXPECTED_ERROR_RELEASE = '1.66.0'SCHEDULED_RELEASE_DATE = 'August 6, 2024'_version_not_supported = False
try: from grpc._utilities import first_version_is_lower _version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION)except ImportError: _version_not_supported = True
if _version_not_supported: warnings.warn( f'The grpc package installed is at version {GRPC_VERSION},' + f' but the generated code in inference_pb2_grpc.py depends on' + f' grpcio>={GRPC_GENERATED_VERSION}.' + f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}' + f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.' + f' This warning will become an error in {EXPECTED_ERROR_RELEASE},' + f' scheduled for release on {SCHEDULED_RELEASE_DATE}.', RuntimeWarning )
class GuideAndRescaleServiceStub(object): """Missing associated documentation comment in .proto file."""
def __init__(self, channel): """Constructor.
Args: channel: A grpc.Channel. """ self.swap = channel.unary_unary( '/inference.GuideAndRescaleService/swap', request_serializer=inference__pb2.GuideAndRescaleRequest.SerializeToString, response_deserializer=inference__pb2.GuideAndRescaleResponse.FromString, _registered_method=True)
class GuideAndRescaleServiceServicer(object): """Missing associated documentation comment in .proto file."""
def swap(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
def add_GuideAndRescaleServiceServicer_to_server(servicer, server): rpc_method_handlers = { 'swap': grpc.unary_unary_rpc_method_handler( servicer.swap, request_deserializer=inference__pb2.GuideAndRescaleRequest.FromString, response_serializer=inference__pb2.GuideAndRescaleResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'inference.GuideAndRescaleService', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) server.add_registered_method_handlers('inference.GuideAndRescaleService', rpc_method_handlers)
# This class is part of an EXPERIMENTAL API.class GuideAndRescaleService(object): """Missing associated documentation comment in .proto file."""
@staticmethod def swap(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary( request, target, '/inference.GuideAndRescaleService/swap', inference__pb2.GuideAndRescaleRequest.SerializeToString, inference__pb2.GuideAndRescaleResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, _registered_method=True)12345pillow==10.0.0grpcio==1.63.0grpcio_tools==1.63.0gradio==4.31.5cachetools==5.3.3app.pyAdded+96
inference_pb2.pyAdded+30
inference_pb2.pyiAdded+25
inference_pb2_grpc.pyAdded+102
input/1.pngAdded

input/13.pngAdded

input/zebra.jpegAdded

requirements.txtAdded+5