HaseebRaza115 commited on
Commit
4568847
·
verified ·
1 Parent(s): 07ef438

Solve the problem of iboothme syntax , adds the gadgets description to blend the ideations, Improve the Gradio UI

Browse files
Files changed (1) hide show
  1. app.py +302 -202
app.py CHANGED
@@ -1,202 +1,302 @@
1
- import gradio as gr
2
- import re
3
- import random
4
- from dotenv import load_dotenv
5
- import os
6
- from openai import OpenAI
7
-
8
- # 🔐 Load API Key from .env
9
- load_dotenv()
10
- api_key = os.getenv("OPENAI_API_KEY")
11
- client = OpenAI(api_key=api_key)
12
-
13
-
14
- def extract_keywords(paragraph):
15
- prompt = f"""
16
- You are an expert in experiential event planning.
17
-
18
- Extract 5-10 short, specific, and thematic keywords or concepts from the event description below. These will be used to inspire immersive, tech-powered event ideas.
19
-
20
- Each keyword should be 2-4 words long and describe a concrete idea or theme (e.g., "Photo booths", "smart vending", "interactive storytelling").
21
-
22
- Event Description:
23
- "{paragraph}"
24
-
25
- Return the keywords as a comma-separated list.
26
- """
27
- response = client.chat.completions.create(
28
- model="gpt-4",
29
- messages=[{"role": "user", "content": prompt}],
30
- temperature=0.7,
31
- max_tokens=200
32
- )
33
-
34
- keywords_raw = response.choices[0].message.content
35
- keywords = re.split(r'[,\n]', keywords_raw)
36
- return [kw.strip().lower() for kw in keywords if kw.strip()]
37
-
38
-
39
- def extract_keywords_from_title_and_link(title, link):
40
- prompt = f"""
41
- You are an expert in event innovation.
42
-
43
- Given the title and link below, extract 3-5 short, specific, and meaningful keywords or themes (2-4 words each) that describe what the page is about.
44
-
45
- Title: {title}
46
- Link: {link}
47
-
48
- Return the keywords as a comma-separated list.
49
- """
50
- response = client.chat.completions.create(
51
- model="gpt-4",
52
- messages=[{"role": "user", "content": prompt}],
53
- temperature=0.6,
54
- max_tokens=150
55
- )
56
-
57
- raw = response.choices[0].message.content
58
- return [kw.strip().lower() for kw in re.split(r'[,\n]', raw) if kw.strip()]
59
-
60
-
61
- def search_similar_events_and_products_openai(keywords):
62
- input_text = f"Generate 10 useful URLs for experiential event ideas or iBoothMe.com inspiration related to the keywords: {', '.join(keywords)}"
63
-
64
- try:
65
- print("🌐 Using OpenAI web search tool...")
66
- response = client.responses.create(
67
- model="gpt-4.1",
68
- tools=[{"type": "web_search_preview"}],
69
- input=input_text
70
- )
71
- content = response.output_text
72
- results = []
73
- for line in content.strip().split("\n"):
74
- if "http" in line:
75
- parts = line.split(" - ", 1)
76
- if len(parts) == 2:
77
- results.append((parts[0].strip(), parts[1].strip()))
78
- else:
79
- url = line.strip()
80
- results.append((url, url))
81
- return results[:10]
82
- except Exception as e:
83
- print(f"Search failed: {e}")
84
- return []
85
-
86
-
87
- def generate_event_ideas(paragraph, search_links, all_keywords, idea_count):
88
- search_summary = "\n".join([f"- {title}: {url}" for title, url in search_links])
89
-
90
- include_games = "game" in " ".join(all_keywords)
91
- if include_games:
92
- if idea_count == 6:
93
- game_instruction = "Include **only one** game-related idea (e.g. quiz game, vending challenge)."
94
- else:
95
- game_instruction = "Include **no more than two** game-related ideas."
96
- else:
97
- game_instruction = ""
98
-
99
- prompt = f"""
100
- You are an expert event strategist for iBoothMe, a company offering creative experiences like AI photo booths, smart vending machines, audio booths, personalization stations, and immersive visual storytelling.
101
-
102
- Based on the event description below, generate {idea_count} **unique and diverse** iBoothMe-powered event ideas.
103
-
104
- **Event Description:**
105
- {paragraph}
106
-
107
- **Inspiration from Related Ideas:**
108
- {search_summary}
109
-
110
- 💡 **Your Task:**
111
- Create ideas that are immersive, memorable, and creatively use iBoothMe's **photo, video, and audio**-based technologies. Do **not** use AR, VR, projection mapping, or other tech-heavy elements.
112
-
113
- You can optionally include:
114
- - Studio Ghibli-inspired visuals **(in just one idea)**
115
- - Personalized giveaways (e.g., Labibu dolls, custom t-shirts, stickers)
116
- - Audio booths, video diaries, face filters, sound remixes, or creative vending
117
-
118
- {game_instruction}
119
-
120
- ❗ Important:
121
- - Avoid using AR, VR, holograms, or projection domes
122
- - Don’t repeat formats like photo booths
123
- - Every idea should have a **creative title**
124
- - Each idea should be described in a paragraph
125
- - Immediately after, write a second paragraph continuing the **user journey flow** (e.g., user enters → takes photo → plays → receives item). No headings or bullet points.
126
-
127
- Return only the final ideas in markdown format.
128
- """
129
- response = client.chat.completions.create(
130
- model="gpt-4",
131
- messages=[{"role": "user", "content": prompt}],
132
- temperature=0.95,
133
- max_tokens=1500
134
- )
135
-
136
- return response.choices[0].message.content
137
-
138
-
139
- def main_workflow(paragraph):
140
- print("🚀 Started workflow")
141
-
142
- if not paragraph.strip():
143
- return "❌ Please enter an event description."
144
-
145
- print("🔍 Extracting keywords from paragraph...")
146
- base_keywords = extract_keywords(paragraph)
147
-
148
- print("🌐 Searching using OpenAI tool...")
149
- links = search_similar_events_and_products_openai(base_keywords)
150
-
151
- print("🔍 Extracting extra keywords from titles and links...")
152
- link_keywords = []
153
- for title, url in links:
154
- link_keywords.extend(extract_keywords_from_title_and_link(title, url))
155
-
156
- all_keywords = sorted(set(base_keywords + link_keywords))
157
-
158
- idea_count = random.choice([6, 7]) # randomly pick 6 or 7
159
- print(f"🧠 Generating {idea_count} ideas...")
160
- ideas = generate_event_ideas(paragraph, links, all_keywords, idea_count)
161
-
162
- keyword_summaries = []
163
- for kw in all_keywords[:10]:
164
- try:
165
- response = client.chat.completions.create(
166
- model="gpt-4",
167
- messages=[{"role": "user", "content": f"Give a short one-line event idea description using the keyword: {kw}"}],
168
- temperature=0.6,
169
- max_tokens=60
170
- )
171
- description = response.choices[0].message.content.strip()
172
- keyword_summaries.append(f"- **{kw.title()}**: {description}")
173
- except:
174
- keyword_summaries.append(f"- **{kw.title()}**")
175
-
176
- formatted_links = "\n".join(keyword_summaries)
177
-
178
- return f"""
179
- 🌐 **Relevant Ideas:**
180
- {formatted_links}
181
-
182
- {ideas}
183
- """
184
-
185
-
186
- # 🎨 Gradio UI
187
- with gr.Blocks(title="iBoothMe Event Ideation App") as demo:
188
- gr.Markdown("## 🎉 iBoothMe Event Idea Generator\nDescribe your event goal and receive interactive, tech-powered ideas!")
189
-
190
- paragraph = gr.Textbox(label="📝 Describe Your Event (e.g. Women's Day, Product Launch)", lines=4)
191
-
192
- submit_btn = gr.Button("🚀 Generate Event Concepts")
193
- output = gr.Markdown()
194
-
195
- submit_btn.click(
196
- fn=main_workflow,
197
- inputs=[paragraph],
198
- outputs=output,
199
- show_progress=True
200
- )
201
-
202
- demo.launch(inline=False, share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import re
3
+ import random
4
+ import json
5
+ from dotenv import load_dotenv
6
+ import os
7
+ from openai import OpenAI
8
+
9
+ # 🔐 Load API Key from .env
10
+ load_dotenv()
11
+ api_key = os.getenv("OPENAI_API_KEY")
12
+ client = OpenAI(api_key=api_key)
13
+
14
+ # 1) Load your product catalog once at startup
15
+ def load_product_catalog(path="products.json"):
16
+ with open(path, "r", encoding="utf-8") as f:
17
+ data = json.load(f)
18
+ # Expecting products_desc to be a dict: { "iboothme X": "…", }
19
+ return data["products_desc"]
20
+
21
+ PRODUCT_CATALOG = load_product_catalog()
22
+
23
+ # 2) Helper to pull full descriptions for a list of product names
24
+ def get_product_descriptions(product_names: list[str]) -> str:
25
+ entries = []
26
+ for name in product_names:
27
+ desc = PRODUCT_CATALOG.get(name)
28
+ if desc:
29
+ entries.append(f"**{name}**\n{desc}")
30
+ return "\n\n".join(entries)
31
+
32
+ # Keyword extraction from the paragraph
33
+ def extract_keywords(paragraph: str) -> list[str]:
34
+ prompt = f"""
35
+ You are an expert in experiential event planning.
36
+
37
+ Extract 5-10 short, specific, and thematic keywords or concepts from the event description below. These will be used to inspire immersive, tech-powered event ideas.
38
+
39
+ Each keyword should be 2-4 words long and describe a concrete idea or theme (e.g., "photo booths", "smart vending", "interactive storytelling").
40
+
41
+ Event Description:
42
+ \"{paragraph}\"
43
+
44
+ Return the keywords as a comma-separated list.
45
+ """
46
+ response = client.chat.completions.create(
47
+ model="gpt-4",
48
+ messages=[{"role": "user", "content": prompt}],
49
+ temperature=0.7,
50
+ max_tokens=200
51
+ )
52
+ raw = response.choices[0].message.content
53
+ return [kw.strip().lower() for kw in re.split(r'[,\n]', raw) if kw.strip()]
54
+
55
+ # (Optional) Keyword extraction from titles/links
56
+ def extract_keywords_from_title_and_link(title: str, link: str) -> list[str]:
57
+ prompt = f"""
58
+ You are an expert in event innovation.
59
+
60
+ Given the title and link below, extract 3-5 short, specific, and meaningful keywords or themes (2-4 words each) that describe what the page is about.
61
+
62
+ Title: {title}
63
+ Link: {link}
64
+
65
+ Return the keywords as a comma-separated list.
66
+ """
67
+ response = client.chat.completions.create(
68
+ model="gpt-4",
69
+ messages=[{"role": "user", "content": prompt}],
70
+ temperature=0.6,
71
+ max_tokens=150
72
+ )
73
+ raw = response.choices[0].message.content
74
+ return [kw.strip().lower() for kw in re.split(r'[,\n]', raw) if kw.strip()]
75
+
76
+ # (Optional) Web search for inspiration
77
+ def search_similar_events_and_products_openai(keywords: list[str]) -> list[tuple[str,str]]:
78
+ input_text = f"Generate 10 useful URLs for experiential event ideas or iboothme.com inspiration related to the keywords: {', '.join(keywords)}"
79
+ try:
80
+ response = client.responses.create(
81
+ model="gpt-4.1",
82
+ tools=[{"type": "web_search_preview"}],
83
+ input=input_text
84
+ )
85
+ content = response.output_text
86
+ results = []
87
+ for line in content.split("\n"):
88
+ if "http" in line:
89
+ parts = line.split(" - ", 1)
90
+ if len(parts) == 2:
91
+ results.append((parts[0].strip(), parts[1].strip()))
92
+ else:
93
+ url = line.strip()
94
+ results.append((url, url))
95
+ return results[:10]
96
+ except Exception as e:
97
+ print("Search failed:", e)
98
+ return []
99
+
100
+ # Core idea generation, enriched with random product descriptions
101
+ def generate_event_ideas(
102
+ paragraph: str,
103
+ product_info: str,
104
+ search_links: list[tuple[str,str]],
105
+ all_keywords: list[str],
106
+ idea_count: int
107
+ ) -> str:
108
+ search_summary = "\n".join([f"- {title}: {url}" for title, url in search_links])
109
+ include_games = any("game" in kw for kw in all_keywords)
110
+ game_instruction = "Include at least two game-related ideas (e.g., quiz game, vending challenge)." if include_games else ""
111
+
112
+ prompt = f"""
113
+ You are an expert event strategist for iboothme, a company offering creative experiences like AI photo booths, smart vending machines, audio booths, personalization stations, and immersive visual storytelling.
114
+
115
+ Below are full descriptions of three randomly selected iboothme products, to keep all ideas on-brand:
116
+ {product_info}
117
+
118
+ Based on the event description below, generate {idea_count} unique and diverse iboothme-powered event ideas.
119
+ Make sure that the syntax of the brand is always "iboothme" (all lowercase).
120
+
121
+ **Event Description:**
122
+ {paragraph}
123
+
124
+ **Inspiration from Related Ideas:**
125
+ {search_summary}
126
+
127
+ 💡 **Your Task:**
128
+ Create ideas that are immersive, memorable, and creatively use iboothme's photo, video, and audio-based technologies. Do not use AR, VR, projection mapping, or other tech-heavy elements.
129
+
130
+ You must include:
131
+ - At least two game-related ideas
132
+ - Studio Ghibli-inspired visuals in one idea
133
+ - Personalized giveaways (e.g., custom t-shirts, stickers, Labibu dolls)
134
+ {game_instruction}
135
+
136
+ Important:
137
+ - Avoid AR, VR, holograms, or projection domes
138
+ - Do not repeat photo‑booth formats
139
+ - Every idea should have a creative title
140
+ - Each idea should be described in a paragraph
141
+ - Immediately after, write a second paragraph describing the user journey flow
142
+
143
+ Return **only** the final ideas in markdown format.
144
+ """
145
+ resp = client.chat.completions.create(
146
+ model="gpt-4",
147
+ messages=[{"role": "user", "content": prompt}],
148
+ temperature=0.95,
149
+ max_tokens=1500
150
+ )
151
+ return resp.choices[0].message.content
152
+
153
+ # Main orchestration
154
+ def main_workflow(paragraph: str) -> str:
155
+ print("main_workflow called with paragraph:", paragraph)
156
+ if not paragraph.strip():
157
+ print("No paragraph provided.")
158
+ return "❌ Please enter an event description."
159
+
160
+ # 1. Randomly pick 3 products from your catalog
161
+ try:
162
+ gadget_names = random.sample(list(PRODUCT_CATALOG.keys()), k=4)
163
+ print("Randomly selected products:", gadget_names)
164
+ product_info = get_product_descriptions(gadget_names)
165
+ except Exception as e:
166
+ print("Error selecting products:", e)
167
+ return f" Error selecting products: {e}"
168
+
169
+ # 2. Gather keywords + optional web search
170
+ try:
171
+ base_kw = extract_keywords(paragraph)
172
+ print("Extracted base keywords:", base_kw)
173
+ links = search_similar_events_and_products_openai(base_kw)
174
+ print("Found links:", links)
175
+ link_kw = []
176
+ for t, u in links:
177
+ kws = extract_keywords_from_title_and_link(t, u)
178
+ print(f"Extracted keywords from link ({t}, {u}):", kws)
179
+ link_kw.extend(kws)
180
+ all_kw = sorted(set(base_kw + link_kw))
181
+ print("All keywords:", all_kw)
182
+ except Exception as e:
183
+ print("Error in keyword extraction or web search:", e)
184
+ return f"❌ Error in keyword extraction or web search: {e}"
185
+
186
+ # 3. Generate ideas
187
+ try:
188
+ idea_count = random.choice([5,6,7,8])
189
+ print("Idea count:", idea_count)
190
+ ideas_md = generate_event_ideas(paragraph, product_info, links, all_kw, idea_count)
191
+ print("Generated ideas markdown.")
192
+ except Exception as e:
193
+ print("Error generating ideas:", e)
194
+ return f"❌ Error generating ideas: {e}"
195
+
196
+ # 4. Summarize top keywords
197
+ summaries = []
198
+ for kw in all_kw[:10]:
199
+ try:
200
+ print(f"Summarizing keyword: {kw}")
201
+ r = client.chat.completions.create(
202
+ model="gpt-4",
203
+ messages=[{"role": "user", "content": f"Give a short one-line event idea description using the keyword: {kw}"}],
204
+ temperature=0.6,
205
+ max_tokens=60
206
+ )
207
+ desc = r.choices[0].message.content.strip()
208
+ summaries.append(f"- **{kw.title()}**: {desc}")
209
+ except Exception as e:
210
+ print(f"Error summarizing keyword {kw}:", e)
211
+ summaries.append(f"- **{kw.title()}**")
212
+
213
+ summary_md = "\n".join(summaries)
214
+ print("Returning final markdown output.")
215
+ return f"""
216
+ 🌐 **Relevant Keywords Summary:**
217
+ {summary_md}
218
+
219
+ {ideas_md}
220
+ """
221
+
222
+ # Custom theme and CSS for purple/white and gradient effects
223
+ custom_theme = gr.themes.Base(
224
+ primary_hue="purple",
225
+ secondary_hue="purple",
226
+ neutral_hue="gray"
227
+ ).set(
228
+ body_background_fill="white",
229
+ block_background_fill="white",
230
+ block_border_width="2px",
231
+ block_border_color="#a18cd1",
232
+ block_shadow="0 4px 24px 0 rgba(161,140,209,0.10)",
233
+ button_primary_background_fill="linear-gradient(90deg, #a18cd1 0%, #fbc2eb 100%)",
234
+ button_primary_text_color="white",
235
+ button_primary_shadow="0 2px 8px 0 rgba(161,140,209,0.10)",
236
+ input_background_fill="white",
237
+ input_border_color="#a18cd1",
238
+ input_shadow="0 2px 8px 0 rgba(161,140,209,0.05)"
239
+ )
240
+
241
+ custom_css = """
242
+ #iboothme-heading {
243
+ font-weight: 900 !important;
244
+ font-size: 2.5rem !important;
245
+ background: linear-gradient(90deg, #a18cd1 0%, #fbc2eb 100%);
246
+ -webkit-background-clip: text;
247
+ -webkit-text-fill-color: black;
248
+ margin-bottom: 0.5em;
249
+ text-align: center;
250
+ letter-spacing: 1px;
251
+ }
252
+ #desc-subheading {
253
+ text-align: center;
254
+ font-size: 1.15rem;
255
+ font-weight: 500;
256
+ color: #6d4fa7;
257
+ margin-bottom: 2em;
258
+ }
259
+ .gradio-container { min-height: 100vh; background: white !important; }
260
+ .gr-box, .gr-input, .gr-button, .gr-markdown, .gr-textbox, .gr-column, .gr-row {
261
+ border-radius: 18px !important;
262
+ }
263
+ #event-desc-box, #output-box {
264
+ border: 2px solid #a18cd1 !important;
265
+ box-shadow: 0 4px 24px 0 rgba(161,140,209,0.10) !important;
266
+ background: white !important;
267
+ }
268
+ #generate-btn {
269
+ font-weight: bold;
270
+ font-size: 1.1rem;
271
+ background: linear-gradient(90deg, #a18cd1 0%, #fbc2eb 100%) !important;
272
+ color: white !important;
273
+ border-radius: 12px !important;
274
+ box-shadow: 0 2px 8px 0 rgba(161,140,209,0.10) !important;
275
+ margin-top: 1.5em;
276
+ }
277
+ """
278
+
279
+ with gr.Blocks(theme=custom_theme, css=custom_css, title="iboothme Event Ideation App") as demo:
280
+ gr.Markdown(
281
+ "<div id='iboothme-heading'>🎉 <b>iboothme Event Idea Generator</b></div>"
282
+ "<div id='desc-subheading'>Describe your event goal and receive interactive, tech‑powered ideas!</div>"
283
+ )
284
+ with gr.Row():
285
+ with gr.Column(scale=2):
286
+ paragraph = gr.Textbox(
287
+ label="📝 Describe Your Event (e.g. Women’s Day, Product Launch)",
288
+ lines=4,
289
+ elem_id="event-desc-box"
290
+ )
291
+ with gr.Column(scale=1, min_width=220):
292
+ submit_btn = gr.Button("🚀 Generate Event Concepts", elem_id="generate-btn")
293
+ output = gr.Markdown(elem_id="output-box")
294
+
295
+ submit_btn.click(
296
+ fn=main_workflow,
297
+ inputs=[paragraph],
298
+ outputs=output,
299
+ show_progress=True
300
+ )
301
+
302
+ demo.launch(inline=False, share=True)