Spaces:
Runtime error
Runtime error
File size: 5,581 Bytes
9ee7df3 b73d967 5766b79 9b7a36c 5766b79 9b7a36c 5766b79 9b7a36c 5766b79 9b7a36c 367845b 9b7a36c 6b21ea3 5766b79 6b21ea3 5766b79 6b21ea3 5766b79 9b7a36c 5766b79 8cb30f4 9b7a36c fc2b131 e773f66 fc2b131 6b21ea3 93178f2 5766b79 6b21ea3 5766b79 6b21ea3 5766b79 8cb30f4 5766b79 9b7a36c 5766b79 9b7a36c 5766b79 367845b 5766b79 9b7a36c 5766b79 6b21ea3 5766b79 9b7a36c 5766b79 6b21ea3 5766b79 6b21ea3 8cb30f4 6b21ea3 5766b79 8cb30f4 9b7a36c 5766b79 6b21ea3 5766b79 9b7a36c 6b21ea3 5766b79 9b7a36c 5766b79 6b21ea3 5766b79 6b21ea3 9b7a36c 6b21ea3 5766b79 9b7a36c 5766b79 b09ff95 5766b79 3e8ca16 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | import os
import requests
import gradio as gr
from transformers import pipeline
# -----------------------------
# AI Models for Scoring and Reasoning
# -----------------------------
# Gradio will download these models the first time you run the app.
# The zero-shot classifier scores the relevance of each social channel.
print("Loading zero-shot classification model...")
try:
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
except Exception as e:
print(f"Error loading classifier model: {e}")
classifier = None
# The text-to-text model generates a brief marketing reason for each channel.
print("Loading text generation model...")
try:
reasoning_model = pipeline("text2text-generation", model="google/flan-t5-base")
except Exception as e:
print(f"Error loading reasoning model: {e}")
reasoning_model = None
# -----------------------------
# Configuration and API Keys
# -----------------------------
# List of social media channels to be considered for recommendation.
CHANNELS = ["Instagram", "YouTube", "Facebook", "LinkedIn"]
# IMPORTANT: API keys are fetched from environment variables.
# This is the recommended way to handle secrets on Hugging Face Spaces.
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
GOOGLE_CX = os.getenv("GOOGLE_CX")
YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY")
SERPAPI_KEY = os.getenv("SERPAPI_KEY")
# -----------------------------
# AI Reason Generator (Platform-specific)
# -----------------------------
def generate_reason(product_desc, channel):
"""
Generates a brief marketing reason for a given channel based on the product description.
"""
if not reasoning_model:
return "⚠️ Reasoning model not loaded. Cannot generate a reason."
# New, more descriptive prompt to avoid repetition and provide better guidance.
prompt = f"""
As a social media marketing expert, provide a concise, 2-3 sentence marketing strategy for a product launch on {channel}.
Product: {product_desc}
Include a distinct, actionable recommendation for each platform.
Focus on:
- Target audience on {channel}
- Recommended content format (e.g., Reels, posts, video reviews)
- Influencer collaboration or community engagement strategies
Do NOT repeat the product name or channel name in the generated text.
"""
try:
out = reasoning_model(prompt, max_new_tokens=120, truncation=True)
return out[0]["generated_text"].strip()
except Exception as e:
return f"⚠️ AI error: {str(e)}"
# -----------------------------
# Zero-shot Scoring
# -----------------------------
def score_channels(product_desc):
"""
Uses a zero-shot classifier to score how relevant each channel is to the product.
If the classifier fails, it provides a random fallback score.
"""
if not classifier:
import random
return {ch: round(random.uniform(0.1, 0.5), 2) for ch in CHANNELS}
try:
result = classifier(product_desc, candidate_labels=CHANNELS)
scores = dict(zip(result["labels"], result["scores"]))
return {ch: round(scores.get(ch, 0), 2) for ch in CHANNELS}
except Exception as e:
print(f"Classifier error: {e}. Falling back to random scores.")
import random
return {ch: round(random.uniform(0.1, 0.5), 2) for ch in CHANNELS}
# -----------------------------
# Search Functions (Top influencers/trending posts)
# -----------------------------
def google_search(query, site=None, num=3, region_code=None):
"""Performs a Google search using the Custom Search API."""
if not GOOGLE_API_KEY or not GOOGLE_CX:
return []
url = "https://www.googleapis.com/customsearch/v1"
params = {"q": query, "key": GOOGLE_API_KEY, "cx": GOOGLE_CX, "num": num}
if region_code and region_code.lower() != "none":
params["gl"] = region_code.lower()
try:
resp = requests.get(url, params=params, timeout=10)
data = resp.json()
results = []
if "items" in data:
for item in data["items"][:num]:
link = item.get("link", "")
title = item.get("title", "")
if site and site not in link:
continue
results.append((title, link))
return results
except Exception as e:
print(f"Google Search error: {e}")
return []
def serpapi_search(query, site=None, num=3, region_code=None):
"""Performs a search using SerpAPI as a fallback."""
if not SERPAPI_KEY:
return []
url = "https://serpapi.com/search"
params = {"engine": "google", "q": f"site:{site} {query}" if site else query, "api_key": SERPAPI_KEY, "num": num}
if region_code and region_code.lower() != "none":
params["gl"] = region_code.lower()
params["hl"] = "en"
try:
resp = requests.get(url, params=params, timeout=10)
data = resp.json()
results = []
if "organic_results" in data:
for item in data["organic_results"][:num]:
results.append((item.get("title", "No title"), item.get("link", "#")))
return results
except Exception as e:
print(f"SerpAPI Search error: {e}")
return []
def youtube_search(query, num=3, region_code=None):
"""Performs a search on YouTube using the YouTube Data API."""
if not YOUTUBE_API_KEY:
return []
url = "https://www.googleapis.com/youtube/v3/search"
params = {"part": "snippet", "q": query, "type": "video", "maxResults": num, "key": YOUTUBE_API_KEY}
if region_code
|