Spaces:
Runtime error
Runtime error
Update app.py
Browse files12345678910111213141516174 unmodified lines222324252627282 unmodified lines3132333435363730 unmodified lines686970717273741 unmodified line76777879808110 unmodified lines92939495969798991001011022 unmodified lines1051061071081091103 unmodified lines1141151161171181191204 unmodified lines12512612712812913013125 unmodified lines1571581591601611621638 unmodified lines17217317417517617717812 unmodified lines19119219319419519619723 unmodified lines2212222232242252262272282292301 unmodified line2322332342352362372382393 unmodified lines2432442452462472482492502512522531 unmodified line25525625725825926026111 unmodified lines2732742752762772782792802812822831 unmodified line2852862872882892902918 unmodified lines3003013023033043053061 unmodified line30830931031131231331417 unmodified lines33233333433533633733833934034134212 unmodified lines3553563573583593603611 unmodified line3633643653663673683693702 unmodified lines37337437537637737837938038138238338438538638738838939039139239339439539639739839940040117 unmodified lines41942042142242342442542642742842943043143243343422 unmodified lines45745845946046146246346432 unmodified lines4974984995005015025035045055065075085095104 unmodified lines515516517518519520521522523524525526527528529530531532533import base64import ioimport osfrom typing import List, Tuple, Optionalimport gradio as grfrom PIL import Image# -----------------------# Optional imports guarded at call-time# -----------------------def _get_openai_client(api_key: str):from openai import OpenAI # imported here to avoid issues if lib missingreturn OpenAI(api_key=api_key)4 unmodified lines# -----------------------# Helper: apply visual presets# -----------------------def apply_preset_to_prompt(2 unmodified linesstyle: 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,")extra = " ".join(x10 unmodified linesreturn f"{base_prompt}, {extra}"else:return extra.strip()return base_prompt or "high quality image"# -----------------------# OpenAI: Text + Image# -----------------------def generate_text_openai(2 unmodified linesmode: 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 linesif mode == "Infographic Spec":user_prompt = (f"Create a Palantir/Anduril-level infographic specification based on:\n\n{prompt}\n\n""Return:\n""1) Title options\n""2) 3–5 main sections\n"4 unmodified lineselse:user_prompt = prompt# Using Chat Completions interfaceresp = 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 onessize_map = {"Square (1024x1024)": "1024x1024","Portrait (1024x1792)": "1024x1792",8 unmodified lines"quality": quality,"n": n_images,}# seed is optional on some models; safe to include conditionallyif seed is not None:kwargs["seed"] = seed12 unmodified linesmode: str,) -> str:genai = _configure_google(api_key)# Default to a strong text modelmodel = genai.GenerativeModel("gemini-1.5-pro")if mode == "Infographic Spec":23 unmodified linesseed: Optional[int],) -> List[Image.Image]:"""NOTE: Model & output handling may need adjustment depending onthe exact Nano-Banana / Nano-Banana-Pro API you use in Google AI Studio.This assumes a GenerativeModel that returns inline image data."""genai = _configure_google(api_key)model = genai.GenerativeModel(google_image_model)1 unmodified lineimages: 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 linesgeneration_config=generation_config or None,)# Try to pull image bytes from response partsfor 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)img = Image.open(io.BytesIO(raw)).convert("RGB")images.append(img)1 unmodified line# -----------------------# Core Gradio callback# -----------------------def run_generation(11 unmodified linesseed: int,use_seed: bool,google_image_model: str,google_text_model_hint: str,) -> Tuple[str, List[Image.Image], str]:"""Returns: (text_output, images, debug_info)"""text_output = ""images: List[Image.Image] = []debug_lines = []1 unmodified lineif not base_prompt.strip():return "Please enter a prompt.", [], "No prompt provided."# Build full prompt for imagescontent_type = "Image" if task_type == "Image" else task_typefull_prompt = apply_preset_to_prompt(base_prompt=base_prompt,8 unmodified linesdebug_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"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 lineseed_val: Optional[int] = seed if use_seed else Nonetry:# TEXT or INFOGRAPHICif task_type in ["Text", "Infographic Spec"]:if provider == "OpenAI":if not openai_key.strip():17 unmodified linesif 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 defaultimage_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 linesreturn "Missing Google API key.", [], "Google key not provided."images = generate_image_google(api_key=google_key.strip(),google_image_model=google_image_model.strip(),prompt=full_prompt,n_images=n_images,seed=seed_val,1 unmodified lineif 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.")if not images and task_type == "Image":2 unmodified linesreturn text_output, images, "\n".join(debug_lines)except Exception as e:return f"Error: {e}", [], "\n".join(debug_lines + [f"Exception: {e}"])# -----------------------# UI# -----------------------with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("""# 🧬 ZEN Omni Studio — Text • Images • InfographicsA unified 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.""")with gr.Row():with gr.Column():gr.Markdown("### 🔐 API Keys (kept only in your browser session)")openai_key = gr.Textbox(label="OPENAI_API_KEY",type="password",17 unmodified lineslabel="Primary Provider",)# Prompt regionbase_prompt = gr.Textbox(label="Main Prompt",lines=5,placeholder="Describe what you want to create for ZEN (image, copy, infographic, etc.)",)negative_prompt = gr.Textbox(label="Negative Prompt (optional)",lines=2,placeholder="Things to avoid: low-res, cluttered, distorted text, etc.",)with gr.Row():22 unmodified lineslabel="Style Accent",)# OpenAI image optionsgr.Markdown("### 🎛 OpenAI Image Controls (DALL·E / GPT-Image)")with gr.Row():size = gr.Dropdown([32 unmodified linesgr.Markdown("### 🧪 Google Image / Text Model Hints")google_image_model = gr.Textbox(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)",)google_text_model_hint = gr.Textbox(label="Google Text Model Hint (for future tweaking)",value="gemini-1.5-pro",placeholder="Used in code as default Gemini text model.",)generate_btn = gr.Button("🚀 Generate", variant="primary")4 unmodified linesgr.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)")debug_output = gr.Textbox(label="Debug Info",lines=10,)# Wire up callbackgenerate_btn.click(fn=run_generation,inputs=[12345678910111213141516174 unmodified lines222324252627282 unmodified lines31323334353630 unmodified lines6768697071721 unmodified line747576777879808110 unmodified lines92939495969798991001011021032 unmodified lines1061071081091101111123 unmodified lines1161171181191201211221234 unmodified lines12812913013113213325 unmodified lines1591601611621631648 unmodified lines17317417517617717812 unmodified lines19119219319419519623 unmodified lines2202212222232242252262272281 unmodified line2302312322332342353 unmodified lines2392402412422432442452462472482492501 unmodified line25225325425525625725811 unmodified lines2702712722732742752762771 unmodified line2792802812822832848 unmodified lines2932942952962972982991 unmodified line30130230330430530630717 unmodified lines32532632732832933033133233312 unmodified lines3463473483493503513521 unmodified line3543553563573583593603612 unmodified lines36436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339417 unmodified lines41241341441541641741841942042142242342442542622 unmodified lines44945045145245345445532 unmodified lines4884894904914924934944954964974984995005014 unmodified lines506507508509510511512513514515516517518519520521522import base64import iofrom typing import List, Tuple, Optionalimport gradio as grfrom PIL import Image# -----------------------# OpenAI + Google helpers# -----------------------def _get_openai_client(api_key: str):from openai import OpenAI # local import so app still loads if lib missingreturn OpenAI(api_key=api_key)4 unmodified lines# -----------------------# Prompt / preset logic# -----------------------def apply_preset_to_prompt(2 unmodified linesstyle: str,content_type: str,) -> str:base_prompt = base_prompt.strip()preset_addons = {30 unmodified lines"Cinematic": " cinematic lighting, dramatic composition, filmic contrast",}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 linesreturn f"{base_prompt}, {extra}"else:return extra.strip()return base_prompt or "high quality image"# -----------------------# OpenAI text + images# -----------------------def generate_text_openai(2 unmodified linesmode: 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 linesif mode == "Infographic Spec":user_prompt = ("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 lineselse:user_prompt = promptresp = client.chat.completions.create(model="gpt-4.1-mini",messages=[25 unmodified lines) -> List[Image.Image]:client = _get_openai_client(api_key)size_map = {"Square (1024x1024)": "1024x1024","Portrait (1024x1792)": "1024x1792",8 unmodified lines"quality": quality,"n": n_images,}if seed is not None:kwargs["seed"] = seed12 unmodified linesmode: str,) -> str:genai = _configure_google(api_key)model = genai.GenerativeModel("gemini-1.5-pro")if mode == "Infographic Spec":23 unmodified linesseed: Optional[int],) -> List[Image.Image]:"""This assumes your Nano-Banana / Nano-Banana-Pro image model inGoogle 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 lineimages: List[Image.Image] = []for i in range(n_images):generation_config = {}if seed is not None:generation_config["seed"] = seed + i3 unmodified linesgeneration_config=generation_config or None,)# Extract images from candidatesfor 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 callback# -----------------------def run_generation(11 unmodified linesseed: int,use_seed: bool,google_image_model: str,google_text_model_hint: str, # currently just logged) -> Tuple[str, List[Image.Image], str]:text_output = ""images: List[Image.Image] = []debug_lines = []1 unmodified lineif not base_prompt.strip():return "Please enter a prompt.", [], "No prompt provided."content_type = "Image" if task_type == "Image" else task_typefull_prompt = apply_preset_to_prompt(base_prompt=base_prompt,8 unmodified linesdebug_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 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 lineseed_val: Optional[int] = seed if use_seed else Nonetry:# TEXT / INFOGRAPHICif task_type in ["Text", "Infographic Spec"]:if provider == "OpenAI":if not openai_key.strip():17 unmodified linesif provider == "OpenAI":if not openai_key.strip():return "Missing OpenAI API key.", [], "OpenAI key not provided."# Default to GPT-Image-1; for Palantir preset, swap to DALL·E 3image_model = "gpt-image-1"if "Palantir" in preset:image_model = "dall-e-3"12 unmodified linesreturn "Missing Google API key.", [], "Google key not provided."images = generate_image_google(api_key=google_key.strip(),google_image_model=google_image_model.strip() or "nano-banana-pro",prompt=full_prompt,n_images=n_images,seed=seed_val,1 unmodified lineif not text_output and task_type == "Image":text_output = ("Image(s) generated. Use Text / Infographic Spec mode to ""generate captions, copy, or layout specs.")if not images and task_type == "Image":2 unmodified linesreturn 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)# -----------------------# UI# -----------------------with gr.Blocks() as demo: # <- no theme arggr.Markdown("""# 🧬 ZEN Omni Studio — Text • Images • InfographicsMulti-provider creator for the ZEN ecosystem:- 🔑 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 (local to this session)")openai_key = gr.Textbox(label="OPENAI_API_KEY",type="password",17 unmodified lineslabel="Primary Provider",)base_prompt = gr.Textbox(label="Main Prompt",lines=5,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, clutter, warped text, etc.",)with gr.Row():22 unmodified lineslabel="Style Accent",)gr.Markdown("### 🎛 OpenAI Image Controls")with gr.Row():size = gr.Dropdown([32 unmodified linesgr.Markdown("### 🧪 Google Image / Text Model Hints")google_image_model = gr.Textbox(label="Google Image Model (default: nano-banana-pro)",value="nano-banana-pro",placeholder="e.g. nano-banana-pro or your exact model id",)google_text_model_hint = gr.Textbox(label="Google Text Model Hint",value="gemini-1.5-pro",placeholder="Used internally as default text model.",)generate_btn = gr.Button("🚀 Generate", variant="primary")4 unmodified linesgr.Markdown("### 🖼 Image Output")image_gallery = gr.Gallery(show_label=False,columns=2,height=500,)gr.Markdown("### 🧾 Debug / Logs")debug_output = gr.Textbox(label="Debug Info",lines=10,)generate_btn.click(fn=run_generation,inputs=[
app.py+46-57