Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,22 +1,26 @@
|
|
| 1 |
-
#
|
| 2 |
-
#
|
| 3 |
|
| 4 |
-
import time, io, base64,
|
| 5 |
-
import requests
|
| 6 |
import gradio as gr
|
| 7 |
from PIL import Image
|
| 8 |
|
| 9 |
# ---------------------------
|
| 10 |
-
# HARDCODED KEYS
|
| 11 |
# ---------------------------
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
GROQ_MODEL = "meta-llama/llama-4-scout-17b-16e-instruct"
|
| 16 |
|
| 17 |
-
#
|
| 18 |
-
|
| 19 |
-
|
|
|
|
| 20 |
GENAI_AVAILABLE = False
|
| 21 |
GENAI_CLIENT = None
|
| 22 |
|
|
@@ -30,93 +34,130 @@ def ensure_genai_client():
|
|
| 30 |
GENAI_AVAILABLE = True
|
| 31 |
return True
|
| 32 |
except Exception:
|
|
|
|
|
|
|
| 33 |
return False
|
| 34 |
|
| 35 |
# ---------------------------
|
| 36 |
-
#
|
| 37 |
# ---------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
def call_llama_text(message, history):
|
| 39 |
headers = {"Authorization": f"Bearer {GROQ_KEY}", "Content-Type": "application/json"}
|
| 40 |
msgs = []
|
| 41 |
-
for u, m in history:
|
| 42 |
-
msgs.append({"role":
|
| 43 |
-
msgs.append({"role":
|
| 44 |
-
msgs.append({"role":
|
| 45 |
payload = {"model": GROQ_MODEL, "messages": msgs}
|
| 46 |
-
r =
|
| 47 |
data = r.json()
|
| 48 |
if "choices" in data and data["choices"]:
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
| 50 |
return str(data)
|
| 51 |
|
| 52 |
# ---------------------------
|
| 53 |
-
# Gemini 2.5
|
| 54 |
# ---------------------------
|
| 55 |
def call_gemini25_image_text(prompt):
|
| 56 |
if not ensure_genai_client():
|
| 57 |
-
return "ERROR: google-genai not installed.
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
contents = [types.Content(role="user", parts=[types.Part.from_text(text=prompt)])]
|
| 63 |
-
config = types.GenerateContentConfig(response_modalities=["IMAGE", "TEXT"])
|
| 64 |
|
| 65 |
-
|
| 66 |
-
|
| 67 |
|
| 68 |
-
|
| 69 |
-
for chunk in GENAI_CLIENT.models.generate_content_stream(
|
| 70 |
-
model=model, contents=contents, config=config
|
| 71 |
-
):
|
| 72 |
if not chunk.candidates:
|
| 73 |
continue
|
| 74 |
-
|
| 75 |
-
if not
|
| 76 |
continue
|
| 77 |
-
|
| 78 |
-
part
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
except Exception as e:
|
| 91 |
-
return f"
|
| 92 |
-
|
| 93 |
-
caption = " ".join(messages).strip() or f"Generated image for: {prompt}"
|
| 94 |
-
if image:
|
| 95 |
-
return [(caption, image)]
|
| 96 |
-
return caption
|
| 97 |
|
| 98 |
# ---------------------------
|
| 99 |
-
# Chat fn
|
| 100 |
# ---------------------------
|
| 101 |
-
def chat_fn(message, history,
|
| 102 |
try:
|
| 103 |
-
if
|
| 104 |
return call_gemini25_image_text(message)
|
| 105 |
-
|
|
|
|
|
|
|
| 106 |
return call_llama_text(message, history)
|
| 107 |
else:
|
| 108 |
-
return "Unknown model."
|
| 109 |
except Exception as e:
|
| 110 |
-
return f"Error: {e}"
|
| 111 |
|
| 112 |
# ---------------------------
|
| 113 |
# CSS
|
| 114 |
# ---------------------------
|
| 115 |
css = """
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
#
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
"""
|
| 121 |
|
| 122 |
# ---------------------------
|
|
@@ -124,19 +165,26 @@ css = """
|
|
| 124 |
# ---------------------------
|
| 125 |
with gr.Blocks(css=css, title="⚡ YellowFlash.ai") as app:
|
| 126 |
with gr.Row(elem_id="topbar"):
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
gr.HTML("<div id='title'>⚡ YellowFlash.ai</div>")
|
| 134 |
|
| 135 |
gr.ChatInterface(
|
| 136 |
fn=chat_fn,
|
| 137 |
-
title="⚡",
|
| 138 |
-
description="
|
| 139 |
-
additional_inputs=[
|
| 140 |
)
|
| 141 |
|
| 142 |
app.launch(share=True)
|
|
|
|
| 1 |
+
# yellowflash_chat_with_separate_image_dropdown_keys.py
|
| 2 |
+
# TEST ONLY: hardcoded API keys included (do NOT publish)
|
| 3 |
|
| 4 |
+
import time, io, base64, traceback, requests
|
|
|
|
| 5 |
import gradio as gr
|
| 6 |
from PIL import Image
|
| 7 |
|
| 8 |
# ---------------------------
|
| 9 |
+
# HARDCODED KEYS (TESTING)
|
| 10 |
# ---------------------------
|
| 11 |
+
# Gemini text
|
| 12 |
+
GEMINI_KEY = "AIzaSyAPfDiu2V_aD6un00qHt5bkISm6C0Pkx7o"
|
| 13 |
+
GEMINI_TEXT_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent"
|
| 14 |
+
|
| 15 |
+
# Groq / LLaMA
|
| 16 |
+
GROQ_KEY = "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"
|
| 17 |
+
GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
|
| 18 |
GROQ_MODEL = "meta-llama/llama-4-scout-17b-16e-instruct"
|
| 19 |
|
| 20 |
+
# Gemini image streaming (2.5)
|
| 21 |
+
GEMINI_IMAGE_MODEL = "gemini-2.5-flash-image-preview" # streaming model name
|
| 22 |
+
|
| 23 |
+
# lazy genai client
|
| 24 |
GENAI_AVAILABLE = False
|
| 25 |
GENAI_CLIENT = None
|
| 26 |
|
|
|
|
| 34 |
GENAI_AVAILABLE = True
|
| 35 |
return True
|
| 36 |
except Exception:
|
| 37 |
+
GENAI_AVAILABLE = False
|
| 38 |
+
GENAI_CLIENT = None
|
| 39 |
return False
|
| 40 |
|
| 41 |
# ---------------------------
|
| 42 |
+
# helpers
|
| 43 |
# ---------------------------
|
| 44 |
+
def post_with_retries(url, headers, payload, timeout=18, max_retries=2):
|
| 45 |
+
for i in range(max_retries):
|
| 46 |
+
try:
|
| 47 |
+
r = requests.post(url, headers=headers, json=payload, timeout=timeout)
|
| 48 |
+
r.raise_for_status()
|
| 49 |
+
return r
|
| 50 |
+
except Exception:
|
| 51 |
+
if i == max_retries - 1:
|
| 52 |
+
raise
|
| 53 |
+
time.sleep(0.5 + i)
|
| 54 |
+
raise Exception("Max retries exceeded")
|
| 55 |
+
|
| 56 |
+
# ---------------------------
|
| 57 |
+
# Text model calls
|
| 58 |
+
# ---------------------------
|
| 59 |
+
def call_gemini_text(message, history):
|
| 60 |
+
headers = {"Content-Type":"application/json","x-goog-api-key": GEMINI_KEY}
|
| 61 |
+
contents = []
|
| 62 |
+
for u, m in (history or []):
|
| 63 |
+
contents.append({"role":"user","parts":[{"text":u}]})
|
| 64 |
+
contents.append({"role":"model","parts":[{"text":m}]})
|
| 65 |
+
contents.append({"role":"user","parts":[{"text":message}]})
|
| 66 |
+
payload = {"contents": contents}
|
| 67 |
+
r = post_with_retries(GEMINI_TEXT_URL, headers, payload, timeout=30)
|
| 68 |
+
data = r.json()
|
| 69 |
+
return data.get("candidates",[{}])[0].get("content",{}).get("parts",[{}])[0].get("text","")
|
| 70 |
+
|
| 71 |
def call_llama_text(message, history):
|
| 72 |
headers = {"Authorization": f"Bearer {GROQ_KEY}", "Content-Type": "application/json"}
|
| 73 |
msgs = []
|
| 74 |
+
for u, m in (history or []):
|
| 75 |
+
msgs.append({"role":"user","content":u})
|
| 76 |
+
msgs.append({"role":"assistant","content":m})
|
| 77 |
+
msgs.append({"role":"user","content":message})
|
| 78 |
payload = {"model": GROQ_MODEL, "messages": msgs}
|
| 79 |
+
r = post_with_retries(GROQ_URL, headers, payload, timeout=30)
|
| 80 |
data = r.json()
|
| 81 |
if "choices" in data and data["choices"]:
|
| 82 |
+
ch = data["choices"][0]
|
| 83 |
+
if isinstance(ch.get("message"), dict):
|
| 84 |
+
return ch["message"].get("content","")
|
| 85 |
+
return ch.get("text","")
|
| 86 |
return str(data)
|
| 87 |
|
| 88 |
# ---------------------------
|
| 89 |
+
# Gemini 2.5 image streaming call
|
| 90 |
# ---------------------------
|
| 91 |
def call_gemini25_image_text(prompt):
|
| 92 |
if not ensure_genai_client():
|
| 93 |
+
return "ERROR: google-genai client not installed. Add `google-genai` to requirements and rebuild."
|
| 94 |
+
try:
|
| 95 |
+
from google.genai import types
|
| 96 |
+
messages = []
|
| 97 |
+
image = None
|
|
|
|
|
|
|
| 98 |
|
| 99 |
+
contents = [types.Content(role="user", parts=[types.Part.from_text(text=prompt)])]
|
| 100 |
+
cfg = types.GenerateContentConfig(response_modalities=["IMAGE", "TEXT"])
|
| 101 |
|
| 102 |
+
for chunk in GENAI_CLIENT.models.generate_content_stream(model=GEMINI_IMAGE_MODEL, contents=contents, config=cfg):
|
|
|
|
|
|
|
|
|
|
| 103 |
if not chunk.candidates:
|
| 104 |
continue
|
| 105 |
+
cand = chunk.candidates[0]
|
| 106 |
+
if not getattr(cand, "content", None):
|
| 107 |
continue
|
| 108 |
+
parts = cand.content.parts or []
|
| 109 |
+
for part in parts:
|
| 110 |
+
if getattr(part, "text", None):
|
| 111 |
+
messages.append(part.text)
|
| 112 |
+
inline = getattr(part, "inline_data", None)
|
| 113 |
+
if inline and getattr(inline, "data", None):
|
| 114 |
+
try:
|
| 115 |
+
img_bytes = io.BytesIO(inline.data)
|
| 116 |
+
image = Image.open(img_bytes).convert("RGB")
|
| 117 |
+
except Exception:
|
| 118 |
+
data_uri = getattr(inline, "dataURI", None) or getattr(inline, "data_uri", None)
|
| 119 |
+
if data_uri and data_uri.startswith("data:"):
|
| 120 |
+
header, b64 = data_uri.split(",", 1)
|
| 121 |
+
img_bytes = io.BytesIO(base64.b64decode(b64))
|
| 122 |
+
image = Image.open(img_bytes).convert("RGB")
|
| 123 |
+
|
| 124 |
+
caption = " ".join([m for m in messages if m]).strip()
|
| 125 |
+
if not caption:
|
| 126 |
+
caption = f"Generated image for: {prompt}"
|
| 127 |
+
if image:
|
| 128 |
+
return [(caption, image)]
|
| 129 |
+
return caption
|
| 130 |
except Exception as e:
|
| 131 |
+
return f"Image generation error: {e}\n{traceback.format_exc()}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
# ---------------------------
|
| 134 |
+
# Chat fn
|
| 135 |
# ---------------------------
|
| 136 |
+
def chat_fn(message, history, text_model_choice, image_model_choice):
|
| 137 |
try:
|
| 138 |
+
if image_model_choice == "Gemini Imagen 2.5":
|
| 139 |
return call_gemini25_image_text(message)
|
| 140 |
+
if text_model_choice == "Google Gemini 2.0 Flash":
|
| 141 |
+
return call_gemini_text(message, history)
|
| 142 |
+
elif text_model_choice == "Meta LLaMA 4":
|
| 143 |
return call_llama_text(message, history)
|
| 144 |
else:
|
| 145 |
+
return "Unknown model selected."
|
| 146 |
except Exception as e:
|
| 147 |
+
return f"Error: {e}\n{traceback.format_exc()}"
|
| 148 |
|
| 149 |
# ---------------------------
|
| 150 |
# CSS
|
| 151 |
# ---------------------------
|
| 152 |
css = """
|
| 153 |
+
:root{ --topbar-h:68px; --accent:#2cc3ff; --title:#ffcc33;}
|
| 154 |
+
body { background:#0d0d0d; color:#fff; font-family:Inter, Arial, sans-serif; margin:0; }
|
| 155 |
+
#topbar { display:flex; justify-content:space-between; align-items:center; padding:12px 20px; background:#0f0f0f; border-bottom:1px solid #1f1f1f; position:fixed; left:0; right:0; top:0; z-index:999; height:var(--topbar-h); }
|
| 156 |
+
#title { font-weight:800; color:var(--title); font-size:18px; padding-left:12px; }
|
| 157 |
+
#left_controls { display:flex; gap:12px; align-items:center; }
|
| 158 |
+
#model_dropdown .gr-dropdown, #image_dropdown .gr-dropdown { background:transparent !important; border:1px solid #2b2b2b !important; color:#ddd !important; padding:8px 12px !important; border-radius:8px !important; width:260px !important; box-shadow:none !important; }
|
| 159 |
+
.gradio-container { padding-top: calc(var(--topbar-h) + 8px) !important; }
|
| 160 |
+
.gradio-container .chat-interface .chatbot { min-height: calc(100vh - 220px); }
|
| 161 |
"""
|
| 162 |
|
| 163 |
# ---------------------------
|
|
|
|
| 165 |
# ---------------------------
|
| 166 |
with gr.Blocks(css=css, title="⚡ YellowFlash.ai") as app:
|
| 167 |
with gr.Row(elem_id="topbar"):
|
| 168 |
+
with gr.Row(elem_id="left_controls"):
|
| 169 |
+
text_model_dropdown = gr.Dropdown(
|
| 170 |
+
choices=["Google Gemini 2.0 Flash", "Meta LLaMA 4"],
|
| 171 |
+
value="Google Gemini 2.0 Flash",
|
| 172 |
+
show_label=False,
|
| 173 |
+
elem_id="model_dropdown"
|
| 174 |
+
)
|
| 175 |
+
image_model_dropdown = gr.Dropdown(
|
| 176 |
+
choices=["None", "Gemini Imagen 2.5"],
|
| 177 |
+
value="None",
|
| 178 |
+
show_label=False,
|
| 179 |
+
elem_id="image_dropdown"
|
| 180 |
+
)
|
| 181 |
gr.HTML("<div id='title'>⚡ YellowFlash.ai</div>")
|
| 182 |
|
| 183 |
gr.ChatInterface(
|
| 184 |
fn=chat_fn,
|
| 185 |
+
title="⚡ YellowFlash.ai",
|
| 186 |
+
description="Select a text model or switch image dropdown to 'Gemini Imagen 2.5' for inline image generation.",
|
| 187 |
+
additional_inputs=[text_model_dropdown, image_model_dropdown],
|
| 188 |
)
|
| 189 |
|
| 190 |
app.launch(share=True)
|