Tulitula commited on
Commit
7bffaa8
Β·
verified Β·
1 Parent(s): b3deaba

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -29
app.py CHANGED
@@ -96,7 +96,7 @@ def get_recommendations():
96
  def process(image: Image):
97
  try:
98
  if image is None:
99
- return "Please upload an image", "", "", "", get_recommendations()
100
 
101
  # 1) BLIP caption
102
  caption_result = caption_pipe(image, max_new_tokens=64)
@@ -119,57 +119,69 @@ def process(image: Image):
119
 
120
  # 3) Five-sentence analysis
121
  ana_prompt = (
122
- f"Description: {desc}\n\n"
123
- "Write exactly five sentences explaining what this ad communicates and its emotional impact."
124
  )
125
  raw_ana_result = analysis_pipe(ana_prompt)
126
  raw_ana = raw_ana_result[0]['generated_text'].strip()
127
  sentences = re.split(r'(?<=[.!?])\s+', raw_ana)
128
- analysis = " ".join(sentences[:5])
 
 
 
 
 
129
 
130
  # 4) Five bullet-point suggestions
131
  sug_prompt = (
132
- f"Description: {desc}\n\n"
133
- "Suggest five distinct improvements for this ad. Each must start with '- ' and be one sentence."
134
  )
135
  raw_sug_result = suggestion_pipe(sug_prompt)
136
  raw_sug = raw_sug_result[0]['generated_text'].strip()
137
- bullets = [l for l in raw_sug.splitlines() if l.startswith('-')]
138
- if len(bullets) < 5:
139
- extra = [l for l in raw_sug.splitlines() if l.strip()]
140
- for line in extra:
141
- if len(bullets) >= 5:
142
- break
143
- bullets.append(line if line.startswith('-') else '- ' + line)
144
- suggestions = '\n'.join(bullets[:5])
145
-
146
- return caption, category, analysis, suggestions, get_recommendations()
 
 
 
 
 
 
 
 
147
 
148
  except Exception as e:
149
- error_msg = f"Error processing image: {str(e)}"
150
  print(error_msg)
151
- return error_msg, "", "", "", get_recommendations()
152
 
153
  # Gradio UI definition
154
  def main():
155
  with gr.Blocks(title="Smart Ad Analyzer") as demo:
156
  gr.Markdown("## πŸ“’ Smart Ad Analyzer")
157
  gr.Markdown(
158
- "Upload an image ad to get:\n"
159
- "- **BLIP Caption** (raw)\n"
160
- "- **Ad Category**\n"
161
- "- **Five-sentence Analysis**\n"
162
- "- **Five bullet-point Suggestions**\n"
163
- "- **Example Ads**"
164
  )
165
 
166
  with gr.Row():
167
  inp = gr.Image(type='pil', label='Upload Ad Image')
168
  with gr.Column():
169
- cap_out = gr.Textbox(label='πŸ” BLIP Caption', interactive=False)
170
- cat_out = gr.Textbox(label='Ad Category', interactive=False)
171
- ana_out = gr.Textbox(label='Ad Analysis', lines=5, interactive=False)
172
- sug_out = gr.Textbox(label='Improvement Suggestions', lines=5, interactive=False)
173
  btn = gr.Button('Analyze Ad', size='sm', variant='primary')
174
 
175
  gallery = gr.Gallery(label='Example Ads') # Empty initially
@@ -177,7 +189,7 @@ def main():
177
  btn.click(
178
  fn=process,
179
  inputs=[inp],
180
- outputs=[cap_out, cat_out, ana_out, sug_out, gallery],
181
  )
182
 
183
  gr.Markdown('Made by Simon Thalmay')
 
96
  def process(image: Image):
97
  try:
98
  if image is None:
99
+ return "", "", "", get_recommendations()
100
 
101
  # 1) BLIP caption
102
  caption_result = caption_pipe(image, max_new_tokens=64)
 
119
 
120
  # 3) Five-sentence analysis
121
  ana_prompt = (
122
+ f"Based on this advertisement description: {desc}\n\n"
123
+ "Write exactly 5 detailed sentences analyzing this advertisement. Cover: 1) What product/service is being advertised, 2) The main visual elements and design, 3) The target audience, 4) The marketing message or value proposition, 5) The emotional appeal or persuasion technique used. Make each sentence substantial and informative."
124
  )
125
  raw_ana_result = analysis_pipe(ana_prompt)
126
  raw_ana = raw_ana_result[0]['generated_text'].strip()
127
  sentences = re.split(r'(?<=[.!?])\s+', raw_ana)
128
+ # Take first 5 sentences and ensure they're substantial
129
+ analysis_sentences = []
130
+ for i, sentence in enumerate(sentences[:8]): # Look at more sentences to find 5 good ones
131
+ if len(sentence.strip()) > 20 and len(analysis_sentences) < 5: # Filter short sentences
132
+ analysis_sentences.append(sentence.strip())
133
+ analysis = " ".join(analysis_sentences[:5])
134
 
135
  # 4) Five bullet-point suggestions
136
  sug_prompt = (
137
+ f"Based on this advertisement: {desc}\n\n"
138
+ "Provide exactly 5 specific, actionable improvement suggestions for this advertisement. Focus on concrete changes like: visual design improvements, clearer messaging, better call-to-action, enhanced targeting, or stronger emotional appeal. Each suggestion should be one clear sentence starting with '- ' and be practical to implement."
139
  )
140
  raw_sug_result = suggestion_pipe(sug_prompt)
141
  raw_sug = raw_sug_result[0]['generated_text'].strip()
142
+
143
+ # Better parsing of suggestions
144
+ lines = raw_sug.split('\n')
145
+ suggestions_list = []
146
+ for line in lines:
147
+ line = line.strip()
148
+ if line.startswith('-'):
149
+ suggestions_list.append(line)
150
+ elif line and not line.startswith('-') and len(suggestions_list) < 5:
151
+ suggestions_list.append(f"- {line}")
152
+
153
+ # Ensure we have exactly 5 suggestions
154
+ while len(suggestions_list) < 5:
155
+ suggestions_list.append(f"- Improve visual hierarchy and readability")
156
+
157
+ suggestions = '\n'.join(suggestions_list[:5])
158
+
159
+ return category, analysis, suggestions, get_recommendations()
160
 
161
  except Exception as e:
162
+ error_msg = f"Error analyzing advertisement: {str(e)}"
163
  print(error_msg)
164
+ return "Analysis failed", error_msg, "", get_recommendations()
165
 
166
  # Gradio UI definition
167
  def main():
168
  with gr.Blocks(title="Smart Ad Analyzer") as demo:
169
  gr.Markdown("## πŸ“’ Smart Ad Analyzer")
170
  gr.Markdown(
171
+ "Transform your advertising with AI-powered insights! Upload any advertisement image to receive:\n\n"
172
+ "🎯 **Smart Categorization** - Automatically classify your ad type\n\n"
173
+ "πŸ” **Deep Analysis** - Get a comprehensive 5-sentence breakdown of your ad's message, visual elements, and emotional impact\n\n"
174
+ "πŸ’‘ **Actionable Improvements** - Receive 5 specific, practical suggestions to enhance your ad's effectiveness\n\n"
175
+ "πŸ“Έ **Inspiration Gallery** - Discover example ads after your analysis\n\n"
176
+ "Perfect for marketers, business owners, and creative professionals looking to optimize their advertising campaigns!"
177
  )
178
 
179
  with gr.Row():
180
  inp = gr.Image(type='pil', label='Upload Ad Image')
181
  with gr.Column():
182
+ cat_out = gr.Textbox(label='πŸ“‚ Ad Category', interactive=False)
183
+ ana_out = gr.Textbox(label='πŸ“Š Ad Analysis', lines=8, interactive=False)
184
+ sug_out = gr.Textbox(label='πŸš€ Improvement Suggestions', lines=8, interactive=False)
 
185
  btn = gr.Button('Analyze Ad', size='sm', variant='primary')
186
 
187
  gallery = gr.Gallery(label='Example Ads') # Empty initially
 
189
  btn.click(
190
  fn=process,
191
  inputs=[inp],
192
+ outputs=[cat_out, ana_out, sug_out, gallery],
193
  )
194
 
195
  gr.Markdown('Made by Simon Thalmay')