Spaces:
Build error
Build error
| import gradio as gr | |
| import requests | |
| from PIL import Image | |
| from io import BytesIO | |
| import random | |
| # --- Configuration --- | |
| # Using SDXL Turbo as the engine for high-speed generation | |
| MODEL_API_URL = "https://api-inference.huggingface.co/models/stabilityai/sdxl-turbo" | |
| # --- Helper Functions --- | |
| def query_huggingface_api(payload, token): | |
| """ | |
| Sends a request to the Hugging Face Inference API. | |
| """ | |
| headers = {"Authorization": f"Bearer {token}"} | |
| response = requests.post(MODEL_API_URL, headers=headers, json=payload) | |
| if response.status_code != 200: | |
| error_data = {} | |
| try: | |
| error_data = response.json() | |
| except: | |
| pass | |
| if response.status_code == 503: | |
| raise gr.Error("Model is warming up. Please try again in a moment.") | |
| elif response.status_code == 401: | |
| raise gr.Error("Invalid Access Token. Please check your credentials.") | |
| elif response.status_code == 429: | |
| raise gr.Error("Rate limit exceeded. Please wait a moment.") | |
| else: | |
| error_msg = error_data.get("error", f"Error {response.status_code}") | |
| raise gr.Error(f"API Error: {error_msg}") | |
| return response.content | |
| def generate_image( | |
| prompt: str, | |
| token: str, | |
| negative_prompt: str = "", | |
| steps: int = 2, | |
| guidance_scale: float = 0.0, | |
| progress=gr.Progress() | |
| ): | |
| """ | |
| Main generation function. | |
| """ | |
| if not token or not token.startswith("hf_"): | |
| raise gr.Error("Please enter a valid Hugging Face Access Token (starts with 'hf_').") | |
| if not prompt: | |
| raise gr.Error("Please enter a text prompt.") | |
| progress(0.1, desc="Initializing...") | |
| payload = { | |
| "inputs": prompt, | |
| "parameters": { | |
| "negative_prompt": negative_prompt, | |
| "num_inference_steps": int(steps), | |
| "guidance_scale": float(guidance_scale) | |
| } | |
| } | |
| progress(0.5, desc="Generating...") | |
| try: | |
| image_bytes = query_huggingface_api(payload, token) | |
| image = Image.open(BytesIO(image_bytes)) | |
| progress(1.0, desc="Done!") | |
| return image | |
| except Exception as e: | |
| if isinstance(e, gr.Error): | |
| raise e | |
| raise gr.Error(f"An unexpected error occurred: {str(e)}") | |
| def get_random_prompt(): | |
| """Returns a random creative prompt.""" | |
| prompts = [ | |
| "A cinematic shot of a futuristic astronaut standing on Mars, golden hour lighting, hyperrealistic, 8k", | |
| "A cute robot painting a canvas in a garden, watercolor style, soft colors, highly detailed", | |
| "Cyberpunk street food vendor in Tokyo, neon rain reflections, volumetric lighting", | |
| "A majestic lion made of clouds in a blue sky, fantasy art, dreamlike atmosphere", | |
| "Portrait of a warrior with intricate golden armor, digital painting, dramatic lighting", | |
| "A cozy library inside a giant tree, magical atmosphere, fireflies, warm lighting", | |
| "Futuristic sports car concept, sleek design, neon trim, motion blur, dark city background" | |
| ] | |
| return random.choice(prompts) | |
| # --- Gradio 6 Application --- | |
| # Custom CSS to mimic the dark/tech vibe of the original HTML | |
| custom_css = """ | |
| body { | |
| background-color: #0f172a; | |
| color: #f8fafc; | |
| } | |
| .gradio-container { | |
| background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%); | |
| max-width: 1400px !important; | |
| } | |
| #header-text { | |
| font-family: 'Courier New', monospace; | |
| font-weight: bold; | |
| color: #6366f1; | |
| text-transform: uppercase; | |
| letter-spacing: 2px; | |
| } | |
| """ | |
| # Define the Theme | |
| custom_theme = gr.themes.Soft( | |
| primary_hue="indigo", | |
| secondary_hue="pink", | |
| neutral_hue="slate", | |
| font=gr.themes.GoogleFont("Outfit"), | |
| text_size="lg", | |
| spacing_size="lg", | |
| radius_size="md" | |
| ).set( | |
| button_primary_background_fill="linear-gradient(90deg, #6366f1 0%, #ec4899 100%)", | |
| button_primary_background_fill_hover="linear-gradient(90deg, #4f46e5 0%, #db2777 100%)", | |
| button_primary_text_color="white", | |
| block_background_fill="*neutral_950", | |
| block_border_color="*neutral_800", | |
| block_shadow="0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)", | |
| block_title_text_weight="600", | |
| block_title_text_color="*primary_300", | |
| ) | |
| with gr.Blocks(theme=custom_theme, css=custom_css) as demo: | |
| # Header | |
| gr.HTML(""" | |
| <div style="display: flex; justify-content: space-between; align-items: center; padding: 20px; border-bottom: 1px solid rgba(255,255,255,0.1);"> | |
| <div id="header-text" style="font-size: 1.5rem;"> | |
| <i class="fa-solid fa-bolt"></i> Z-Image Turbo | |
| </div> | |
| <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: #94a3b8; text-decoration: none; font-size: 0.9rem; border: 1px solid rgba(255,255,255,0.1); padding: 8px 16px; border-radius: 20px; transition: all 0.3s;"> | |
| Built with anycoder <i class="fa-solid fa-arrow-up-right-from-square" style="font-size: 0.7em;"></i> | |
| </a> | |
| </div> | |
| """) | |
| gr.Markdown("Generate high-quality images in seconds using the SDXL Turbo engine.", elem_classes="text-center") | |
| with gr.Row(): | |
| # --- Left Column: Controls --- | |
| with gr.Column(scale=1): | |
| with gr.Group(): | |
| gr.Markdown("### 🛠️ Configuration") | |
| # Authentication | |
| token_input = gr.Textbox( | |
| label="Hugging Face Access Token", | |
| placeholder="hf_...", | |
| type="password", | |
| info="Your token is required to access the API. It is not stored on the server.", | |
| scale=9 | |
| ) | |
| # Prompts | |
| prompt_input = gr.Textbox( | |
| label="Prompt", | |
| placeholder="Describe the image you want to generate...", | |
| lines=3, | |
| info="Be descriptive for better results." | |
| ) | |
| with gr.Row(): | |
| random_btn = gr.Button("🎲 Surprise Me", size="sm", scale=1) | |
| clear_btn = gr.Button("🗑️ Clear", size="sm", scale=1) | |
| negative_prompt_input = gr.Textbox( | |
| label="Negative Prompt", | |
| placeholder="blur, low quality, distortion...", | |
| lines=1, | |
| info="Elements to avoid in the image." | |
| ) | |
| # Parameters | |
| with gr.Accordion("Advanced Settings", open=False): | |
| steps_slider = gr.Slider( | |
| minimum=1, | |
| maximum=4, | |
| step=1, | |
| value=2, | |
| label="Inference Steps", | |
| info="Turbo models work best with 1-4 steps." | |
| ) | |
| guidance_slider = gr.Slider( | |
| minimum=0.0, | |
| maximum=2.0, | |
| step=0.1, | |
| value=0.0, | |
| label="Guidance Scale", | |
| info="Lower values (0.0-1.0) often work best for Turbo." | |
| ) | |
| generate_btn = gr.Button( | |
| "✨ Generate Image", | |
| variant="primary", | |
| size="lg" | |
| ) | |
| # --- Right Column: Output --- | |
| with gr.Column(scale=2): | |
| with gr.Group(): | |
| gr.Markdown("### 🖼️ Result") | |
| output_image = gr.Image( | |
| label="Generated Image", | |
| type="pil", | |
| height=600, | |
| show_label=False, | |
| show_download_button=True, | |
| interactive=False | |
| ) | |
| # Status/Info | |
| status_text = gr.Markdown("", visible=False) | |
| # --- Event Listeners --- | |
| # Random Prompt Logic | |
| random_btn.click( | |
| fn=get_random_prompt, | |
| outputs=prompt_input | |
| ) | |
| # Clear Logic | |
| clear_btn.click( | |
| fn=lambda: ("", "", None), | |
| outputs=[prompt_input, negative_prompt_input, output_image] | |
| ) | |
| # Generate Logic | |
| generate_btn.click( | |
| fn=generate_image, | |
| inputs=[ | |
| prompt_input, | |
| token_input, | |
| negative_prompt_input, | |
| steps_slider, | |
| guidance_slider | |
| ], | |
| outputs=output_image, | |
| api_name="generate", | |
| api_visibility="public" | |
| ) | |
| # --- Footer Links --- | |
| footer_links = [ | |
| {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}, | |
| {"label": "Gradio", "url": "https://gradio.app"}, | |
| {"label": "Hugging Face", "url": "https://huggingface.co"} | |
| ] | |
| # --- Launch --- | |
| demo.launch( | |
| footer_links=footer_links | |
| ) |