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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -30
app.py CHANGED
@@ -1,14 +1,14 @@
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():
@@ -27,27 +27,33 @@ def get_recommendations():
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
  ]
@@ -55,40 +61,55 @@ def gemma_image_analysis(image: Image.Image):
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
  )
94
  with gr.Row():
@@ -110,3 +131,4 @@ def main():
110
  if __name__ == "__main__":
111
  demo = main()
112
  demo.launch()
 
 
1
  import gradio as gr
2
  from PIL import Image
 
3
  import io
4
+ import os
5
  from huggingface_hub import InferenceClient
6
 
7
+ # You may need to set your Hugging Face token as an environment variable:
8
+ # os.environ["HF_TOKEN"] = "your-hf-token"
9
  client = InferenceClient(
10
  model="google/gemma-3-4b-it",
11
+ token=os.environ.get("HF_TOKEN") # Add your token if needed for Spaces
12
  )
13
 
14
  def get_recommendations():
 
27
  ]
28
 
29
  def gemma_image_analysis(image: Image.Image):
 
30
  buf = io.BytesIO()
31
  image.save(buf, format="PNG")
32
  buf.seek(0)
33
  img_bytes = buf.read()
34
 
 
 
 
35
  messages = [
36
  {
37
  "role": "system",
38
  "content": [
39
+ {"type": "text", "text": (
40
+ "You are an expert ad analyst AI. Analyze the given ad and provide answers for three sections:"
41
+ " 1. Category (one word),"
42
+ " 2. Analysis (five sentences),"
43
+ " 3. Five unique, actionable improvement suggestions as a list starting with '- '."
44
+ " Output must be in three sections with clear headings."
45
+ )}
46
  ]
47
  },
48
  {
49
  "role": "user",
50
  "content": [
51
+ {"type": "image", "image": img_bytes},
52
+ {"type": "text", "text": (
53
+ "Please respond with:\n\nCategory:\n[category]\n\nAnalysis:\n[5 sentences]\n\nImprovement Suggestions:\n"
54
+ "- [suggestion 1]\n- [suggestion 2]\n- [suggestion 3]\n- [suggestion 4]\n- [suggestion 5]\n\n"
55
+ "Each suggestion must be unique and actionable. Do not repeat suggestions. If you don't know, say 'not detected'."
56
+ )}
57
  ]
58
  }
59
  ]
 
61
  response = client.chat.completions.create(
62
  model="google/gemma-3-4b-it",
63
  messages=messages,
64
+ max_tokens=512,
65
  )
66
 
67
  return response.choices[0].message["content"]
68
 
69
+ def process(image: Image.Image):
70
  if image is None:
71
  return "", "", "", get_recommendations()
72
 
73
+ # Run multimodal analysis
74
  full_output = gemma_image_analysis(image)
75
+
76
+ # Parse the output into sections (simple but robust splitting)
77
+ category = ""
78
+ analysis = ""
79
+ suggestions = ""
80
+ # Find the sections in model output (robust to little formatting errors)
81
  try:
82
+ lower = full_output.lower()
83
+ cat_idx = lower.find("category")
84
+ ana_idx = lower.find("analysis")
85
+ sug_idx = lower.find("improvement suggestions")
86
+
87
+ if cat_idx != -1 and ana_idx != -1:
88
+ category = full_output[cat_idx + 8 : ana_idx].strip().strip(":")
89
+ if ana_idx != -1 and sug_idx != -1:
90
+ analysis = full_output[ana_idx + 8 : sug_idx].strip().strip(":")
91
+ if sug_idx != -1:
92
+ suggestions = full_output[sug_idx + len("improvement suggestions"):].strip()
93
  except Exception:
94
+ # Fallback if parsing fails
95
+ return "", "Analysis parsing failed", "Suggestion parsing failed", get_recommendations()
96
 
97
+ return category.strip(), analysis.strip(), suggestions.strip(), get_recommendations()
98
 
99
  def main():
100
+ with gr.Blocks(title="Smart Ad Analyzer") as demo:
101
+ gr.Markdown("## 📢 Smart Ad Analyzer (Gemma-3 Model)")
102
  gr.Markdown(
103
  """
104
+ **Upload your ad image below and instantly get expert feedback.**
105
+
106
+ This AI tool will analyze your ad and provide:
107
+ - 📂 **Category** — What type of ad is this?
108
+ - 📊 **In-depth Analysis** — Five detailed sentences covering message, visuals, emotional impact, and more.
109
+ - 🚀 **Improvement Suggestions** — Five actionable, unique ways to make your ad better.
110
+ - 📸 **Inspiration Gallery** — See other effective ads for ideas.
111
+
112
+ Perfect for marketers, founders, designers, and anyone looking to boost ad performance with actionable insights!
113
  """
114
  )
115
  with gr.Row():
 
131
  if __name__ == "__main__":
132
  demo = main()
133
  demo.launch()
134
+