| |
| import gradio as gr |
| import torch |
| from diffusers import StableDiffusionPipeline |
| import time |
| import base64 |
| from io import BytesIO |
| import json |
|
|
| |
| MODEL_ID = "OFA-Sys/small-stable-diffusion-v0" |
| DEVICE = "cpu" |
|
|
| |
| print("π Loading Stable Diffusion model...") |
| try: |
| pipe = StableDiffusionPipeline.from_pretrained( |
| MODEL_ID, |
| torch_dtype=torch.float32, |
| safety_checker=None, |
| requires_safety_checker=False |
| ) |
| pipe = pipe.to(DEVICE) |
| print("β
Model loaded successfully!") |
| except Exception as e: |
| print(f"β Model loading failed: {e}") |
| pipe = None |
|
|
| |
| def generate_image_api( |
| prompt: str, |
| negative_prompt: str = "", |
| steps: int = 25, |
| width: int = 512, |
| height: int = 512, |
| seed: int = -1 |
| ): |
| """ |
| API endpoint for WordPress automation |
| Returns: {"image": "base64_string", "status": "message"} |
| """ |
| |
| if pipe is None: |
| return { |
| "error": "Model not loaded", |
| "data": [] |
| } |
| |
| try: |
| print(f"πΈ API call: {prompt[:50]}...") |
| |
| |
| generator = None |
| if seed != -1: |
| generator = torch.Generator(device=DEVICE).manual_seed(seed) |
| |
| |
| start_time = time.time() |
| image = pipe( |
| prompt=prompt, |
| negative_prompt=negative_prompt, |
| num_inference_steps=steps, |
| width=width, |
| height=height, |
| guidance_scale=7.5, |
| generator=generator |
| ).images[0] |
| |
| gen_time = time.time() - start_time |
| |
| |
| buffered = BytesIO() |
| image.save(buffered, format="PNG") |
| img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8') |
| |
| |
| return { |
| "data": [ |
| f"data:image/png;base64,{img_base64}", |
| f"β
Generated in {gen_time:.1f}s" |
| ] |
| } |
| |
| except Exception as e: |
| return { |
| "error": str(e), |
| "data": [] |
| } |
|
|
| |
| def generate_image_ui(prompt, negative_prompt="", steps=25, width=512, height=512, seed=-1): |
| """For UI display only""" |
| result = generate_image_api(prompt, negative_prompt, steps, width, height, seed) |
| |
| if "error" in result: |
| return None, f"β Error: {result['error']}" |
| |
| |
| img_data = result["data"][0].split(",")[1] |
| img_bytes = base64.b64decode(img_data) |
| image = gr.Image().pil_to_bytes(img_bytes) |
| |
| return image, result["data"][1] |
|
|
| |
| with gr.Blocks(title="Stable Diffusion API", theme=gr.themes.Soft()) as demo: |
| gr.Markdown(""" |
| # π¨ Stable Diffusion Image Generator |
| ## β
**API ENDPOINT EXPOSED:** `/api/predict` |
| |
| ### For WordPress Automation: |
| ```bash |
| curl -X POST https://huggingface.co/spaces/AllanHill/CdGarment/api/predict \\ |
| -H "Content-Type: application/json" \\ |
| -d '{ |
| "data": [ |
| "your prompt here", |
| "negative prompt", |
| 25, |
| 512, |
| 512, |
| -1 |
| ] |
| }' |
| ``` |
| |
| **Response format:** |
| ```json |
| { |
| "data": [ |
| "data:image/png;base64,iVBORw0KGgo...", |
| "β
Generated in 12.3s" |
| ] |
| } |
| ``` |
| """) |
| |
| |
| with gr.Row(): |
| prompt = gr.Textbox(label="Prompt", placeholder="Textile factory...", lines=2) |
| generate_btn = gr.Button("Test Generate", variant="secondary") |
| |
| with gr.Row(): |
| output_image = gr.Image(label="Preview") |
| output_status = gr.Textbox(label="API Status") |
| |
| generate_btn.click( |
| fn=generate_image_ui, |
| inputs=[prompt], |
| outputs=[output_image, output_status] |
| ) |
|
|
| |
| if __name__ == "__main__": |
| demo.launch(debug=True) |