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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -45
app.py CHANGED
@@ -1,51 +1,43 @@
1
  import os
2
  import requests
3
  import gradio as gr
4
- from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
5
 
6
  # -----------------------------
7
- # Load AI Model for Reason Generation
8
  # -----------------------------
9
- model_name = "google/flan-t5-small"
10
- tokenizer = AutoTokenizer.from_pretrained(model_name)
11
- model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
12
-
13
- def generate_reason(channel, product_desc):
14
- prompt = f"Explain why the social media channel '{channel}' is suitable for promoting: {product_desc} in 1-2 sentences."
15
- inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=128)
16
- outputs = model.generate(
17
- **inputs,
18
- max_new_tokens=100,
19
- temperature=0.7,
20
- do_sample=True
21
- )
22
- reason = tokenizer.decode(outputs[0], skip_special_tokens=True)
23
- return reason
24
 
25
  # -----------------------------
26
  # Config
27
  # -----------------------------
28
  CHANNELS = ["TikTok", "Instagram", "YouTube", "LinkedIn", "Facebook"]
 
29
  GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
30
  GOOGLE_CX = os.getenv("GOOGLE_CX")
31
 
32
  # -----------------------------
33
  # Helper Functions
34
  # -----------------------------
 
 
 
 
 
35
  def google_search(query, num=3, region=""):
36
- """Search Google using Custom Search API."""
37
  if not GOOGLE_API_KEY or not GOOGLE_CX:
38
  return [("⚠️ Missing Google API credentials", "")]
39
 
40
- url = "https://www.googleapis.com/customsearch/v1"
41
  params = {
42
- "q": query,
43
  "key": GOOGLE_API_KEY,
44
  "cx": GOOGLE_CX,
45
  "num": num,
46
- "gl": region, # optional region
 
47
  }
48
- resp = requests.get(url, params=params)
49
  data = resp.json()
50
 
51
  results = []
@@ -60,25 +52,22 @@ def google_search(query, num=3, region=""):
60
  return results[:num]
61
 
62
  def recommend_channels(product_desc, region=""):
63
- output = "## Suggested Channels\n\n"
 
 
64
 
65
- # Generate AI score per channel (dummy ranking for demonstration)
66
- # You can integrate classifier if needed
67
- scores = {ch: 1.0/len(CHANNELS) for ch in CHANNELS} # equal scores for simplicity
68
 
69
  for ch in CHANNELS:
70
  score = scores.get(ch, 0)
71
- reason = generate_reason(ch, product_desc)
72
- output += f"### {ch} ({score:.2f}) → {reason}\n\n"
73
-
74
- # Google search per channel
75
- query = f"site:{ch.lower()}.com {product_desc}"
76
- results = google_search(query, num=3, region=region)
77
- for idx, (title, link) in enumerate(results, 1):
78
- if link:
79
- output += f"{idx}. {title}\nURL: {link}\n"
80
- else:
81
- output += f"{idx}. {title}\n"
82
  output += "\n"
83
 
84
  return output
@@ -88,19 +77,16 @@ def recommend_channels(product_desc, region=""):
88
  # -----------------------------
89
  with gr.Blocks() as demo:
90
  gr.Markdown("## 🌐 Social Media Channel Recommender AI")
91
- gr.Markdown(
92
- "Enter a short description of your product or campaign. "
93
- "The AI will suggest top social media platforms and real accounts to follow."
94
- )
95
 
96
  inp = gr.Textbox(label="Describe your product", placeholder="e.g., Nail care session for Gen Z")
97
  region_dropdown = gr.Dropdown(
98
  label="Select Region (optional)",
99
- choices=["", "us", "in", "uk", "ca", "au"],
100
- value="in",
101
- info="Region code for Google search (ISO country code)"
102
  )
103
- out = gr.Markdown(label="Suggested Channels")
104
 
105
  btn = gr.Button("Recommend")
106
  btn.click(recommend_channels, inputs=[inp, region_dropdown], outputs=out)
 
1
  import os
2
  import requests
3
  import gradio as gr
4
+ from transformers import pipeline
5
 
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
14
  # -----------------------------
15
  CHANNELS = ["TikTok", "Instagram", "YouTube", "LinkedIn", "Facebook"]
16
+
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 = []
 
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
  # -----------------------------
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)