Spaces:
Build error
Build error
update pose images
#8
by yumingj - opened
Files changed (12)
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.17app_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':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('patch -p1'.split(), cwd='Text2Human', stdin=f)from model import ModelDESCRIPTION = '''# Text2HumanThis 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.)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.'''FOOTER = '<img id="visitor-badge" alt="visitor badge" src="https://visitor-badge.glitch.me/badge?page_id=hysts.text2human" />'def 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)with gr.Blocks(theme=args.theme, 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.Variable()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.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():label_image = gr.Image(label='Label Image',type='numpy',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():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')with gr.Column():with gr.Row():result = gr.Image(label='Result',type='numpy',elem_id='result-image')gr.Markdown(FOOTER)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=model.generate_human,inputs=[label_image,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 lines4546474849505152535455565758596061626364656667686970717273747576777879808123 unmodified lines1051061071081091101115 unmodified lines117118119120121122123124125126127128129130from __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 data23 unmodified linesself.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)5 unmodified linescolored_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)1234563 unmodified lines101112131415161718192026 unmodified lines47484950515253545556575859606162636465666768697071727374757677787980818283848523 unmodified lines1091101111121131141151165 unmodified lines122123124125126127128129130131132133134135136137from __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)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():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 data23 unmodified linesself.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)5 unmodified linescolored_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)
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.2123456789101112einops==0.4.1lpips==0.1.4mmcv-full==1.5.2mmsegmentation==0.24.1numpy==1.22.3openmim==0.1.5Pillow==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;}12345678910111213141516h1 {text-align: center;}#input-image {max-height: 300px;}#label-image {height: 300px;}#result-image {height: 300px;}img#visitor-badge {display: block;margin: auto;}
.pre-commit-config.yaml+45-60
.style.yapfAdded+5
README.md+1-2
app.py+137-112
model.py+24-17
pose_images/001.png

Large File Pointer Details
- SHA256: 83f059e8281483a1c8848c9e190813f2e4eb56b0bfa866cf004e87f019ef4d2c
- Pointer size: 130 Bytes
- Size of remote file: 48.7 kB

Large File Pointer Details
- SHA256: 35b68667f2f2eb5a287ffede8e496e9db920be78871fda73b24598ed0f85dcc4
- Pointer size: 131 Bytes
- Size of remote file: 135 kB
pose_images/002.png

Large File Pointer Details
- SHA256: 0fe37d3d227a61259faa032f7430c95fb1162758545d02e1f4c6bd4cd2bc99fc
- Pointer size: 130 Bytes
- Size of remote file: 43.4 kB

Large File Pointer Details
- SHA256: e109163ba1ebfe4c3323ac700e1e6dd9443d5d3cf7e468a3587de7fc40383fa8
- Pointer size: 131 Bytes
- Size of remote file: 116 kB
pose_images/003.png

Large File Pointer Details
- SHA256: 83f059e8281483a1c8848c9e190813f2e4eb56b0bfa866cf004e87f019ef4d2c
- Pointer size: 130 Bytes
- Size of remote file: 48.7 kB

Large File Pointer Details
- SHA256: 35b68667f2f2eb5a287ffede8e496e9db920be78871fda73b24598ed0f85dcc4
- Pointer size: 131 Bytes
- Size of remote file: 135 kB
pose_images/004.png

Large File Pointer Details
- SHA256: 43a71489b88a0bfb8c3a035f62599534cdd6df7b2adb188be4da351819709de1
- Pointer size: 130 Bytes
- Size of remote file: 45.8 kB

Large File Pointer Details
- SHA256: de2aa00f09620cd8c33e722d1eab610ea99cd473d5ce4541275e04ab5e642d99
- Pointer size: 131 Bytes
- Size of remote file: 122 kB
pose_images/005.png

Large File Pointer Details
- SHA256: 9bd8833ace00dd3c97eb858e5b87d6803e0611fd718234699329bad7e4f906f1
- Pointer size: 130 Bytes
- Size of remote file: 45.7 kB

Large File Pointer Details
- SHA256: 69f6511b2e9a50c77650bd796ccf144d3c5dc12dda84ba899b6e5beb8de052de
- Pointer size: 131 Bytes
- Size of remote file: 137 kB
requirements.txt+6-6
style.css+8-2