import openai import os import gradio as gr from dotenv import load_dotenv import io from PIL import Image import pytesseract # Import Tesseract OCR # Load environment variables (where your OpenAI key will be stored) load_dotenv() # Load the OpenAI API key from environment variables and strip any trailing newlines or spaces openai.api_key = os.getenv("OPENAI_API_KEY").strip() # Function to analyze the ad and generate marketing personas + scoring def analyze_ad(image): # Extract text from the image using Tesseract OCR ad_copy = pytesseract.image_to_string(image) if not ad_copy.strip(): # Check if OCR extracted any text return "No text was detected in the image. Please upload a clearer ad image." # Prompt for the marketing persona and scoring rubric prompt = f""" Analyze the following ad copy and generate a marketing persona. Then, provide a score (out of 10) for each of the following: 1. Relevance to Target Audience: Is the ad appealing to the intended demographic? 2. Emotional Engagement: Does the ad evoke the right emotional response? 3. Brand Consistency: Does the ad align with the brand’s voice and values? 4. Creativity: How unique or innovative is the ad's design and text approach? 5. Persuasiveness: Does the ad motivate action, such as clicking or purchasing? Ad Copy: {ad_copy} Provide the persona description and the scores in table form with a final score. """ # Send the prompt to GPT-4o-mini for analysis response = openai.ChatCompletion.create( model="gpt-4o-mini", # Use the gpt-4o-mini model as requested messages=[ {"role": "system", "content": "You are a marketing expert analyzing an advertisement."}, {"role": "user", "content": prompt} ], temperature=0.7, max_tokens=400 ) # Extract the response text from the API output result = response['choices'][0]['message']['content'] # Return the result for display return result # Function to process the image and run the analysis def upload_and_analyze(image): # Pass the uploaded image to the analyze_ad function result = analyze_ad(image) return result # Gradio interface for Hugging Face deployment iface = gr.Interface( fn=upload_and_analyze, inputs=gr.Image(type="pil", label="Upload Advertisement Image"), # Use type="pil" for the image input outputs=gr.Textbox(label="Marketing Persona and Ad Analysis"), title="Advertisement Persona and Scoring Analyzer", description="Upload an advertisement image, and the app will generate marketing personas and evaluate the ad based on Relevance, Emotional Engagement, Brand Consistency, Creativity, and Persuasiveness." ) # Launch the app if __name__ == "__main__": iface.launch()