Spaces:
Sleeping
Sleeping
Download app.py from Matejstein/Photo2texture: direct link, hf CLI and curl.
- Browser
- Download file 8.9 kB
-
https://huggingface.co/spaces/Matejstein/Photo2texture/resolve/refs%2Fpr%2F1/app.py
- Command line
-
hf download hf://spaces/Matejstein/Photo2texture@refs/pr/1/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Matejstein/Photo2texture/resolve/refs%2Fpr%2F1/app.py
8.9 kB
| import spaces # MUST be line 1 for ZeroGPU | |
| # --------------------------------------------------------------------------- | |
| # GRADIO SCHEMA BUG PATCH (Prevents TypeError on boolean schema definitions) | |
| # --------------------------------------------------------------------------- | |
| import gradio_client.utils as gc_utils | |
| _orig_get_type = gc_utils.get_type | |
| def _safe_get_type(schema): | |
| if not isinstance(schema, dict): | |
| return "Any" | |
| return _orig_get_type(schema) | |
| gc_utils.get_type = _safe_get_type | |
| _orig_json_schema_to_python_type = gc_utils._json_schema_to_python_type | |
| def _safe_json_schema_to_python_type(schema, defs=None): | |
| if not isinstance(schema, dict): | |
| return "Any" | |
| return _orig_json_schema_to_python_type(schema, defs) | |
| gc_utils._json_schema_to_python_type = _safe_json_schema_to_python_type | |
| # --------------------------------------------------------------------------- | |
| import tempfile | |
| import os | |
| import random | |
| import torch | |
| import numpy as np | |
| from PIL import Image | |
| import gradio as gr | |
| from diffusers import StableDiffusionInpaintPipeline | |
| # Lazy pipeline loader for ZeroGPU | |
| pipe_inpaint = None | |
| def get_inpaint_pipeline(): | |
| global pipe_inpaint | |
| if pipe_inpaint is None: | |
| pipe_inpaint = StableDiffusionInpaintPipeline.from_pretrained( | |
| "runwayml/stable-diffusion-inpainting", | |
| torch_dtype=torch.float16, | |
| safety_checker=None | |
| ) | |
| pipe_inpaint.enable_attention_slicing() | |
| return pipe_inpaint | |
| def shift_image(pil_img, mode="Horizontal Only (Landscapes/City Facades)"): | |
| """Shifts image by 50% along selected axes to position outer seams at canvas center.""" | |
| img = np.array(pil_img.convert("RGB")) | |
| h, w, _ = img.shape | |
| if "Horizontal" in mode: | |
| shifted = np.roll(img, w // 2, axis=1) | |
| else: | |
| shifted = np.roll(np.roll(img, h // 2, axis=0), w // 2, axis=1) | |
| return Image.fromarray(shifted) | |
| def create_seam_mask(width, height, seam_width_pct=0.25, mode="Horizontal Only (Landscapes/City Facades)"): | |
| """ | |
| Creates a black-and-white mask. | |
| White = Area to be inpainted by AI (center seam join zone). | |
| Black = Area to keep 100% original photo intact. | |
| """ | |
| mask = np.zeros((height, width), dtype=np.uint8) | |
| if "Horizontal" in mode: | |
| w_seam = int(width * seam_width_pct) | |
| x_start = (width - w_seam) // 2 | |
| mask[:, x_start:x_start + w_seam] = 255 | |
| else: | |
| w_seam = int(width * seam_width_pct) | |
| h_seam = int(height * seam_width_pct) | |
| x_start = (width - w_seam) // 2 | |
| y_start = (height - h_seam) // 2 | |
| mask[:, x_start:x_start + w_seam] = 255 | |
| mask[y_start:y_start + h_seam, :] = 255 | |
| return Image.fromarray(mask) | |
| def create_tiled_preview(pil_img, mode="Horizontal Only (Landscapes/City Facades)"): | |
| """Generates 1x3 horizontal panorama or 3x3 grid preview.""" | |
| preview_img = pil_img.copy() | |
| if preview_img.width > 1024: | |
| preview_img = preview_img.resize((1024, 1024), Image.Resampling.LANCZOS) | |
| w, h = preview_img.size | |
| if "Horizontal" in mode: | |
| tiled = Image.new("RGB", (w * 3, h)) | |
| for c in range(3): | |
| tiled.paste(preview_img, (c * w, 0)) | |
| else: | |
| tiled = Image.new("RGB", (w * 3, h * 3)) | |
| for r in range(3): | |
| for c in range(3): | |
| tiled.paste(preview_img, (c * w, r * h)) | |
| return tiled | |
| def generate_ai_texture(input_image, prompt, method_mode, tiling_mode, seam_width_pct, steps, seed_val, resolution_str, ut99_quantize): | |
| if input_image is None: | |
| return None, None, None, None, "⚠️ Please upload a source photo first." | |
| actual_seed = random.randint(0, 2147483647) if (seed_val == -1 or seed_val is None) else int(seed_val) | |
| res_val = int(resolution_str.split("x")[0]) | |
| pipeline = get_inpaint_pipeline() | |
| pipeline.to("cuda") | |
| generator = torch.Generator("cuda").manual_seed(actual_seed) | |
| # 1. Prepare shifted image and resolution | |
| init_img = input_image.resize((512, 512), Image.Resampling.LANCZOS) | |
| shifted_init = shift_image(init_img, mode=tiling_mode) | |
| # 2. Build Inpainting Mask vs Full Mask | |
| if "Inpainting" in method_mode: | |
| seam_mask = create_seam_mask(512, 512, seam_width_pct=seam_width_pct / 100.0, mode=tiling_mode) | |
| else: | |
| # Full mask regenerates entire canvas | |
| seam_mask = Image.new("L", (512, 512), 255) | |
| user_steps = max(10, int(steps)) | |
| full_prompt = prompt + ", seamless tileable game asset, detailed continuous pattern, high quality" | |
| negative_prompt = "seam line, border, frame, edge line, blur, watermark, distortion" | |
| # 3. Perform AI Inpainting | |
| inpainted_result = pipeline( | |
| prompt=full_prompt, | |
| negative_prompt=negative_prompt, | |
| image=shifted_init, | |
| mask_image=seam_mask, | |
| num_inference_steps=user_steps, | |
| guidance_scale=7.5, | |
| generator=generator | |
| ).images[0] | |
| # 4. Upscale to target resolution (up to 8K) | |
| final_img = inpainted_result.resize((res_val, res_val), Image.Resampling.LANCZOS) | |
| tiled_preview = create_tiled_preview(final_img, mode=tiling_mode) | |
| # 5. Export 8-bit UT99 Formats (.PCX / .BMP) | |
| temp_dir = tempfile.mkdtemp() | |
| pcx_path = os.path.join(temp_dir, f"ut99_texture_{res_val}.pcx") | |
| bmp_path = os.path.join(temp_dir, f"ut99_texture_{res_val}.bmp") | |
| if ut99_quantize: | |
| quantized = final_img.convert("P", palette=Image.Palette.ADAPTIVE, colors=256) | |
| quantized.save(pcx_path, format="PCX") | |
| quantized.save(bmp_path, format="BMP") | |
| display_img = quantized.convert("RGB") | |
| else: | |
| final_img.save(pcx_path, format="PCX") | |
| final_img.save(bmp_path, format="BMP") | |
| display_img = final_img | |
| status_msg = f"✅ Success | Method: {method_mode} | Seed: {actual_seed} | Output: {res_val}x{res_val}" | |
| return display_img, tiled_preview, pcx_path, bmp_path, status_msg | |
| # Gradio Interface | |
| with gr.Blocks(title="UT99 ZeroGPU AI Texture Forge") as demo: | |
| gr.Markdown("# ⚡ UT99 ZeroGPU AI Texture Forge") | |
| gr.Markdown("Generate seamless 8-bit UT99 textures using Smart Seam Inpainting or Full AI Synthesis.") | |
| with gr.Row(): | |
| with gr.Column(): | |
| input_img = gr.Image(type="pil", label="Upload Source Photo") | |
| method_mode = gr.Radio( | |
| choices=["⚡ Smart Seam Inpainting (Preserves Photo)", "🎨 Full Canvas Generation"], | |
| value="⚡ Smart Seam Inpainting (Preserves Photo)", | |
| label="Generation Method" | |
| ) | |
| tiling_mode = gr.Radio( | |
| choices=["Horizontal Only (Landscapes/City Facades)", "Full 2D (Both Axes)"], | |
| value="Horizontal Only (Landscapes/City Facades)", | |
| label="Seamless Axis Mode" | |
| ) | |
| prompt = gr.Textbox( | |
| value="Mountain ridge horizon panorama, detailed rocky landscape texture", | |
| label="AI Inpainting Prompt (Describe how the seam should blend)" | |
| ) | |
| seam_width_pct = gr.Slider( | |
| minimum=10, maximum=50, value=25, step=5, | |
| label="Inpaint Seam Width (% of image centered over join)" | |
| ) | |
| with gr.Row(): | |
| steps = gr.Slider(minimum=10, maximum=40, value=20, step=1, label="Denoising Steps") | |
| seed_val = gr.Number(value=-1, precision=0, label="Seed (-1 = Random)") | |
| resolution = gr.Dropdown( | |
| choices=[ | |
| "128x128", | |
| "256x256 (Default UT99)", | |
| "512x512 (HD UT99)", | |
| "1024x1024", | |
| "2048x2048 (2K)", | |
| "4096x4096 (4K)", | |
| "8192x8192 (8K)" | |
| ], | |
| value="512x512 (HD UT99)", | |
| label="Output Resolution" | |
| ) | |
| ut99_quantize = gr.Checkbox( | |
| value=True, | |
| label="Convert to 8-Bit / 256 Colors (.PCX / .BMP)" | |
| ) | |
| btn = gr.Button("🚀 Generate AI Inpainted Texture", variant="primary") | |
| with gr.Column(): | |
| output_status = gr.Textbox(label="Status / Seed", interactive=False) | |
| output_texture = gr.Image(type="pil", label="Generated Texture") | |
| output_preview = gr.Image(type="pil", label="Tiling Preview Test") | |
| with gr.Row(): | |
| pcx_file = gr.File(label="Download .PCX") | |
| bmp_file = gr.File(label="Download .BMP") | |
| btn.click( | |
| fn=generate_ai_texture, | |
| inputs=[ | |
| input_img, prompt, method_mode, tiling_mode, | |
| seam_width_pct, steps, seed_val, resolution, ut99_quantize | |
| ], | |
| outputs=[output_texture, output_preview, pcx_file, bmp_file, output_status] | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch(show_api=False) | |