Sumayyea commited on
Commit
2d02bfe
Β·
verified Β·
1 Parent(s): c25aeab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +146 -47
app.py CHANGED
@@ -1,51 +1,150 @@
1
  import streamlit as st
2
- from langchain_community.llms import HuggingFaceHub
3
  import os
 
 
 
 
 
4
 
5
- # Streamlit interface
6
- st.title("Chat with Hugging Face Model")
7
- st.write("This chatbot is powered by a model hosted on Hugging Face Hub.")
8
-
9
- # Note: You need to set HF_TOKEN as environment variable
10
- if not os.getenv('HF_TOKEN2'):
11
- st.error("Please set the HF_TOKEN environment variable")
12
- st.stop()
13
-
14
- # Select a model that works with the Inference API
15
- model_repo = st.selectbox(
16
- "Select Model",
17
- [
18
- "gpt2",
19
- "distilgpt2",
20
- "facebook/opt-350m",
21
- "google/flan-t5-small"
22
- ],
23
- index=1 # Default to distilgpt2 which usually works
24
- )
25
-
26
- # Initialize the HuggingFace model
27
- try:
28
- llm = HuggingFaceHub(
29
- repo_id=model_repo,
30
- huggingfacehub_api_token=os.getenv('HF_TOKEN'),
31
- model_kwargs={
32
- "max_length": 128,
33
- "temperature": 0.7,
34
- "max_new_tokens": 50
35
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  )
37
- except Exception as e:
38
- st.error(f"Failed to initialize model: {str(e)}")
39
- st.stop()
40
-
41
- user_input = st.text_input("You:", "Type your message here...")
42
-
43
- if st.button("Send"):
44
- if user_input:
45
- try:
46
- response = llm(user_input)
47
- st.write(f"Bot: {response}")
48
- except Exception as e:
49
- st.error(f"Error: {str(e)}. Try a different model or check your token.")
50
- else:
51
- st.write("Please enter a message.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import google.generativeai as genai
3
  import os
4
+ from PIL import Image
5
+ import requests
6
+ from io import BytesIO
7
+ from typing import Tuple, Optional
8
+ import time
9
 
10
+ # Constants
11
+ LOGO_API_URL = "https://image.pollinations.ai/prompt/"
12
+ DEFAULT_IMAGE_SIZE = (512, 512)
13
+
14
+ # Configure Gemini
15
+ @st.cache_resource
16
+ def configure_gemini():
17
+ GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
18
+ if not GOOGLE_API_KEY:
19
+ st.error("Google API key not found. Please set the GOOGLE_API_KEY environment variable.")
20
+ st.stop()
21
+
22
+ try:
23
+ genai.configure(api_key=GOOGLE_API_KEY)
24
+ return genai.GenerativeModel('gemini-2.0-flash')
25
+ except Exception as e:
26
+ st.error(f"Failed to configure Gemini: {str(e)}")
27
+ st.stop()
28
+
29
+ model = configure_gemini()
30
+
31
+ def generate_logo(prompt: str, size: Tuple[int, int] = DEFAULT_IMAGE_SIZE) -> Optional[Image.Image]:
32
+ """Generate a logo using the DALL-E style API with error handling."""
33
+ try:
34
+ dalle_prompt = f"Minimal vector-style logo for {prompt} brand on white background, high quality"
35
+ response = requests.get(
36
+ f"{LOGO_API_URL}{dalle_prompt}",
37
+ timeout=10 # Add timeout to prevent hanging
38
+ )
39
+ response.raise_for_status() # Raise HTTP errors
40
+
41
+ img = Image.open(BytesIO(response.content))
42
+ return img.resize(size)
43
+ except requests.exceptions.RequestException as e:
44
+ st.error(f"Failed to generate logo: {str(e)}")
45
+ return None
46
+ except Exception as e:
47
+ st.error(f"An unexpected error occurred: {str(e)}")
48
+ return None
49
+
50
+ @st.cache_data(show_spinner=False, max_entries=5, ttl=3600)
51
+ def generate_brand_identity(brand: str, category: str) -> str:
52
+ """Generate brand identity with caching to avoid repeated API calls."""
53
+ prompt = f"""
54
+ Generate a comprehensive brand identity for a {category} brand named '{brand}'.
55
+ Provide the following in markdown format with clear section headings:
56
+
57
+ ### 🎯 Slogan
58
+ - Provide 2-3 catchy slogan options with a recommended one
59
+
60
+ ### 🎨 Color Palette
61
+ - 3 HEX codes with names and brief rationale for each choice
62
+ - Show color swatches in markdown if possible
63
+
64
+ ### βœ’οΈ Typography
65
+ - 2 suitable Google Fonts (one for headings, one for body)
66
+ - Brief explanation of font choices
67
+
68
+ ### πŸ“ Brand Description
69
+ - 1-2 paragraph professional description
70
+
71
+ ### πŸ’‘ Brand Attributes
72
+ - 4-5 key brand characteristics
73
+
74
+ Additional suggestions for:
75
+ - Logo design direction
76
+ - Imagery style
77
+ - Tone of voice
78
+ """
79
+
80
+ try:
81
+ response = model.generate_content(prompt)
82
+ return response.text
83
+ except Exception as e:
84
+ return f"Error generating brand identity: {str(e)}"
85
+
86
+ def format_output(text: str) -> None:
87
+ """Format the output text with proper markdown rendering."""
88
+ st.markdown(text, unsafe_allow_html=True)
89
+
90
+ def create_download_button(image: Image.Image, brand_name: str) -> None:
91
+ """Create a download button for the generated logo."""
92
+ buf = BytesIO()
93
+ image.save(buf, format="PNG")
94
+ st.download_button(
95
+ label="Download Logo",
96
+ data=buf.getvalue(),
97
+ file_name=f"{brand_name.lower().replace(' ', '_')}_logo.png",
98
+ mime="image/png"
99
  )
100
+
101
+ # Streamlit UI
102
+ def main():
103
+ st.set_page_config(page_title="AI Brand Identity Designer", page_icon="🎨")
104
+
105
+ st.title("🎨 AI Brand Identity Designer")
106
+ st.markdown("Create a complete brand identity package with AI")
107
+
108
+ with st.form("brand_form"):
109
+ brand_name = st.text_input("Brand Name", placeholder="Enter your brand name")
110
+ category = st.selectbox(
111
+ "Brand Category",
112
+ ["Tech", "Fashion", "Food", "Education", "Health", "Other"],
113
+ index=0
114
+ )
115
+
116
+ submitted = st.form_submit_button("Generate Brand Kit")
117
+
118
+ if submitted:
119
+ if not brand_name.strip():
120
+ st.warning("Please enter a brand name")
121
+ return
122
+
123
+ with st.spinner("Creating your brand identity..."):
124
+ start_time = time.time()
125
+
126
+ # Parallel processing would be better but Streamlit has limitations
127
+ col1, col2 = st.columns(2)
128
+
129
+ with col1:
130
+ identity = generate_brand_identity(brand_name, category)
131
+
132
+ with col2:
133
+ logo_img = generate_logo(brand_name)
134
+
135
+ elapsed = time.time() - start_time
136
+ st.success(f"Brand kit generated in {elapsed:.1f} seconds!")
137
+
138
+ if logo_img:
139
+ st.subheader("πŸ–Ό Logo Concept")
140
+ st.image(logo_img, use_column_width=True)
141
+ create_download_button(logo_img, brand_name)
142
+
143
+ st.subheader("🧠 Brand Identity Guide")
144
+ format_output(identity)
145
+
146
+ st.markdown("---")
147
+ st.caption("Note: This is an AI-generated concept. Please review and adapt as needed for your brand.")
148
+
149
+ if __name__ == "__main__":
150
+ main()