r1sh1 commited on
Commit
cc5ef85
·
verified ·
1 Parent(s): 459aa22

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -3
app.py CHANGED
@@ -6,7 +6,10 @@ from PIL import Image
6
  import io
7
  import json
8
  import hashlib
 
 
9
  app = FastAPI()
 
10
  app.add_middleware(
11
  CORSMiddleware,
12
  allow_origins=["*"],
@@ -14,9 +17,12 @@ app.add_middleware(
14
  allow_methods=["*"],
15
  allow_headers=["*"],
16
  )
 
17
  print("Initializing backend...")
 
18
  GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
19
  MODEL_LOADED = False
 
20
  if GEMINI_API_KEY:
21
  try:
22
  genai.configure(api_key=GEMINI_API_KEY)
@@ -46,9 +52,11 @@ if GEMINI_API_KEY:
46
  print(f"General configuration error: {e}")
47
  else:
48
  print("Warning: GEMINI_API_KEY environment variable not set. Running in simulation mode.")
 
49
  @app.get("/")
50
  def read_root():
51
  return {"status": "online", "engine": "Creative Intelligence Engine", "active": True}
 
52
  @app.get("/api/health")
53
  def health_check():
54
  return {
@@ -57,16 +65,19 @@ def health_check():
57
  "api_key_configured": bool(GEMINI_API_KEY),
58
  "message": "Neural Engine analysis is operational."
59
  }
 
60
  prompt_template = """
61
  You are a neuromarketing expert AI analyzing an ad creative image critically with emphasis on copy, CTA, best time and platform etc..
62
  Evaluate this image strictly on these 5 cognitive parameters. Give a score between 0.10 and 0.98.
63
  Also provide a VERY brief 1-sentence analytical reason based exactly on what is visibly in the image.
 
64
  The parameters are:
65
  - visual_saliency (How effectively it draws the eye with contrast, colors, shapes)
66
  - cognitive_ease (Clean layout vs clutter. Higher score = easier to process)
67
  - emotional_arousal (Does it trigger a mood via faces, colors, or atmosphere)
68
  - value_recognition (Speed of identifying the core reward/benefit/CTA)
69
  - memory_encoding (Distinctiveness of brand motifs, logos, or striking imagery)
 
70
  Return strictly valid JSON containing a single "scores" object, a "reasons" object, and an "insights" array.
71
  Format:
72
  {
@@ -89,6 +100,7 @@ Format:
89
  ]
90
  }
91
  """
 
92
  @app.post("/api/analyze")
93
  async def analyze_creative(
94
  creative: UploadFile = File(None),
@@ -119,14 +131,25 @@ async def analyze_creative(
119
  scores = data.get("scores", {})
120
  reasons = data.get("reasons", {})
121
  insights = data.get("insights", ["Analysis completed successfully."])
 
 
 
 
 
 
 
 
 
 
122
  except Exception as e:
 
123
  scores = {
124
  "visual_saliency": 0.32, "cognitive_ease": 0.28,
125
  "emotional_arousal": 0.10, "value_recognition": 0.45, "memory_encoding": 0.24
126
  }
127
- reasons = {k: f"Error: {str(e)[:50]}..." for k in scores}
128
- insights = [f"API Error: {str(e)}"]
129
- source = f"HF Space (Error)"
130
  else:
131
  # Deterministic fallback based on file name
132
  seed = name + description
@@ -148,6 +171,7 @@ async def analyze_creative(
148
  }
149
  insights = ["Running in simulation mode. No valid GEMINI_API_KEY provided."]
150
  source = "HF Space (Simulation Fallback)"
 
151
  # Calculate timeline metrics from current scores (averaging for consistency)
152
  avg_score = sum(scores.values()) / len(scores) if scores else 0.5
153
  timeline = {
@@ -157,6 +181,7 @@ async def analyze_creative(
157
  }
158
  # Clamp timeline scores to 100
159
  timeline = {k: min(v, 99.0) for k, v in timeline.items()}
 
160
  return {
161
  "id": id,
162
  "name": name,
 
6
  import io
7
  import json
8
  import hashlib
9
+ from google.api_core import exceptions as google_exceptions
10
+
11
  app = FastAPI()
12
+
13
  app.add_middleware(
14
  CORSMiddleware,
15
  allow_origins=["*"],
 
17
  allow_methods=["*"],
18
  allow_headers=["*"],
19
  )
20
+
21
  print("Initializing backend...")
22
+
23
  GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
24
  MODEL_LOADED = False
25
+
26
  if GEMINI_API_KEY:
27
  try:
28
  genai.configure(api_key=GEMINI_API_KEY)
 
52
  print(f"General configuration error: {e}")
53
  else:
54
  print("Warning: GEMINI_API_KEY environment variable not set. Running in simulation mode.")
55
+
56
  @app.get("/")
57
  def read_root():
58
  return {"status": "online", "engine": "Creative Intelligence Engine", "active": True}
59
+
60
  @app.get("/api/health")
61
  def health_check():
62
  return {
 
65
  "api_key_configured": bool(GEMINI_API_KEY),
66
  "message": "Neural Engine analysis is operational."
67
  }
68
+
69
  prompt_template = """
70
  You are a neuromarketing expert AI analyzing an ad creative image critically with emphasis on copy, CTA, best time and platform etc..
71
  Evaluate this image strictly on these 5 cognitive parameters. Give a score between 0.10 and 0.98.
72
  Also provide a VERY brief 1-sentence analytical reason based exactly on what is visibly in the image.
73
+
74
  The parameters are:
75
  - visual_saliency (How effectively it draws the eye with contrast, colors, shapes)
76
  - cognitive_ease (Clean layout vs clutter. Higher score = easier to process)
77
  - emotional_arousal (Does it trigger a mood via faces, colors, or atmosphere)
78
  - value_recognition (Speed of identifying the core reward/benefit/CTA)
79
  - memory_encoding (Distinctiveness of brand motifs, logos, or striking imagery)
80
+
81
  Return strictly valid JSON containing a single "scores" object, a "reasons" object, and an "insights" array.
82
  Format:
83
  {
 
100
  ]
101
  }
102
  """
103
+
104
  @app.post("/api/analyze")
105
  async def analyze_creative(
106
  creative: UploadFile = File(None),
 
131
  scores = data.get("scores", {})
132
  reasons = data.get("reasons", {})
133
  insights = data.get("insights", ["Analysis completed successfully."])
134
+
135
+ except google_exceptions.ResourceExhausted as e:
136
+ print(f"Quota Exceeded (429): {e}")
137
+ scores = {
138
+ "visual_saliency": 0.40, "cognitive_ease": 0.35,
139
+ "emotional_arousal": 0.30, "value_recognition": 0.40, "memory_encoding": 0.35
140
+ }
141
+ reasons = {k: "Analysis paused due to capacity constraints." for k in scores}
142
+ insights = ["Neural Engine is currently at peak capacity. Analysis is temporarily paused to ensure data fidelity. Please try again in a few moments."]
143
+ source = "Cloud VLM (Quota Reached)"
144
  except Exception as e:
145
+ print(f"API Error during analysis: {e}")
146
  scores = {
147
  "visual_saliency": 0.32, "cognitive_ease": 0.28,
148
  "emotional_arousal": 0.10, "value_recognition": 0.45, "memory_encoding": 0.24
149
  }
150
+ reasons = {k: "Neural processing temporarily restricted." for k in scores}
151
+ insights = ["The Neural Engine encountered an unexpected synchronization error. Please retry the analysis."]
152
+ source = f"HF Space (Sync Error)"
153
  else:
154
  # Deterministic fallback based on file name
155
  seed = name + description
 
171
  }
172
  insights = ["Running in simulation mode. No valid GEMINI_API_KEY provided."]
173
  source = "HF Space (Simulation Fallback)"
174
+
175
  # Calculate timeline metrics from current scores (averaging for consistency)
176
  avg_score = sum(scores.values()) / len(scores) if scores else 0.5
177
  timeline = {
 
181
  }
182
  # Clamp timeline scores to 100
183
  timeline = {k: min(v, 99.0) for k, v in timeline.items()}
184
+
185
  return {
186
  "id": id,
187
  "name": name,