Download app.py from ChairKet/Image: direct link, hf CLI and curl.
- Browser
- Download file 5.38 kB
-
https://huggingface.co/spaces/ChairKet/Image/resolve/main/app.py
- Command line
-
hf download hf://spaces/ChairKet/Image/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ChairKet/Image/resolve/main/app.py
5.38 kB
| """ | |
| Minimal Gradio wrapper for Qwen-Image-Edit — LOW-MEMORY VERSION | |
| Optimized for 16GB RAM and modest GPUs (or CPU-only). | |
| """ | |
| import os | |
| from typing import Optional | |
| # --- Force CPU-only if needed (uncomment to disable GPU entirely) --- | |
| os.environ["CUDA_VISIBLE_DEVICES"] = "" | |
| import gradio as gr | |
| import torch | |
| from PIL import Image | |
| from huggingface_hub import snapshot_download | |
| # --- your project imports (as in the original script) --- | |
| from hacked_models.scheduler import FlowMatchEulerDiscreteScheduler | |
| from hacked_models.pipeline import QwenImageEditPipeline | |
| from hacked_models.models import QwenImageTransformer2DModel | |
| from hacked_models.utils import seed_everything | |
| # ----------------------------- | |
| # Global state (LOW-MEM CONFIG) | |
| # ----------------------------- | |
| _DEVICE = "cuda" if torch.cuda.is_available() else "cpu" | |
| _DTYPE = torch.float32 # Use float32 for maximum compatibility | |
| _PIPELINE: Optional[QwenImageEditPipeline] = None | |
| _LOADED_MODEL_PATH: Optional[str] = None | |
| def _load_pipeline(model_path: str) -> QwenImageEditPipeline: | |
| """Load model safely with low memory usage.""" | |
| global _PIPELINE, _LOADED_MODEL_PATH | |
| if _PIPELINE is not None and _LOADED_MODEL_PATH == model_path: | |
| return _PIPELINE | |
| seed_everything(42) | |
| # Load scheduler | |
| scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained( | |
| os.path.join(model_path, "scheduler"), torch_dtype=_DTYPE | |
| ) | |
| # Load transformer with CPU-first strategy | |
| transformer = QwenImageTransformer2DModel.from_pretrained( | |
| os.path.join(model_path, "transformer"), | |
| torch_dtype=_DTYPE, | |
| low_cpu_mem_usage=True, | |
| device_map="cpu", # Critical: load to CPU first | |
| ) | |
| # Load full pipeline | |
| pipe = QwenImageEditPipeline.from_pretrained( | |
| model_path, | |
| torch_dtype=_DTYPE, | |
| scheduler=scheduler, | |
| transformer=transformer, | |
| low_cpu_mem_usage=True, | |
| device_map="cpu", | |
| ) | |
| pipe.set_progress_bar_config(disable=None) | |
| # Do NOT move to GPU here — do it dynamically in predict() | |
| _PIPELINE = pipe | |
| _LOADED_MODEL_PATH = model_path | |
| return pipe | |
| def _build_grag_scale(cond_b: float, cond_delta: float, repeats: int = 10): | |
| """Reduced GRAG schedule for 512x512 resolution.""" | |
| return [((256, 1.0, 1.0), (1024, cond_b, cond_delta))] * repeats | |
| def predict( | |
| image: Image.Image, | |
| edit_prompt: str, | |
| cond_b: float, | |
| cond_delta: float, | |
| pipeline, | |
| ): | |
| if image is None or not edit_prompt: | |
| return None | |
| # Move to GPU only if available and needed | |
| if _DEVICE == "cuda": | |
| pipeline.to("cuda") | |
| try: | |
| # Downscale to 512x512 to save memory | |
| input_image = image.convert("RGB").resize((512, 512)) | |
| inputs = { | |
| "image": input_image, | |
| "prompt": edit_prompt, | |
| "generator": torch.manual_seed(42), | |
| "true_cfg_scale": 4.0, | |
| "negative_prompt": " ", | |
| "num_inference_steps": 12, # Reduced from 24 | |
| "return_dict": False, | |
| "grag_scale": _build_grag_scale(cond_b, cond_delta, repeats=10), # Reduced from 60 | |
| } | |
| with torch.inference_mode(): | |
| image_batch, x0_images, saved_outputs = pipeline(**inputs) | |
| result = image_batch[0] | |
| finally: | |
| # Always move back to CPU to free GPU memory | |
| if _DEVICE == "cuda": | |
| pipeline.to("cpu") | |
| torch.cuda.empty_cache() | |
| return result | |
| # ----------------------------- | |
| # Model loading | |
| # ----------------------------- | |
| model_dir = "Qwen-Image-Edit" | |
| repo_id = "Qwen/Qwen-Image-Edit" | |
| if not os.path.exists(model_dir) or not os.listdir(model_dir): | |
| # Use HF mirror for China users | |
| os.environ.setdefault("HF_ENDPOINT", "https://hf-mirror.com") | |
| snapshot_download(repo_id=repo_id, local_dir=model_dir, local_dir_use_symlinks=False) | |
| print(f"Model downloaded to {model_dir}") | |
| else: | |
| print(f"Model already exists at {model_dir}") | |
| pipe = _load_pipeline(model_dir) | |
| # ----------------------------- | |
| # Gradio UI | |
| # ----------------------------- | |
| with gr.Blocks(title="Qwen Image Edit — Low-Mem Mode") as demo: | |
| gr.Markdown("# Qwen Image Edit — Low-Memory Mode\nUpload an image, enter your edit instruction, and set GRAG params.") | |
| with gr.Row(): | |
| in_image = gr.Image(label="Input Image", type="pil") | |
| out_image = gr.Image(label="Edited Output", type="pil") | |
| edit_prompt = gr.Textbox(label="Edit Instruction", placeholder="e.g., Put sunglasses on her.") | |
| with gr.Row(): | |
| cond_b = gr.Slider(label="cond_b", minimum=0.8, maximum=2.0, value=1.0, step=0.01) | |
| cond_delta = gr.Slider(label="cond_delta", minimum=0.8, maximum=2.0, value=1.0, step=0.01) | |
| run_btn = gr.Button("Run Edit") | |
| run_btn.click( | |
| fn=predict, | |
| inputs=[in_image, edit_prompt, cond_b, cond_delta, pipe], | |
| outputs=[out_image], | |
| api_name="run_edit", | |
| ) | |
| gr.Markdown( | |
| """ | |
| **Low-Mem Optimizations Applied** | |
| - Resolution: **512×512** (instead of 1024×1024) | |
| - Inference steps: **12** (instead of 24) | |
| - GRAG repeats: **10** (instead of 60) | |
| - Precision: **float32** (max compatibility) | |
| - Model loaded to **CPU first**, moved to GPU only during inference | |
| - GPU memory freed immediately after generation | |
| """ | |
| ) | |
| if __name__ == "__main__": | |
| demo.queue().launch(share=True) |