Spaces:
Build error
Build error
Upload 000.png
#1
by yumingj - opened
Files changed (13)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061exclude: ^patchrepos:- repo: https://github.com/pre-commit/pre-commit-hooksrev: v4.6.0hooks:- id: check-executables-have-shebangs- id: check-json- id: check-merge-conflict- id: check-shebang-scripts-are-executable- id: check-toml- id: check-yaml- id: end-of-file-fixer- id: mixed-line-endingargs: ["--fix=lf"]- id: requirements-txt-fixer- id: trailing-whitespace- repo: https://github.com/myint/docformatterrev: v1.7.5hooks:- id: docformatterargs: ["--in-place"]- repo: https://github.com/pycqa/isortrev: 5.13.2hooks:- id: isortargs: ["--profile", "black"]- repo: https://github.com/pre-commit/mirrors-mypyrev: v1.10.0hooks:- id: mypyargs: ["--ignore-missing-imports"]additional_dependencies:["types-python-slugify","types-requests","types-PyYAML","types-pytz",]- repo: https://github.com/psf/blackrev: 24.4.2hooks:- id: blacklanguage_version: python3.10args: ["--line-length", "119"]- repo: https://github.com/kynan/nbstripoutrev: 0.7.1hooks:- id: nbstripoutargs:["--extra-keys","metadata.interpreter metadata.kernelspec cell.metadata.pycharm",]- repo: https://github.com/nbQA-dev/nbQArev: 1.8.5hooks:- id: nbqa-black- id: nbqa-pyupgradeargs: ["--py37-plus"]- id: nbqa-isortargs: ["--float-to-top"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546exclude: ^(Text2Human|patch)repos:- repo: https://github.com/pre-commit/pre-commit-hooksrev: v4.2.0hooks:- id: check-executables-have-shebangs- id: check-json- id: check-merge-conflict- id: check-shebang-scripts-are-executable- id: check-toml- id: check-yaml- id: double-quote-string-fixer- id: end-of-file-fixer- id: mixed-line-endingargs: ['--fix=lf']- id: requirements-txt-fixer- id: trailing-whitespace- repo: https://github.com/myint/docformatterrev: v1.4hooks:- id: docformatterargs: ['--in-place']- repo: https://github.com/pycqa/isortrev: 5.10.1hooks:- id: isort- repo: https://github.com/pre-commit/mirrors-mypyrev: v0.812hooks:- id: mypyargs: ['--ignore-missing-imports']- repo: https://github.com/google/yapfrev: v0.32.0hooks:- id: yapfargs: ['--parallel', '--in-place']- repo: https://github.com/kynan/nbstripoutrev: 0.5.0hooks:- id: nbstripoutargs: ['--extra-keys', 'metadata.interpreter metadata.kernelspec cell.metadata.pycharm']- repo: https://github.com/nbQA-dev/nbQArev: 1.3.1hooks:- id: nbqa-isort- id: nbqa-yapf
12345[style]based_on_style = pep8blank_line_before_nested_class_or_def = falsespaces_before_comment = 2split_before_logical_operator = true3 unmodified lines456789101112133 unmodified linescolorFrom: purplecolorTo: graysdk: gradiosdk_version: 4.36.1app_file: app.pypinned: falsesuggested_hardware: t4-small---Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference3 unmodified lines4567891011123 unmodified linescolorFrom: purplecolorTo: graysdk: gradiosdk_version: 3.0.11app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference
1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331 unmodified linefrom __future__ import annotationsimport osimport pathlibimport randomimport shleximport subprocessif os.getenv("SYSTEM") == "spaces":subprocess.run(shlex.split("pip install click==7.1.2"))subprocess.run(shlex.split("pip install typer==0.9.4"))import mimmim.uninstall("mmcv-full", confirm_yes=True)mim.install("mmcv-full==1.5.2", is_yes=True)with open("patch") as f:subprocess.run(shlex.split("patch -p1"), cwd="Text2Human", stdin=f)import gradio as grimport numpy as npfrom model import ModelDESCRIPTION = """# [Text2Human](https://github.com/yumingj/Text2Human)You can modify sample steps and seeds. By varying seeds, you can sample different human images under the same pose, shape description, and texture description. The larger the sample steps, the better quality of the generated images. (The default value of sample steps is 256 in the original repo.)Label image generation step can be skipped. However, in that case, the input label image must be 512x256 in size and must contain only the specified colors."""MAX_SEED = np.iinfo(np.int32).maxdef randomize_seed_fn(seed: int, randomize_seed: bool) -> int:if randomize_seed:seed = random.randint(0, MAX_SEED)return seedmodel = Model()with gr.Blocks(css="style.css") as demo:gr.Markdown(DESCRIPTION)with gr.Row():with gr.Column():with gr.Row():input_image = gr.Image(label="Input Pose Image", type="pil", elem_id="input-image")pose_data = gr.State()with gr.Row():paths = sorted(pathlib.Path("pose_images").glob("*.png"))gr.Examples(examples=[[path.as_posix()] for path in paths], inputs=input_image)with gr.Row():shape_text = gr.Textbox(label="Shape Description",placeholder="""<gender>, <sleeve length>, <length of lower clothing>, <outer clothing type>, <other accessories1>, ...Note: The outer clothing type and accessories can be omitted.""",)with gr.Row():gr.Examples(examples=[["man, sleeveless T-shirt, long pants"], ["woman, short-sleeve T-shirt, short jeans"]],inputs=shape_text,)with gr.Row():generate_label_button = gr.Button("Generate Label Image")with gr.Column():with gr.Row():label_image = gr.Image(label="Label Image", type="numpy", format="png", elem_id="label-image")with gr.Row():texture_text = gr.Textbox(label="Texture Description",placeholder="""<upper clothing texture>, <lower clothing texture>, <outer clothing texture>Note: Currently, only 5 types of textures are supported, i.e., pure color, stripe/spline, plaid/lattice, floral, denim.""",)with gr.Row():gr.Examples(examples=[["pure color, denim"],["floral, stripe"],],inputs=texture_text,)with gr.Row():sample_steps = gr.Slider(label="Sample Steps", minimum=10, maximum=300, step=1, value=256)with gr.Row():seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)randomize_seed = gr.Checkbox(label="Randomize seed", value=True)with gr.Row():generate_human_button = gr.Button("Generate Human")with gr.Column():with gr.Row():result = gr.Image(label="Result")input_image.change(fn=model.process_pose_image,inputs=input_image,outputs=pose_data,)generate_label_button.click(fn=model.generate_label_image,inputs=[pose_data,shape_text,],outputs=label_image,)generate_human_button.click(fn=randomize_seed_fn,inputs=[seed, randomize_seed],outputs=seed,queue=False,).then(fn=model.generate_human,inputs=[label_image,texture_text,sample_steps,seed,],outputs=result,)if __name__ == "__main__":demo.queue(max_size=10).launch()1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581 unmodified linefrom __future__ import annotationsimport argparseimport osimport pathlibimport subprocessimport gradio as grif os.getenv('SYSTEM') == 'spaces':subprocess.call('pip uninstall -y mmcv-full'.split())subprocess.call('pip install mmcv-full==1.5.2'.split())subprocess.call('git apply ../patch'.split(), cwd='Text2Human')from model import Modeldef parse_args() -> argparse.Namespace:parser = argparse.ArgumentParser()parser.add_argument('--device', type=str, default='cpu')parser.add_argument('--theme', type=str)parser.add_argument('--share', action='store_true')parser.add_argument('--port', type=int)parser.add_argument('--disable-queue',dest='enable_queue',action='store_false')return parser.parse_args()def set_example_image(example: list) -> dict:return gr.Image.update(value=example[0])def set_example_text(example: list) -> dict:return gr.Textbox.update(value=example[0])def main():args = parse_args()model = Model(args.device)css = '''h1#title {text-align: center;}#input-image {max-height: 300px;}#label-image {height: 300px;}#result-image {height: 300px;}'''with gr.Blocks(theme=args.theme, css=css) as demo:gr.Markdown('''<h1 id="title">Text2Human</h1>This is an unofficial demo for <a href="https://github.com/yumingj/Text2Human">https://github.com/yumingj/Text2Human</a>.You can modify sample steps and seeds. By varying seeds, you can sample different human images under the same pose, shape description, and texture description. The larger the sample steps, the better quality of the generated images. (The default value of sample steps is 256 in the original repo.)</a>''')with gr.Row():with gr.Column():with gr.Row():input_image = gr.Image(label='Input Pose Image',type='pil',elem_id='input-image')with gr.Row():paths = sorted(pathlib.Path('pose_images').glob('*.png'))example_images = gr.Dataset(components=[input_image],samples=[[path.as_posix()]for path in paths])with gr.Column():with gr.Row():label_image = gr.Image(label='Label Image',type='numpy',elem_id='label-image')with gr.Row():shape_text = gr.Textbox(label='Shape Description',placeholder='''<gender>, <sleeve length>, <length of lower clothing>, <outer clothing type>, <other accessories1>, ...Note: The outer clothing type and accessories can be omitted.''')with gr.Row():shape_example_texts = gr.Dataset(components=[shape_text],samples=[['man, sleeveless T-shirt, long pants'],['woman, short-sleeve T-shirt, short jeans']])with gr.Row():generate_label_button = gr.Button('Generate Label Image')with gr.Column():with gr.Row():result = gr.Image(label='Result',type='numpy',elem_id='result-image')with gr.Row():texture_text = gr.Textbox(label='Texture Description',placeholder='''<upper clothing texture>, <lower clothing texture>, <outer clothing texture>Note: Currently, only 5 types of textures are supported, i.e., pure color, stripe/spline, plaid/lattice, floral, denim.''')with gr.Row():texture_example_texts = gr.Dataset(components=[texture_text],samples=[['pure color, denim'], ['floral, stripe']])with gr.Row():sample_steps = gr.Slider(10,300,value=10,step=10,label='Sample Steps')with gr.Row():seed = gr.Slider(0, 1000000, value=0, step=1, label='Seed')with gr.Row():generate_human_button = gr.Button('Generate Human')gr.Markdown('<center><img src="https://visitor-badge.glitch.me/badge?page_id=hysts.text2human" alt="visitor badge"/></center>')input_image.change(fn=model.process_pose_image,inputs=[input_image],outputs=None)generate_label_button.click(fn=model.generate_label_image,inputs=[shape_text],outputs=[label_image])generate_human_button.click(fn=model.generate_human,inputs=[texture_text,sample_steps,seed,],outputs=[result])example_images.click(fn=set_example_image,inputs=example_images,outputs=example_images.components)shape_example_texts.click(fn=set_example_text,inputs=shape_example_texts,outputs=shape_example_texts.components)texture_example_texts.click(fn=set_example_text,inputs=texture_example_texts,outputs=texture_example_texts.components)demo.launch(enable_queue=args.enable_queue,server_port=args.port,share=args.share,)if __name__ == '__main__':main()
123453 unmodified lines910111213141516171826 unmodified lines454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192934 unmodified lines9899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132from __future__ import annotationsimport pathlibimport sysimport zipfile3 unmodified linesimport PIL.Imageimport torchsys.path.insert(0, "Text2Human")from models.sample_model import SampleFromPoseModelfrom utils.language_utils import generate_shape_attributes, generate_texture_attributesfrom utils.options import dict_to_nonedict, parsefrom utils.util import set_random_seed26 unmodified linesclass Model:def __init__(self):device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")self.config = self._load_config()self.config["device"] = device.typeself._download_models()self.model = SampleFromPoseModel(self.config)self.model.batch_size = 1def _load_config(self) -> dict:path = "Text2Human/configs/sample_from_pose.yml"config = parse(path, is_train=False)config = dict_to_nonedict(config)return configdef _download_models(self) -> None:model_dir = pathlib.Path("pretrained_models")if model_dir.exists():returnpath = huggingface_hub.hf_hub_download("yumingj/Text2Human_SSHQ", "pretrained_models.zip")model_dir.mkdir()with zipfile.ZipFile(path) as f:f.extractall(model_dir)@staticmethoddef preprocess_pose_image(image: PIL.Image.Image) -> torch.Tensor:image = (np.array(image.resize(size=(256, 512), resample=PIL.Image.Resampling.LANCZOS))[:, :, 2:].transpose(2, 0, 1).astype(np.float32))image = image / 12.0 - 1data = torch.from_numpy(image).unsqueeze(1)return data@staticmethoddef process_mask(mask: np.ndarray) -> np.ndarray:if mask.shape != (512, 256, 3):return Noneseg_map = np.full(mask.shape[:-1], -1)for index, color in enumerate(COLOR_LIST):seg_map[np.sum(mask == color, axis=2) == 3] = indexif not (seg_map != -1).all():return Nonereturn seg_map@staticmethod4 unmodified linesresult = np.asarray(result[0, :, :, :], dtype=np.uint8)return resultdef process_pose_image(self, pose_image: PIL.Image.Image) -> torch.Tensor:if pose_image is None:returndata = self.preprocess_pose_image(pose_image)self.model.feed_pose_data(data)return datadef generate_label_image(self, pose_data: torch.Tensor, shape_text: str) -> np.ndarray:if pose_data is None:returnself.model.feed_pose_data(pose_data)shape_attributes = generate_shape_attributes(shape_text)shape_attributes = torch.LongTensor(shape_attributes).unsqueeze(0)self.model.feed_shape_attributes(shape_attributes)self.model.generate_parsing_map()self.model.generate_quantized_segm()colored_segm = self.model.palette_result(self.model.segm[0].cpu())return colored_segmdef generate_human(self, label_image: np.ndarray, texture_text: str, sample_steps: int, seed: int) -> np.ndarray:if label_image is None:returnmask = label_image.copy()seg_map = self.process_mask(mask)if seg_map is None:returnself.model.segm = torch.from_numpy(seg_map).unsqueeze(0).unsqueeze(0).to(self.model.device)self.model.generate_quantized_segm()set_random_seed(seed)texture_attributes = generate_texture_attributes(texture_text)1234563 unmodified lines101112131415161718192026 unmodified lines47484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192934 unmodified lines9899100101102103104105106107108109110111112113114115116117118119120121122123124125126from __future__ import annotationsimport osimport pathlibimport sysimport zipfile3 unmodified linesimport PIL.Imageimport torchsys.path.insert(0, 'Text2Human')from models.sample_model import SampleFromPoseModelfrom utils.language_utils import (generate_shape_attributes,generate_texture_attributes)from utils.options import dict_to_nonedict, parsefrom utils.util import set_random_seed26 unmodified linesclass Model:def __init__(self, device: str):self.config = self._load_config()self.config['device'] = deviceself._download_models()self.model = SampleFromPoseModel(self.config)def _load_config(self) -> dict:path = 'Text2Human/configs/sample_from_pose.yml'config = parse(path, is_train=False)config = dict_to_nonedict(config)return configdef _download_models(self) -> None:model_dir = pathlib.Path('pretrained_models')if model_dir.exists():returntoken = os.getenv('HF_TOKEN')path = huggingface_hub.hf_hub_download('hysts/Text2Human','orig/pretrained_models.zip',use_auth_token=token)model_dir.mkdir()with zipfile.ZipFile(path) as f:f.extractall(model_dir)@staticmethoddef preprocess_pose_image(image: PIL.Image.Image) -> torch.Tensor:image = np.array(image.resize(size=(256, 512),resample=PIL.Image.Resampling.LANCZOS))[:, :, 2:].transpose(2, 0, 1).astype(np.float32)image = image / 12. - 1data = torch.from_numpy(image).unsqueeze(1)return data@staticmethoddef process_mask(mask: torch.Tensor) -> torch.Tensor:seg_map = np.full(mask.shape[:-1], -1)for index, color in enumerate(COLOR_LIST):seg_map[np.sum(mask == color, axis=2) == 3] = indexassert (seg_map != -1).all()return seg_map@staticmethod4 unmodified linesresult = np.asarray(result[0, :, :, :], dtype=np.uint8)return resultdef process_pose_image(self, pose_image: PIL.Image.Image) -> None:if pose_image is None:returndata = self.preprocess_pose_image(pose_image)self.model.feed_pose_data(data)def generate_label_image(self, shape_text: str) -> np.ndarray:shape_attributes = generate_shape_attributes(shape_text)shape_attributes = torch.LongTensor(shape_attributes).unsqueeze(0)self.model.feed_shape_attributes(shape_attributes)self.model.generate_parsing_map()self.model.generate_quantized_segm()colored_segm = self.model.palette_result(self.model.segm[0].cpu())mask = colored_segm.copy()seg_map = self.process_mask(mask)self.model.segm = torch.from_numpy(seg_map).unsqueeze(0).unsqueeze(0).to(self.model.device)self.model.generate_quantized_segm()return colored_segmdef generate_human(self, texture_text: str, sample_steps: int,seed: int) -> np.ndarray:set_random_seed(seed)texture_attributes = generate_texture_attributes(texture_text)
123456789101112einops==0.6.1lpips==0.1.4mmcv-full==1.5.2mmsegmentation==0.24.1numpy==1.23.5openmim==0.1.5Pillow==9.5.0sentence-transformers==2.2.2tokenizers==0.13.3torch==1.11.0torchvision==0.12.0transformers==4.30.21234567891011einops==0.4.1lpips==0.1.4mmcv-full==1.5.2mmsegmentation==0.24.1numpy==1.22.3Pillow==9.1.1sentence-transformers==2.2.0tokenizers==0.12.1torch==1.11.0torchvision==0.12.0transformers==4.19.2
12345678910h1 { text-align: center; display: block;}#input-image { max-height: 300px;}#label-image { max-height: 300px;}.pre-commit-config.yaml+45-60
.style.yapfAdded+5
README.md+1-2
app.py+144-119
model.py+28-34
pose_images/000.png


pose_images/001.png


pose_images/002.png


pose_images/003.png


pose_images/004.png


pose_images/005.png


requirements.txt+6-7
style.cssDeleted-10