abhidgp1978 commited on
Commit
e3584fe
·
verified ·
1 Parent(s): f10af90

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -35
app.py CHANGED
@@ -6,8 +6,8 @@ from transformers import pipeline
6
  # -----------------------------
7
  # Load Hugging Face Model
8
  # -----------------------------
9
- classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
10
- reason_generator = pipeline("text-generation", model="gpt2") # AI-generated reason
11
 
12
  # -----------------------------
13
  # Config
@@ -17,57 +17,67 @@ CHANNELS = ["TikTok", "Instagram", "YouTube", "LinkedIn", "Facebook"]
17
  GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
18
  GOOGLE_CX = os.getenv("GOOGLE_CX")
19
 
 
 
 
20
  # -----------------------------
21
  # Helper Functions
22
  # -----------------------------
23
- def generate_reason(product_desc, channel):
24
- prompt = f"Explain in 1-2 sentences why the social media channel '{channel}' is suitable for the product: {product_desc}"
25
- out = reason_generator(prompt, max_new_tokens=60, truncation=True)
26
- return out[0]['generated_text'].strip()
27
-
28
- def google_search(query, num=3, region=""):
29
  if not GOOGLE_API_KEY or not GOOGLE_CX:
30
- return [("⚠️ Missing Google API credentials", "")]
31
 
 
 
 
 
32
  params = {
33
- "q": query + (f" {region}" if region else ""),
34
  "key": GOOGLE_API_KEY,
35
  "cx": GOOGLE_CX,
36
  "num": num,
37
- "gl": region if region else "",
38
- "cr": f"country{region.upper()}" if region else "",
39
  }
40
- resp = requests.get("https://www.googleapis.com/customsearch/v1", params=params)
 
 
 
 
 
 
41
  data = resp.json()
42
 
43
  results = []
44
  if "items" in data:
45
  for item in data["items"]:
46
- title = item.get("title", "No title")
47
  link = item.get("link", "")
48
- results.append((title, link))
49
  else:
50
- results.append(("⚠️ No results found", ""))
51
 
52
  return results[:num]
53
 
54
- def recommend_channels(product_desc, region=""):
55
- # Zero-shot classification to rank channels
56
- result = classifier(product_desc, candidate_labels=CHANNELS)
57
- scores = dict(zip(result["labels"], result["scores"]))
 
 
 
58
 
59
- output = "Suggested Channels\n\n"
 
60
 
61
  for ch in CHANNELS:
62
- score = scores.get(ch, 0)
63
- reason = generate_reason(product_desc, ch)
64
- output += f"{ch} ({score:.2f}) → {reason}\n\n"
65
-
66
- query = f"site:{ch.lower()}.com top {ch} accounts {product_desc}"
67
- search_results = google_search(query, num=3, region=region)
68
-
69
- for idx, (title, link) in enumerate(search_results, 1):
70
- output += f"{idx}. {title}\n URL: {link}\n"
71
  output += "\n"
72
 
73
  return output
@@ -77,16 +87,21 @@ def recommend_channels(product_desc, region=""):
77
  # -----------------------------
78
  with gr.Blocks() as demo:
79
  gr.Markdown("## 🌐 Social Media Channel Recommender AI")
80
- gr.Markdown("Enter a short description of your product or campaign. The AI will suggest top social media platforms and real accounts to follow.")
 
 
 
81
 
82
  inp = gr.Textbox(label="Describe your product", placeholder="e.g., Nail care session for Gen Z")
 
83
  region_dropdown = gr.Dropdown(
84
  label="Select Region (optional)",
85
- choices=["", "in", "us", "gb", "ca", "au", "sg"],
86
- value="",
87
- info="Select ISO country code (e.g., in for India, us for USA). Leave blank for global results."
88
  )
89
- out = gr.Textbox(label="Suggested Channels", lines=25)
 
90
 
91
  btn = gr.Button("Recommend")
92
  btn.click(recommend_channels, inputs=[inp, region_dropdown], outputs=out)
 
6
  # -----------------------------
7
  # Load Hugging Face Model
8
  # -----------------------------
9
+ # AI model for generating reason for choosing each channel
10
+ reason_generator = pipeline("text-generation", model="gpt2")
11
 
12
  # -----------------------------
13
  # Config
 
17
  GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
18
  GOOGLE_CX = os.getenv("GOOGLE_CX")
19
 
20
+ # Default region
21
+ DEFAULT_REGION = "world" # Can be overridden via dropdown
22
+
23
  # -----------------------------
24
  # Helper Functions
25
  # -----------------------------
26
+ def google_search(query, site_filter=None, num=3, region_code=None):
 
 
 
 
 
27
  if not GOOGLE_API_KEY or not GOOGLE_CX:
28
+ return ["⚠️ Missing Google API credentials in Hugging Face Secrets"]
29
 
30
+ # Build query with site filter
31
+ full_query = f"site:{site_filter} {query}" if site_filter else query
32
+
33
+ url = "https://www.googleapis.com/customsearch/v1"
34
  params = {
35
+ "q": full_query,
36
  "key": GOOGLE_API_KEY,
37
  "cx": GOOGLE_CX,
38
  "num": num,
 
 
39
  }
40
+
41
+ # Apply region hints
42
+ if region_code:
43
+ params["gl"] = region_code # country code for ranking
44
+ params["cr"] = f"country{region_code.upper()}" # restrict country
45
+
46
+ resp = requests.get(url, params=params)
47
  data = resp.json()
48
 
49
  results = []
50
  if "items" in data:
51
  for item in data["items"]:
52
+ title = item.get("title", "").replace("\n", " ").strip()
53
  link = item.get("link", "")
54
+ results.append(f"{title}\nURL: {link}")
55
  else:
56
+ results.append(f"⚠️ No results found")
57
 
58
  return results[:num]
59
 
60
+ def generate_reason(channel, product_desc):
61
+ prompt = f"Explain in 1-2 sentences why the social media channel '{channel}' is suitable for the product: {product_desc}"
62
+ generated = reason_generator(prompt, max_length=60, num_return_sequences=1, truncation=True)
63
+ text = generated[0]['generated_text'].replace(prompt, '').strip()
64
+ if not text:
65
+ text = f"{channel} is a suitable social media channel for {product_desc}."
66
+ return text
67
 
68
+ def recommend_channels(product_desc, region_code=DEFAULT_REGION):
69
+ output = "## Suggested Channels\n\n"
70
 
71
  for ch in CHANNELS:
72
+ # Generate AI reason
73
+ reason = generate_reason(ch, product_desc)
74
+ output += f"**{ch}** → {reason}\n\n"
75
+
76
+ # Google search per channel
77
+ search_results = google_search(product_desc, site_filter=ch.lower()+".com", num=3, region_code=region_code)
78
+ for idx, r in enumerate(search_results, 1):
79
+ # Separate each result
80
+ output += f"{idx}. {r}\n"
81
  output += "\n"
82
 
83
  return output
 
87
  # -----------------------------
88
  with gr.Blocks() as demo:
89
  gr.Markdown("## 🌐 Social Media Channel Recommender AI")
90
+ gr.Markdown(
91
+ "Enter a short description of your product or campaign. "
92
+ "The AI will suggest top social media platforms and real accounts to follow."
93
+ )
94
 
95
  inp = gr.Textbox(label="Describe your product", placeholder="e.g., Nail care session for Gen Z")
96
+
97
  region_dropdown = gr.Dropdown(
98
  label="Select Region (optional)",
99
+ choices=["world","in","us","gb","ca","au"],
100
+ value="world",
101
+ info="ISO country code for Google search. 'world' = global results"
102
  )
103
+
104
+ out = gr.Markdown(label="Suggested Channels")
105
 
106
  btn = gr.Button("Recommend")
107
  btn.click(recommend_channels, inputs=[inp, region_dropdown], outputs=out)