File size: 6,620 Bytes
e0a377a
2d02bfe
bc8e119
2d02bfe
 
 
 
 
e0a377a
2d02bfe
 
6bba421
2d02bfe
6bb8270
2d02bfe
6bb8270
 
2d02bfe
 
6bb8270
 
 
 
 
 
 
2d02bfe
 
 
 
6bb8270
 
 
 
2d02bfe
6bb8270
2d02bfe
 
6bb8270
2d02bfe
 
6bb8270
 
6bba421
6bb8270
 
6bba421
 
 
6bb8270
6bba421
 
 
2d02bfe
6bb8270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d02bfe
6bb8270
 
 
2d02bfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bb8270
2d02bfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc8e119
2d02bfe
 
 
 
 
 
 
 
6bb8270
 
 
 
 
 
 
 
 
 
 
 
2d02bfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bba421
6bb8270
2d02bfe
 
 
 
 
6bb8270
2d02bfe
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
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()