Spaces:
Sleeping
Sleeping
Update app.py
Browse files5 unmodified lines67891011121314151 unmodified line17181920212223242526272823 unmodified lines52535455565758596061622 unmodified lines6566676869707172737475767778798081828316 unmodified lines10010110210310410510624 unmodified lines13113213313413513613713813914014114214314414514614714814912712812915015115215315415515 unmodified lines1711721731741751761773 unmodified lines1811821831841851861875 unmodified linesimport ioimport jsonimport hashlibfrom google.api_core import exceptions as google_exceptions
app = FastAPI()
app.add_middleware( CORSMiddleware, allow_origins=["*"], 1 unmodified line allow_methods=["*"], allow_headers=["*"],)
print("Initializing backend...")
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")MODEL_LOADED = False
if GEMINI_API_KEY: try: genai.configure(api_key=GEMINI_API_KEY)23 unmodified lines print(f"General configuration error: {e}")else: print("Warning: GEMINI_API_KEY environment variable not set. Running in simulation mode.")
@app.get("/")def read_root(): return {"status": "online", "engine": "Creative Intelligence Engine", "active": True}
@app.get("/api/health")def health_check(): return {2 unmodified lines "api_key_configured": bool(GEMINI_API_KEY), "message": "Neural Engine analysis is operational." }
prompt_template = """You are a neuromarketing expert AI analyzing an ad creative image critically with emphasis on copy, CTA, best time and platform etc..Evaluate this image strictly on these 5 cognitive parameters. Give a score between 0.10 and 0.98.Also provide a VERY brief 1-sentence analytical reason based exactly on what is visibly in the image.
The parameters are:- visual_saliency (How effectively it draws the eye with contrast, colors, shapes)- cognitive_ease (Clean layout vs clutter. Higher score = easier to process)- emotional_arousal (Does it trigger a mood via faces, colors, or atmosphere)- value_recognition (Speed of identifying the core reward/benefit/CTA)- memory_encoding (Distinctiveness of brand motifs, logos, or striking imagery)
Return strictly valid JSON containing a single "scores" object, a "reasons" object, and an "insights" array.Format:{16 unmodified lines ]}"""
@app.post("/api/analyze")async def analyze_creative( creative: UploadFile = File(None),24 unmodified lines scores = data.get("scores", {}) reasons = data.get("reasons", {}) insights = data.get("insights", ["Analysis completed successfully."])
except google_exceptions.ResourceExhausted as e: print(f"Quota Exceeded (429): {e}") scores = { "visual_saliency": 0.40, "cognitive_ease": 0.35, "emotional_arousal": 0.30, "value_recognition": 0.40, "memory_encoding": 0.35 } reasons = {k: "Analysis paused due to capacity constraints." for k in scores} insights = ["Neural Engine is currently at peak capacity. Analysis is temporarily paused to ensure data fidelity. Please try again in a few moments."] source = "Cloud VLM (Quota Reached)" except Exception as e: print(f"API Error during analysis: {e}") scores = { "visual_saliency": 0.32, "cognitive_ease": 0.28, "emotional_arousal": 0.10, "value_recognition": 0.45, "memory_encoding": 0.24 } reasons = {k: f"Error: {str(e)[:50]}..." for k in scores} insights = [f"API Error: {str(e)}"] source = f"HF Space (Error)" reasons = {k: "Neural processing temporarily restricted." for k in scores} insights = ["The Neural Engine encountered an unexpected synchronization error. Please retry the analysis."] source = f"HF Space (Sync Error)" else: # Deterministic fallback based on file name seed = name + description15 unmodified lines } insights = ["Running in simulation mode. No valid GEMINI_API_KEY provided."] source = "HF Space (Simulation Fallback)"
# Calculate timeline metrics from current scores (averaging for consistency) avg_score = sum(scores.values()) / len(scores) if scores else 0.5 timeline = {3 unmodified lines } # Clamp timeline scores to 100 timeline = {k: min(v, 99.0) for k, v in timeline.items()}
return { "id": id, "name": name,app.py+28-3