Tulitula commited on
Commit
e439e10
·
verified ·
1 Parent(s): cac9a7a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -56
app.py CHANGED
@@ -1,18 +1,18 @@
1
  import gradio as gr
2
  from PIL import Image
3
- import io
4
  import os
 
5
  from huggingface_hub import InferenceClient
6
 
7
- # Authenticate (Space secrets or env variable)
8
- HF_TOKEN = os.environ.get("HF_TOKEN")
9
  client = InferenceClient(
10
- repo_id="google/gemma-3-4b-it",
11
  token=HF_TOKEN
12
  )
13
 
14
  def get_recommendations():
15
- # Example ad image URLs for the gallery
16
  return [
17
  "https://i.imgur.com/InC88PP.jpeg",
18
  "https://i.imgur.com/7BHfv4T.png",
@@ -26,65 +26,68 @@ def get_recommendations():
26
  "https://i.imgur.com/Xj92Cjv.jpeg",
27
  ]
28
 
29
- def process(image: Image.Image):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  if image is None:
31
  return "", "", "", get_recommendations()
32
- try:
33
- # Convert PIL image to bytes
34
- buf = io.BytesIO()
35
- image.save(buf, format="PNG")
36
- image_bytes = buf.getvalue()
37
-
38
- prompt = (
39
- "You are an expert ad analyst. "
40
- "Given the uploaded image, return these sections:\n\n"
41
- "Category: (a one or two word category, e.g. 'Fitness', 'Food', 'Travel')\n"
42
- "Analysis: Write exactly five sentences about the ad's message, visuals, and emotional impact.\n"
43
- "Suggestions: List five actionable and unique improvements for this ad. "
44
- "Each suggestion must be one sentence and start with '- '. Suggestions must address different aspects: visuals, messaging, call-to-action, targeting, or layout."
45
- )
46
- messages = [
47
- {
48
- "role": "system",
49
- "content": [{"type": "text", "text": "You are a helpful assistant."}]
50
- },
51
- {
52
- "role": "user",
53
- "content": [
54
- {"type": "image", "image": image_bytes},
55
- {"type": "text", "text": prompt}
56
- ]
57
- }
58
- ]
59
- # Model call
60
- output = client.chat.completions.create(
61
- model="google/gemma-3-4b-it",
62
- messages=messages,
63
- max_tokens=800
64
- )
65
- text = output.choices[0].message["content"]
66
 
67
- # Simple parsing
68
- cat, analysis, suggestions = "", "", ""
69
- if "Category:" in text and "Analysis:" in text and "Suggestions:" in text:
70
- cat = text.split("Category:")[1].split("Analysis:")[0].strip()
71
- analysis = text.split("Analysis:")[1].split("Suggestions:")[0].strip()
72
- suggestions = text.split("Suggestions:")[1].strip()
73
- else:
74
- # fallback: show all in analysis, nothing for cat/suggestions
75
- analysis = text
 
 
 
 
 
 
76
 
77
- return cat, analysis, suggestions, get_recommendations()
78
- except Exception as e:
79
- # For debugging
80
- return "Error", "Error", "Error", ["Error"]
81
 
82
  def main():
83
  with gr.Blocks(title="Smart Ad Analyzer (Gemma-3 Edition)") as demo:
84
  gr.Markdown("## 📢 Smart Ad Analyzer (Gemma-3 Edition)")
85
  gr.Markdown(
86
  """
87
- Upload your ad image below and instantly get expert feedback.<br>
88
  Category, analysis, improvement suggestions—and example ads for inspiration.
89
  """
90
  )
@@ -92,8 +95,8 @@ def main():
92
  inp = gr.Image(type='pil', label='Upload Ad Image')
93
  with gr.Column():
94
  cat_out = gr.Textbox(label='📂 Ad Category', interactive=False)
95
- ana_out = gr.Textbox(label='📊 Ad Analysis', lines=7, interactive=False)
96
- sug_out = gr.Textbox(label='🚀 Improvement Suggestions', lines=8, interactive=False)
97
  btn = gr.Button('Analyze Ad', variant='primary')
98
  gallery = gr.Gallery(label='Example Ads')
99
  btn.click(
 
1
  import gradio as gr
2
  from PIL import Image
 
3
  import os
4
+ import io
5
  from huggingface_hub import InferenceClient
6
 
7
+ HF_TOKEN = os.environ.get("HF_TOKEN") # For Hugging Face Spaces
8
+
9
  client = InferenceClient(
10
+ model="google/gemma-3-4b-it",
11
  token=HF_TOKEN
12
  )
13
 
14
  def get_recommendations():
15
+ # Returns list of 10 example ad image URLs
16
  return [
17
  "https://i.imgur.com/InC88PP.jpeg",
18
  "https://i.imgur.com/7BHfv4T.png",
 
26
  "https://i.imgur.com/Xj92Cjv.jpeg",
27
  ]
28
 
29
+ def gemma_image_analysis(image: Image.Image):
30
+ # Convert image to bytes and upload as a file
31
+ buf = io.BytesIO()
32
+ image.save(buf, format="PNG")
33
+ buf.seek(0)
34
+ img_bytes = buf.read()
35
+
36
+ # Upload image to Hugging Face hub and get a URL
37
+ img_url = client.upload_image(img_bytes)
38
+ # Compose multimodal message for Gemma-3
39
+ messages = [
40
+ {
41
+ "role": "system",
42
+ "content": [
43
+ {"type": "text", "text": "You are an expert ad analyst AI. Analyze the given ad and provide answers for three sections: 1. Category (one word) 2. Analysis (five sentences) 3. Five unique actionable improvement suggestions as a list starting with '- ' each. Output must be in three sections with clear headings."}
44
+ ]
45
+ },
46
+ {
47
+ "role": "user",
48
+ "content": [
49
+ {"type": "image_url", "image_url": {"url": img_url}},
50
+ {"type": "text", "text": "Please respond with:\n\nCategory:\n[category]\n\nAnalysis:\n[5 sentences]\n\nImprovement Suggestions:\n- [suggestion 1]\n- [suggestion 2]\n- [suggestion 3]\n- [suggestion 4]\n- [suggestion 5]\n\nEach suggestion must be unique and actionable."}
51
+ ]
52
+ }
53
+ ]
54
+
55
+ response = client.chat.completions.create(
56
+ model="google/gemma-3-4b-it",
57
+ messages=messages,
58
+ max_tokens=500
59
+ )
60
+
61
+ return response.choices[0].message["content"]
62
+
63
+ def process(image):
64
  if image is None:
65
  return "", "", "", get_recommendations()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
+ full_output = gemma_image_analysis(image)
68
+ # Parse the response into 3 sections
69
+ cat, ana, sugs = "", "", ""
70
+ try:
71
+ parts = full_output.split("Analysis:")
72
+ if len(parts) >= 2:
73
+ cat = parts[0].replace("Category:", "").strip()
74
+ rest = parts[1].split("Improvement Suggestions:")
75
+ if len(rest) == 2:
76
+ ana = rest[0].strip()
77
+ sugs = rest[1].strip()
78
+ else:
79
+ ana = parts[1].strip()
80
+ except Exception:
81
+ cat, ana, sugs = "", "", full_output.strip()
82
 
83
+ return cat, ana, sugs, get_recommendations()
 
 
 
84
 
85
  def main():
86
  with gr.Blocks(title="Smart Ad Analyzer (Gemma-3 Edition)") as demo:
87
  gr.Markdown("## 📢 Smart Ad Analyzer (Gemma-3 Edition)")
88
  gr.Markdown(
89
  """
90
+ Upload your ad image below and instantly get expert feedback.
91
  Category, analysis, improvement suggestions—and example ads for inspiration.
92
  """
93
  )
 
95
  inp = gr.Image(type='pil', label='Upload Ad Image')
96
  with gr.Column():
97
  cat_out = gr.Textbox(label='📂 Ad Category', interactive=False)
98
+ ana_out = gr.Textbox(label='📊 Ad Analysis', lines=5, interactive=False)
99
+ sug_out = gr.Textbox(label='🚀 Improvement Suggestions', lines=5, interactive=False)
100
  btn = gr.Button('Analyze Ad', variant='primary')
101
  gallery = gr.Gallery(label='Example Ads')
102
  btn.click(