Spaces:
Runtime error
Runtime error
Update app.py
Browse files1233456789101011121314141516174 unmodified lines22232425252627282 unmodified lines3132333434353630 unmodified lines676869717071721 unmodified line747576777879808110 unmodified lines9293949596979899991001011021032 unmodified lines1061071081091101111123 unmodified lines1161171181171191201211221234 unmodified lines12812913012813113213325 unmodified lines1591601611601621631648 unmodified lines17317417517517617717812 unmodified lines19119219319419419519623 unmodified lines2202212222242252262272232242252262272281 unmodified line2302312322352362332342353 unmodified lines2392402412462472482492502422432442452462472482492501 unmodified line25225325425825525625725811 unmodified lines2702712722762732742782792802752762771 unmodified line2792802812882822832848 unmodified lines2932942953032962972982991 unmodified line30130230331130430530630717 unmodified lines32532632733533633732832933033933133233312 unmodified lines3463473483583493503513521 unmodified line3543553563663673573583593603612 unmodified lines36436536636737636836937037137237337438337537637737837938838038139039139238238338438538638738838939839039139239339417 unmodified lines41241341442241541641742641841942042142243142342442542622 unmodified lines44945045146046145245345445532 unmodified lines4884894905004914925024934944955054964975074984995005014 unmodified lines506507508518509510511512513524514515516517518519530520521522import base64import ioimport osfrom typing import List, Tuple, Optional
import gradio as grfrom PIL import Image
# -----------------------# Optional imports guarded at call-time# OpenAI + Google helpers# -----------------------
def _get_openai_client(api_key: str): from openai import OpenAI # imported here to avoid issues if lib missing from openai import OpenAI # local import so app still loads if lib missing return OpenAI(api_key=api_key)
4 unmodified lines
# -----------------------# Helper: apply visual presets# Prompt / preset logic# -----------------------
def apply_preset_to_prompt(2 unmodified lines style: str, content_type: str,) -> str: """Augment the prompt with preset & style language.""" base_prompt = base_prompt.strip()
preset_addons = {30 unmodified lines "Cinematic": " cinematic lighting, dramatic composition, filmic contrast", }
ct_addon = "" if content_type == "Image": ct_addon = " high-resolution concept art," elif content_type == "Infographic Spec":1 unmodified line " detailed infographic design specification, including layout regions, " "sections, labels, and visual hierarchy," ) else: ct_addon = ""
extra = " ".join( x10 unmodified lines return f"{base_prompt}, {extra}" else: return extra.strip()
return base_prompt or "high quality image"
# -----------------------# OpenAI: Text + Image# OpenAI text + images# -----------------------
def generate_text_openai(2 unmodified lines mode: str,) -> str: client = _get_openai_client(api_key)
system_msg = ( "You are an expert creator for the ZEN AI ecosystem. " "Write clear, concise, high-leverage content. "3 unmodified lines
if mode == "Infographic Spec": user_prompt = ( f"Create a Palantir/Anduril-level infographic specification based on:\n\n{prompt}\n\n" "Create a Palantir/Anduril-level infographic specification based on this topic:\n\n" f"{prompt}\n\n" "Return:\n" "1) Title options\n" "2) 3–5 main sections\n"4 unmodified lines else: user_prompt = prompt
# Using Chat Completions interface resp = client.chat.completions.create( model="gpt-4.1-mini", messages=[25 unmodified lines) -> List[Image.Image]: client = _get_openai_client(api_key)
# Map size choices to OpenAI-supported ones size_map = { "Square (1024x1024)": "1024x1024", "Portrait (1024x1792)": "1024x1792",8 unmodified lines "quality": quality, "n": n_images, } # seed is optional on some models; safe to include conditionally if seed is not None: kwargs["seed"] = seed
12 unmodified lines mode: str,) -> str: genai = _configure_google(api_key) # Default to a strong text model model = genai.GenerativeModel("gemini-1.5-pro")
if mode == "Infographic Spec":23 unmodified lines seed: Optional[int],) -> List[Image.Image]: """ NOTE: Model & output handling may need adjustment depending on the exact Nano-Banana / Nano-Banana-Pro API you use in Google AI Studio.
This assumes a GenerativeModel that returns inline image data. This assumes your Nano-Banana / Nano-Banana-Pro image model in Google AI Studio returns inline image bytes in the response. Adjust parsing if your model behaves differently. """ genai = _configure_google(api_key) model = genai.GenerativeModel(google_image_model)1 unmodified line images: List[Image.Image] = []
for i in range(n_images): # Some image models support generation_config with a seed; # here we pass it if present. generation_config = {} if seed is not None: generation_config["seed"] = seed + i3 unmodified lines generation_config=generation_config or None, )
# Try to pull image bytes from response parts for cand in resp.candidates: for part in cand.content.parts: if hasattr(part, "inline_data") and getattr(part.inline_data, "data", None): raw = base64.b64decode(part.inline_data.data) # Extract images from candidates for cand in getattr(resp, "candidates", []): for part in getattr(cand, "content", {}).parts: inline = getattr(part, "inline_data", None) if inline and getattr(inline, "data", None): raw = base64.b64decode(inline.data) img = Image.open(io.BytesIO(raw)).convert("RGB") images.append(img)
1 unmodified line
# -----------------------# Core Gradio callback# Core callback# -----------------------
def run_generation(11 unmodified lines seed: int, use_seed: bool, google_image_model: str, google_text_model_hint: str, google_text_model_hint: str, # currently just logged) -> Tuple[str, List[Image.Image], str]: """ Returns: (text_output, images, debug_info) """ text_output = "" images: List[Image.Image] = [] debug_lines = []1 unmodified line if not base_prompt.strip(): return "Please enter a prompt.", [], "No prompt provided."
# Build full prompt for images content_type = "Image" if task_type == "Image" else task_type full_prompt = apply_preset_to_prompt( base_prompt=base_prompt,8 unmodified lines debug_lines.append(f"Task: {task_type}") debug_lines.append(f"Provider: {provider}") debug_lines.append(f"Preset: {preset}, Style: {style}") debug_lines.append(f"OpenAI model size: {size}, quality: {quality}") debug_lines.append(f"OpenAI size: {size}, quality: {quality}") debug_lines.append(f"Google image model: {google_image_model}") debug_lines.append(f"Google text model hint: {google_text_model_hint}") debug_lines.append(f"Seed enabled: {use_seed}, seed: {seed if use_seed else 'None'}")1 unmodified line seed_val: Optional[int] = seed if use_seed else None
try: # TEXT or INFOGRAPHIC # TEXT / INFOGRAPHIC if task_type in ["Text", "Infographic Spec"]: if provider == "OpenAI": if not openai_key.strip():17 unmodified lines if provider == "OpenAI": if not openai_key.strip(): return "Missing OpenAI API key.", [], "OpenAI key not provided." # Decide OpenAI image model based on preset selection or UI (we can infer) # We'll expose choice via size/style; model stays fixed to user-facing dropdown externally # but here we assume they want GPT-Image-1 by default
# Default to GPT-Image-1; for Palantir preset, swap to DALL·E 3 image_model = "gpt-image-1" # For Palantir/Anduril preset, sometimes DALL·E 3 is good – user can switch later by editing code. if "Palantir" in preset: image_model = "dall-e-3"
12 unmodified lines return "Missing Google API key.", [], "Google key not provided." images = generate_image_google( api_key=google_key.strip(), google_image_model=google_image_model.strip(), google_image_model=google_image_model.strip() or "nano-banana-pro", prompt=full_prompt, n_images=n_images, seed=seed_val,1 unmodified line
if not text_output and task_type == "Image": text_output = ( "Image(s) generated successfully. Add 'Text' or 'Infographic Spec' mode " "to generate descriptive copy or specs." "Image(s) generated. Use Text / Infographic Spec mode to " "generate captions, copy, or layout specs." )
if not images and task_type == "Image":2 unmodified lines return text_output, images, "\n".join(debug_lines)
except Exception as e: debug_lines.append(f"Exception: {e}") return f"Error: {e}", [], "\n".join(debug_lines + [f"Exception: {e}"]) return f"Error: {e}", [], "\n".join(debug_lines)
# -----------------------# UI# -----------------------
with gr.Blocks(theme=gr.themes.Soft()) as demo:with gr.Blocks() as demo: # <- no theme arg gr.Markdown( """# 🧬 ZEN Omni Studio — Text • Images • Infographics
A unified creator for the ZEN ecosystem.Multi-provider creator for the ZEN ecosystem:
- 🔑 **Bring your own keys** for OpenAI + Google (Gemini / Nano-Banana).- 🧠 Generate **text** and **infographic specs** for ZEN, AI literacy, dashboards, and more.- 🎨 Generate **high-quality images** with advanced controls and presets.- 🔑 Bring your own OpenAI + Google (Gemini / Nano-Banana / Nano-Banana-Pro) keys - 🎨 Generate **images** with presets + fine-grained controls - 🧠 Generate **text** and **infographic specs** for ZEN dashboards, posters, and more """ )
with gr.Row(): with gr.Column(): gr.Markdown("### 🔐 API Keys (kept only in your browser session)") gr.Markdown("### 🔐 API Keys (local to this session)")
openai_key = gr.Textbox( label="OPENAI_API_KEY", type="password",17 unmodified lines label="Primary Provider", )
# Prompt region base_prompt = gr.Textbox( label="Main Prompt", lines=5, placeholder="Describe what you want to create for ZEN (image, copy, infographic, etc.)", placeholder="Describe the ZEN image, text, or infographic you want.", ) negative_prompt = gr.Textbox( label="Negative Prompt (optional)", lines=2, placeholder="Things to avoid: low-res, cluttered, distorted text, etc.", placeholder="Things to avoid: low-res, clutter, warped text, etc.", )
with gr.Row():22 unmodified lines label="Style Accent", )
# OpenAI image options gr.Markdown("### 🎛 OpenAI Image Controls (DALL·E / GPT-Image)") gr.Markdown("### 🎛 OpenAI Image Controls") with gr.Row(): size = gr.Dropdown( [32 unmodified lines
gr.Markdown("### 🧪 Google Image / Text Model Hints") google_image_model = gr.Textbox( label="Google Image Model (default: Nano-Banana-Pro)", label="Google Image Model (default: nano-banana-pro)", value="nano-banana-pro", placeholder="e.g. nano-banana-pro (adjust to your actual model id in Google AI Studio)", placeholder="e.g. nano-banana-pro or your exact model id", ) google_text_model_hint = gr.Textbox( label="Google Text Model Hint (for future tweaking)", label="Google Text Model Hint", value="gemini-1.5-pro", placeholder="Used in code as default Gemini text model.", placeholder="Used internally as default text model.", )
generate_btn = gr.Button("🚀 Generate", variant="primary")4 unmodified lines
gr.Markdown("### 🖼 Image Output") image_gallery = gr.Gallery( label="Generated Images", show_label=False, columns=2, height=500, )
gr.Markdown("### 🧾 Debug / Logs (for you, not end users)") gr.Markdown("### 🧾 Debug / Logs") debug_output = gr.Textbox( label="Debug Info", lines=10, )
# Wire up callback generate_btn.click( fn=run_generation, inputs=[app.py+46-57