Sumayyea's picture
Update app.py
6bb8270 verified
Raw History Blame Contribute Delete
6.62 kB
import streamlit as st
import google.generativeai as genai
import os
from PIL import Image
import requests
from io import BytesIO
from typing import Tuple, Optional
import time
# Constants
DEFAULT_IMAGE_SIZE = (512, 512)
HF_API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"
# Configure APIs
@st.cache_resource
def configure_apis():
# Gemini Configuration
GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
if not GOOGLE_API_KEY:
st.error("Google API key not found in environment variables")
st.stop()
# Hugging Face Configuration
HF_API_KEY = os.getenv('HF_API_KEY')
if not HF_API_KEY:
st.error("Hugging Face API key not found in environment variables")
st.stop()
try:
genai.configure(api_key=GOOGLE_API_KEY)
return {
'gemini': genai.GenerativeModel('gemini-2.0-flash'),
'hf_api_key': HF_API_KEY
}
except Exception as e:
st.error(f"Failed to configure APIs: {str(e)}")
st.stop()
apis = configure_apis()
def generate_logo(prompt: str, size: Tuple[int, int] = DEFAULT_IMAGE_SIZE) -> Optional[Image.Image]:
"""Generate a logo using Stable Diffusion API with enhanced error handling."""
headers = {"Authorization": f"Bearer {apis['hf_api_key']}"}
payload = {
"inputs": f"minimal flat vector style logo for '{prompt}' brand, "
f"white background, clean modern professional design, high quality",
"parameters": {
"width": size[0],
"height": size[1],
"num_inference_steps": 25
}
}
try:
with st.spinner("Generating logo (this may take 20-30 seconds)..."):
response = requests.post(
HF_API_URL,
headers=headers,
json=payload,
timeout=45 # Increased timeout for Hugging Face free tier
)
if response.status_code == 200:
return Image.open(BytesIO(response.content)).resize(size)
elif response.status_code == 401:
st.error("Invalid Hugging Face API key. Please check your credentials.")
elif response.status_code == 503:
estimated_time = response.headers.get("estimated_time", 30)
st.warning(f"Model is loading, please try again in {estimated_time} seconds")
else:
st.error(f"API Error: {response.status_code} - {response.text}")
except requests.exceptions.Timeout:
st.error("Logo generation timed out. The model might be overloaded.")
except Exception as e:
st.error(f"Unexpected error: {str(e)}")
return None
@st.cache_data(show_spinner=False, max_entries=5, ttl=3600)
def generate_brand_identity(brand: str, category: str) -> str:
"""Generate brand identity with caching to avoid repeated API calls."""
prompt = f"""
Generate a comprehensive brand identity for a {category} brand named '{brand}'.
Provide the following in markdown format with clear section headings:
### 🎯 Slogan
- Provide 2-3 catchy slogan options with a recommended one
### 🎨 Color Palette
- 3 HEX codes with names and brief rationale for each choice
- Show color swatches in markdown if possible
### ✒️ Typography
- 2 suitable Google Fonts (one for headings, one for body)
- Brief explanation of font choices
### 📝 Brand Description
- 1-2 paragraph professional description
### 💡 Brand Attributes
- 4-5 key brand characteristics
Additional suggestions for:
- Logo design direction
- Imagery style
- Tone of voice
"""
try:
response = apis['gemini'].generate_content(prompt)
return response.text
except Exception as e:
return f"Error generating brand identity: {str(e)}"
def format_output(text: str) -> None:
"""Format the output text with proper markdown rendering."""
st.markdown(text, unsafe_allow_html=True)
def create_download_button(image: Image.Image, brand_name: str) -> None:
"""Create a download button for the generated logo."""
buf = BytesIO()
image.save(buf, format="PNG")
st.download_button(
label="Download Logo",
data=buf.getvalue(),
file_name=f"{brand_name.lower().replace(' ', '_')}_logo.png",
mime="image/png"
)
# Streamlit UI
def main():
st.set_page_config(page_title="AI Brand Identity Designer", page_icon="🎨")
st.title("🎨 AI Brand Identity Designer")
st.markdown("Create a complete brand identity package with AI")
# API status check
with st.expander("ℹ️ API Status", expanded=False):
if apis.get('hf_api_key'):
st.success("Hugging Face API: Configured")
else:
st.error("Hugging Face API: Not configured")
if apis.get('gemini'):
st.success("Gemini API: Configured")
else:
st.error("Gemini API: Not configured")
with st.form("brand_form"):
brand_name = st.text_input("Brand Name", placeholder="Enter your brand name")
category = st.selectbox(
"Brand Category",
["Tech", "Fashion", "Food", "Education", "Health", "Other"],
index=0
)
submitted = st.form_submit_button("Generate Brand Kit")
if submitted:
if not brand_name.strip():
st.warning("Please enter a brand name")
return
with st.spinner("Creating your brand identity..."):
start_time = time.time()
col1, col2 = st.columns(2)
with col1:
identity = generate_brand_identity(brand_name, category)
with col2:
logo_img = generate_logo(brand_name)
elapsed = time.time() - start_time
st.success(f"Brand kit generated in {elapsed:.1f} seconds!")
if logo_img:
st.subheader("🖼 Logo Concept")
st.image(logo_img, use_column_width=True)
create_download_button(logo_img, brand_name)
else:
st.warning("Could not generate logo. See error messages above for details.")
st.subheader("🧠 Brand Identity Guide")
format_output(identity)
st.markdown("---")
st.caption("Note: This is an AI-generated concept. Please review and adapt as needed.")
if __name__ == "__main__":
main()