Tulitula commited on
Commit
af2ea48
·
verified ·
1 Parent(s): 16e5543

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -68
app.py CHANGED
@@ -1,23 +1,25 @@
1
- import os
2
  import gradio as gr
3
  from PIL import Image
4
- from transformers import BlipProcessor, BlipForConditionalGeneration, pipeline as hf_pipeline
5
- import openai
6
-
7
- # Read OpenAI API key
8
- openai.api_key = os.getenv("OPENAI_API_KEY")
9
- has_api = bool(openai.api_key)
10
-
11
- # Load BLIP for image captioning
12
- blip_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
13
- blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
14
-
15
- # Local fallback generator (EleutherAI GPT-Neo 2.7B)
16
- local_generator = hf_pipeline(
17
- "text-generation",
18
- model="EleutherAI/gpt-neo-2.7B",
19
- tokenizer="EleutherAI/gpt-neo-2.7B",
20
- framework="pt"
 
 
 
21
  )
22
 
23
 
@@ -26,83 +28,64 @@ def get_recommendations():
26
  "https://i.imgur.com/InC88PP.jpeg",
27
  "https://i.imgur.com/7BHfv4T.png",
28
  "https://i.imgur.com/wp3Wzc4.jpeg",
29
- # ... other URLs ...
30
  ]
31
 
32
 
33
  def generate_caption(image):
34
  inputs = blip_processor(images=image, return_tensors="pt")
35
  out = blip_model.generate(**inputs)
36
- return blip_processor.decode(out[0], skip_special_tokens=True)
 
37
 
38
 
39
  def generate_advice_from_caption(caption):
40
- if has_api:
41
- try:
42
- messages = [
43
- {"role": "system", "content": "You are an expert ad copywriter."},
44
- {"role": "user", "content": (
45
- f"Ad description: {caption}\n"
46
- "Suggest three specific improvements to this ad. "
47
- "Focus on a clear call to action, highlight key benefits, and boost visual appeal. "
48
- "Return concise bullet points."
49
- )}
50
- ]
51
- resp = openai.ChatCompletion.create(
52
- model="gpt-3.5-turbo",
53
- messages=messages,
54
- temperature=0.7,
55
- max_tokens=200
56
- )
57
- return resp.choices[0].message.content.strip()
58
- except Exception as e:
59
- return f"Error generating suggestions: {e}"
60
- else:
61
- prompt = (
62
- f"Ad description: {caption}\n"
63
- "Suggest three specific improvements as bullet points."
64
- )
65
- result = local_generator(
66
- prompt,
67
- max_new_tokens=150,
68
- do_sample=True,
69
- temperature=0.8,
70
- top_k=40,
71
- top_p=0.9
72
- )
73
- # remove prompt from output
74
- text = result[0]["generated_text"].replace(prompt, "").strip()
75
- return text
76
 
77
 
78
  def analyze_caption(caption):
79
  keywords = ["product", "offer", "smile", "call to action", "brand"]
80
- return (
81
- "👍 Likely effective for advertising."
82
- if any(k in caption.lower() for k in keywords)
83
- else "👎 Consider clearer focus or stronger messaging."
84
- )
85
 
86
 
87
  def process(image):
88
  caption = generate_caption(image)
89
  suggestions = generate_advice_from_caption(caption)
90
  analysis = analyze_caption(caption)
91
- recs = get_recommendations()
92
- return caption, suggestions, analysis, recs
93
 
94
  with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
95
  gr.Markdown("## 📢 Smart Ad Analyzer")
96
  gr.Markdown(
97
- "Upload an image ad. The model will caption it, suggest improvements, analyze focus, and show examples."
98
  )
99
 
100
  with gr.Row():
101
  image_input = gr.Image(type="pil", label="Upload Ad Image")
102
  with gr.Column():
103
- caption_out = gr.Textbox(label="Generated Caption", interactive=False)
104
- suggestion_out = gr.Textbox(label="Improvement Suggestions", interactive=False)
105
- analysis_out = gr.Textbox(label="Ad Analysis", interactive=False)
 
 
 
 
 
 
106
 
107
  btn = gr.Button("Analyze Ad")
108
  recommendation_gallery = gr.Gallery(label="Recommended Example Ads")
@@ -115,4 +98,5 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
115
 
116
  gr.Markdown("Made by Simon Thalmay")
117
 
118
- if __name__ == "__main__":
 
 
 
1
  import gradio as gr
2
  from PIL import Image
3
+ from transformers import BlipProcessor, BlipForConditionalGeneration, pipeline
4
+
5
+ # Initialize BLIP for image captioning
6
+ blip_processor = BlipProcessor.from_pretrained(
7
+ "Salesforce/blip-image-captioning-base"
8
+ )
9
+ blip_model = BlipForConditionalGeneration.from_pretrained(
10
+ "Salesforce/blip-image-captioning-base"
11
+ )
12
+
13
+ # Instruction‑tuned HF model for ad improvement suggestions
14
+ adv_generator = pipeline(
15
+ "text2text-generation",
16
+ model="google/flan-ul2",
17
+ tokenizer="google/flan-ul2",
18
+ max_new_tokens=150,
19
+ do_sample=True,
20
+ temperature=0.7,
21
+ top_k=50,
22
+ top_p=0.95
23
  )
24
 
25
 
 
28
  "https://i.imgur.com/InC88PP.jpeg",
29
  "https://i.imgur.com/7BHfv4T.png",
30
  "https://i.imgur.com/wp3Wzc4.jpeg",
31
+ # ... add more examples as needed
32
  ]
33
 
34
 
35
  def generate_caption(image):
36
  inputs = blip_processor(images=image, return_tensors="pt")
37
  out = blip_model.generate(**inputs)
38
+ caption = blip_processor.decode(out[0], skip_special_tokens=True)
39
+ return caption
40
 
41
 
42
  def generate_advice_from_caption(caption):
43
+ """
44
+ Uses a Hugging Face instruction‑tuned model (Flan‑UL2) to turn the BLIP caption
45
+ into targeted, bullet‑pointed ad improvement suggestions.
46
+ """
47
+ prompt = (
48
+ f"Ad description: {caption}\n"
49
+ "Please suggest three specific improvements as bullet points, focusing on a clear call to action, key benefits, and visual appeal."
50
+ )
51
+ result = adv_generator(prompt)
52
+ # The model output may include the prompt, so extract after prompt
53
+ text = result[0]["generated_text"].replace(prompt, "").strip()
54
+ return text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
 
57
  def analyze_caption(caption):
58
  keywords = ["product", "offer", "smile", "call to action", "brand"]
59
+ if any(k in caption.lower() for k in keywords):
60
+ return "👍 Likely effective for advertising."
61
+ return "👎 Consider clearer focus or stronger messaging."
 
 
62
 
63
 
64
  def process(image):
65
  caption = generate_caption(image)
66
  suggestions = generate_advice_from_caption(caption)
67
  analysis = analyze_caption(caption)
68
+ recomms = get_recommendations()
69
+ return caption, suggestions, analysis, recomms
70
 
71
  with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
72
  gr.Markdown("## 📢 Smart Ad Analyzer")
73
  gr.Markdown(
74
+ "Upload an image ad. The app will caption it, suggest improvements with a local instruction‑tuned model, analyze focus, and show example ads."
75
  )
76
 
77
  with gr.Row():
78
  image_input = gr.Image(type="pil", label="Upload Ad Image")
79
  with gr.Column():
80
+ caption_out = gr.Textbox(
81
+ label="Generated Caption", interactive=False
82
+ )
83
+ suggestion_out = gr.Textbox(
84
+ label="Improvement Suggestions", interactive=False
85
+ )
86
+ analysis_out = gr.Textbox(
87
+ label="Ad Analysis", interactive=False
88
+ )
89
 
90
  btn = gr.Button("Analyze Ad")
91
  recommendation_gallery = gr.Gallery(label="Recommended Example Ads")
 
98
 
99
  gr.Markdown("Made by Simon Thalmay")
100
 
101
+ if __name__ == "__main__":
102
+ demo.launch()