SocialChannelAI / app.py
abhidgp1978's picture
Update app.py
3e8ca16 verified
Raw History Blame Contribute Delete
5.58 kB
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