Spaces:
Paused
Paused
Upload 2 files
Browse filesFiles changed (2)
- app.py+29-395
- requirements.txt+3-3
123456789101112131415161718192021222324252627283 unmodified lines32333435363738394041424344454647484950515253545556575859606162631 unmodified line6566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444import gradio as grimport requestsimport jsonimport osfrom PIL import Imageimport ioimport timefrom datetime import datetime# Get API key from Hugging Face secretsdef get_api_key():return os.environ.get("PIXAZO_API_KEY")# Call Pixazo APIdef call_pixazo_api(prompt, num_steps=4, seed=None, height=512, width=512,style_preset=None, guidance_scale=None):api_key = get_api_key()if not api_key:return None, {"error": "API key not configured","instructions": "Please set PIXAZO_API_KEY in Hugging Face Space secrets","timestamp": datetime.now().isoformat()}url = "https://gateway.pixazo.ai/flux-1-schnell/v1/getData"3 unmodified lines'Ocp-Apim-Subscription-Key': api_key,}# Prepare request bodybody = {"prompt": prompt,"num_steps": num_steps,"height": height,"width": width,}if seed and seed > 0:body["seed"] = seedif style_preset and style_preset != "none":body["style_preset"] = style_presetif guidance_scale:body["guidance_scale"] = guidance_scaletry:print(f"🌐 Sending request to Pixazo API...")response = requests.post(url,headers=headers,json=body,timeout=120)print(f"✅ Response status: {response.status_code}")if response.status_code == 200:result = response.json()1 unmodified lineif "output" in result:image_url = result["output"]# Download the image from the URLtry:print(f"⬇️ Downloading image from URL...")img_response = requests.get(image_url, timeout=30, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'})if img_response.status_code == 200:image = Image.open(io.BytesIO(img_response.content))# Convert to RGB if necessaryif image.mode in ('RGBA', 'LA', 'P'):image = image.convert('RGB')return image, {"success": True,"status_code": 200,"image_url_preview": image_url[:80] + "..." if len(image_url) > 80 else image_url,"image_size": f"{image.size[0]}x{image.size[1]}","image_format": image.format if hasattr(image, 'format') else "Unknown","timestamp": datetime.now().isoformat()}else:return None, {"error": f"Failed to download image: HTTP {img_response.status_code}","image_url": image_url[:80] + "..." if len(image_url) > 80 else image_url,"download_status": img_response.status_code,"timestamp": datetime.now().isoformat()}except Exception as e:return None, {"error": f"Error downloading image: {str(e)}","image_url": image_url[:80] + "..." if len(image_url) > 80 else image_url,"timestamp": datetime.now().isoformat()}else:return None, {"error": "Response missing 'output' field","response_keys": list(result.keys()),"timestamp": datetime.now().isoformat()}else:try:error_data = response.json()error_msg = error_data.get("error", str(error_data))except:error_msg = response.text[:200] if response.text else "No error message"return None, {"error": f"API returned status {response.status_code}: {error_msg}","status_code": response.status_code,"timestamp": datetime.now().isoformat()}except requests.exceptions.Timeout:return None, {"error": "Request timed out after 120 seconds","suggestion": "Try reducing image size or number of steps","timestamp": datetime.now().isoformat()}except requests.exceptions.RequestException as e:return None, {"error": f"Network error: {str(e)}","timestamp": datetime.now().isoformat()}except Exception as e:return None, {"error": f"Unexpected error: {str(e)}","timestamp": datetime.now().isoformat()}# Create the Gradio interface with correct Gradio 6.x APIwith gr.Blocks(title="Pixazo Image Generator") as demo:# Custom CSSdemo.css = """.success { color: #10b981 !important; }.error { color: #ef4444 !important; }.warning { color: #f59e0b !important; }.api-status {padding: 12px 16px;border-radius: 8px;margin-bottom: 20px;}.api-status-success {background: #d1fae5;border-left: 4px solid #10b981;}.api-status-error {background: #fee2e2;border-left: 4px solid #ef4444;}.example-prompt {cursor: pointer;padding: 10px;border-radius: 6px;margin: 5px 0;background: #f8fafc;border: 1px solid #e2e8f0;}.example-prompt:hover {background: #e2e8f0;}"""# Headergr.Markdown("""# 🎨 Pixazo AI Image GeneratorCreate stunning images with FLUX-1 Schnell model""")# API Statusapi_key = get_api_key()if api_key:gr.Markdown("""<div class="api-status api-status-success"><strong>✅ API Status:</strong> Connected (API key configured)</div>""")else:gr.Markdown("""<div class="api-status api-status-error"><strong>❌ API Status:</strong> Not Configured<p style="margin: 8px 0 0 0; font-size: 0.9em;"><strong>Setup:</strong> Go to Space Settings → Repository secrets → Add: <code>PIXAZO_API_KEY</code> = your key</p></div>""")with gr.Row():# Left column - Inputswith gr.Column(scale=1, min_width=400):# Generation Settings groupwith gr.Group():gr.Markdown("### 🎨 Generation Settings")prompt = gr.Textbox(label="Image Prompt",placeholder="Describe what you want to generate...",lines=3,max_lines=5)with gr.Row():style_preset = gr.Dropdown(label="Style Preset",choices=["none", "cyberpunk", "fantasy", "anime", "photographic","digital-art", "comic", "3d-model", "pixel-art","isometric", "watercolor", "oil-painting"],value="none",scale=2)guidance_scale = gr.Slider(label="Guidance Scale",minimum=1.0,maximum=20.0,value=7.5,step=0.5,scale=1)with gr.Row():num_steps = gr.Slider(label="Number of Steps",minimum=1,maximum=50,value=4,step=1,scale=1)seed = gr.Number(label="Seed",value=42,minimum=0,maximum=999999,scale=1)with gr.Row():width = gr.Slider(label="Width",minimum=256,maximum=1024,value=512,step=64,scale=1)height = gr.Slider(label="Height",minimum=256,maximum=1024,value=512,step=64,scale=1)num_images = gr.Slider(label="Number of Images",minimum=1,maximum=8,value=1,step=1)with gr.Row():generate_btn = gr.Button("✨ Generate Images", variant="primary", scale=2)clear_btn = gr.Button("🗑️ Clear", variant="secondary", scale=1)# Quick exampleswith gr.Accordion("💡 Example Prompts", open=False):examples = [("Cyberpunk city at night with neon lights and flying cars", "cyberpunk"),("Majestic dragon on a mountain peak, fantasy art", "fantasy"),("Cute anime cat in a magical forest", "anime"),("Photorealistic portrait of an astronaut on Mars", "photographic"),("Isometric office scene with plants and computers", "isometric"),]for example_prompt, example_style in examples:with gr.Row():prompt_text = gr.Textbox(value=example_prompt,show_label=False,interactive=False,scale=3)use_btn = gr.Button("Use", size="sm", scale=1)def use_example(p=example_prompt, s=example_style):return p, suse_btn.click(use_example,outputs=[prompt, style_preset])# Right column - Outputswith gr.Column(scale=2, min_width=600):status = gr.Textbox(label="Status",value="Ready to generate images...",interactive=False)gallery = gr.Gallery(label="Generated Images",columns=2,height="auto",object_fit="contain",show_label=True,preview=True)with gr.Accordion("📊 Detailed Response", open=False):json_output = gr.JSON(label="API Response",container=True)# Footergr.Markdown("""---<div style="text-align: center; color: #666; font-size: 0.9em; margin-top: 20px;"><p><strong>API Response Format:</strong> <code>{"output": "IMAGE_URL"}</code></p><p>Built with Gradio • Powered by Pixazo FLUX-1 Schnell</p></div>""")# Event handlersdef on_generate(prompt, num_steps, seed, height, width, style_preset, num_images, guidance_scale):if not prompt.strip():yield "❌ Please enter a prompt first", None, {"error": "No prompt provided"}returnimages = []all_results = []yield "🚀 Starting generation...", None, {"status": "starting"}for i in range(num_images):try:current_seed = seed + i if seed > 0 else 0image, result = call_pixazo_api(prompt=prompt,num_steps=num_steps,seed=current_seed,height=height,width=width,style_preset=style_preset,guidance_scale=guidance_scale)if image:images.append(image)all_results.append(result)status_text = f"Generated {i+1}/{num_images} images"if "error" in result:status_text = f"Image {i+1} error: {result['error'][:50]}..."yield status_text, images if images else None, resultif i < num_images - 1:time.sleep(1)except Exception as e:error_result = {"error": str(e), "image_index": i}all_results.append(error_result)yield f"Exception on image {i+1}: {str(e)[:50]}", images if images else None, error_resultbreak# Final summarysuccess_count = len(images)if success_count == 0:final_status = f"❌ No images generated ({success_count}/{num_images} successful)"elif success_count < num_images:final_status = f"⚠️ Partial success: {success_count}/{num_images} images"else:final_status = f"🎉 Success! All {success_count} images generated"summary = {"summary": {"total_attempts": num_images,"successful": success_count,"failed": num_images - success_count},"parameters": {"prompt_length": len(prompt),"steps": num_steps,"resolution": f"{width}x{height}","style": style_preset}}yield final_status, images if images else None, summarydef on_clear():return "Ready to generate images...", None, None# Connect buttonsgenerate_btn.click(fn=on_generate,inputs=[prompt, num_steps, seed, height, width, style_preset, num_images, guidance_scale],outputs=[status, gallery, json_output])clear_btn.click(fn=on_clear,outputs=[status, gallery, json_output])# Launch the appif __name__ == "__main__":print("=" * 60)print("🚀 Pixazo Image Generator")print(f"📦 Gradio Version: {gr.__version__}")print(f"🔑 API Key Configured: {'Yes' if get_api_key() else 'No'}")print("=" * 60)demo.launch(server_name="0.0.0.0",server_port=7860,share=False,show_api=False,theme=gr.themes.Soft(primary_hue="purple", secondary_hue="pink"),css=demo.css if hasattr(demo, 'css') else "")12345678910111213141516173 unmodified lines2122232425262728293031323334351 unmodified line373839404142434445464748495051525354555657585960616263646566676869707172737475767778import gradio as grimport requestsimport osfrom PIL import Imageimport iofrom datetime import datetimedef get_api_key():return os.environ.get("PIXAZO_API_KEY")def generate_image(prompt):api_key = get_api_key()if not api_key:return None, "❌ API key not set"url = "https://gateway.pixazo.ai/flux-1-schnell/v1/getData"3 unmodified lines'Ocp-Apim-Subscription-Key': api_key,}body = {"prompt": prompt,"num_steps": 4,"height": 512,"width": 512,}try:response = requests.post(url, headers=headers, json=body, timeout=60)if response.status_code == 200:result = response.json()1 unmodified lineif "output" in result:image_url = result["output"]img_response = requests.get(image_url, timeout=30)if img_response.status_code == 200:image = Image.open(io.BytesIO(img_response.content))if image.mode in ('RGBA', 'LA', 'P'):image = image.convert('RGB')return image, "✅ Image generated successfully!"else:return None, f"❌ Failed to download image: HTTP {img_response.status_code}"else:return None, "❌ No image URL in response"else:return None, f"❌ API error: {response.status_code}"except Exception as e:return None, f"❌ Error: {str(e)}"# Simple interfacewith gr.Blocks(title="Pixazo Image Generator") as demo:gr.Markdown("# 🎨 Pixazo Image Generator")api_key = get_api_key()if api_key:gr.Markdown("✅ API Key: Configured")else:gr.Markdown("❌ API Key: Not configured. Set PIXAZO_API_KEY in secrets.")with gr.Row():with gr.Column():prompt = gr.Textbox(label="Prompt", lines=3)btn = gr.Button("Generate", variant="primary")with gr.Column():image = gr.Image(label="Generated Image")status = gr.Textbox(label="Status", interactive=False)btn.click(generate_image, inputs=prompt, outputs=[image, status])if __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860)
123gradio==5.10.0pillow>=10.0.0requests>=2.31.0123gradio==6.2.0pillow==10.4.0requests==2.32.3
app.py+29-395
requirements.txt+3-3