abhidgp1978 commited on
Commit
b09ff95
·
verified ·
1 Parent(s): 4a4de59

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -76
app.py CHANGED
@@ -4,114 +4,115 @@ import gradio as gr
4
  from transformers import pipeline
5
 
6
  # -----------------------------
7
- # Load Hugging Face Models
8
  # -----------------------------
9
- reason_generator = pipeline(
10
- "text-generation",
11
- model="gpt2",
12
- pad_token_id=50256,
13
- max_new_tokens=100
14
- )
15
- classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
16
 
17
  # -----------------------------
18
  # Config
19
  # -----------------------------
20
  CHANNELS = ["TikTok", "Instagram", "YouTube", "LinkedIn", "Facebook"]
21
 
22
- GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
23
- GOOGLE_CX = os.getenv("GOOGLE_CX")
 
24
 
25
  # -----------------------------
26
  # Helper Functions
27
  # -----------------------------
28
- def google_search(query, site_filter=None, num=3, region_code=None):
29
- if not GOOGLE_API_KEY or not GOOGLE_CX:
30
- return ["⚠️ Missing Google API credentials in Hugging Face Secrets"]
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  url = "https://www.googleapis.com/customsearch/v1"
33
  params = {
34
  "q": query,
35
  "key": GOOGLE_API_KEY,
36
  "cx": GOOGLE_CX,
37
- "num": num
38
  }
39
- if region_code:
40
- params["gl"] = region_code
41
-
42
- resp = requests.get(url, params=params)
43
- data = resp.json()
44
-
45
  results = []
46
- if "items" in data:
47
- for item in data["items"]:
48
- link = item.get("link", "")
49
  title = item.get("title", "")
50
- if site_filter and site_filter not in link:
51
- continue
52
- results.append(f"{title} <br> <a href='{link}' target='_blank'>{link}</a>")
53
  else:
54
- results.append("⚠️ No results found <br> URL: ")
55
-
56
- return results[:num]
57
-
58
-
59
- def generate_reason(product_desc, channel_name):
60
- prompt = (
61
- f"Explain in 1-2 sentences why the social media channel '{channel_name}' "
62
- f"is suitable for the product: {product_desc}"
63
- )
64
- output = reason_generator(prompt, max_new_tokens=60, truncation=True)[0]["generated_text"]
65
- reason = output.replace(prompt, "").strip()
66
- if not reason:
67
- reason = f"{channel_name} is suitable for promoting {product_desc}."
68
- return reason
69
-
70
-
71
- def recommend_channels(product_desc, region_code):
72
- result = classifier(product_desc, candidate_labels=CHANNELS)
73
- scores = dict(zip(result["labels"], result["scores"]))
74
-
75
- output = ""
76
- for ch in result["labels"]:
77
- score = scores.get(ch, 0)
78
- reason = generate_reason(product_desc, ch)
79
- output += f"<b>{ch} ({score:.2f})</b> → {reason}<br><br>"
80
-
81
- query = f"top {ch} accounts {product_desc}"
82
- site_filter = ch.lower() + ".com"
83
- search_results = google_search(query, site_filter=site_filter, num=3, region_code=region_code)
84
-
85
- for idx, r in enumerate(search_results, 1):
86
- output += f"{idx}. {r}<br>"
87
- output += "<br>"
88
-
89
  return output
90
 
91
-
92
  # -----------------------------
93
  # Gradio UI
94
  # -----------------------------
95
  with gr.Blocks() as demo:
96
  gr.Markdown("## 🌐 Social Media Channel Recommender AI")
97
- gr.Markdown(
98
- "Enter a brief description of your product. "
99
- "The AI will suggest top social media platforms and real accounts to follow."
100
- )
101
-
102
- inp = gr.Textbox(label="Describe your product", placeholder="e.g., Nail care session for Gen Z")
103
 
104
- region_dropdown = gr.Dropdown(
105
- label="Select Region (optional)",
106
- choices=["", "in", "us", "uk", "ca", "au"],
107
- value="",
108
- info="Optional: Restrict search results to a specific country (ISO code)"
109
- )
110
 
111
- out = gr.HTML(label="Suggested Channels")
112
 
113
  btn = gr.Button("Recommend")
114
- btn.click(recommend_channels, inputs=[inp, region_dropdown], outputs=out)
115
 
116
  if __name__ == "__main__":
117
  demo.launch()
 
4
  from transformers import pipeline
5
 
6
  # -----------------------------
7
+ # Load Hugging Face Model
8
  # -----------------------------
9
+ reason_model = pipeline("text-generation", model="gpt2", tokenizer="gpt2")
 
 
 
 
 
 
10
 
11
  # -----------------------------
12
  # Config
13
  # -----------------------------
14
  CHANNELS = ["TikTok", "Instagram", "YouTube", "LinkedIn", "Facebook"]
15
 
16
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY") # For CSE
17
+ GOOGLE_CX = os.getenv("GOOGLE_CX") # Your custom search engine ID
18
+ YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY") # YouTube Data API Key
19
 
20
  # -----------------------------
21
  # Helper Functions
22
  # -----------------------------
 
 
 
23
 
24
+ def generate_reason(channel_name, product_desc):
25
+ prompt = f"Explain in 1-2 sentences why the social media channel '{channel_name}' is suitable for the product: {product_desc}"
26
+ reason = reason_model(prompt, max_new_tokens=60, do_sample=True)[0]['generated_text']
27
+ # Clean up repetitive prompt
28
+ reason = reason.replace(prompt, "").strip()
29
+ return reason
30
+
31
+ def youtube_search(query, max_results=3):
32
+ if not YOUTUBE_API_KEY:
33
+ return ["⚠️ Missing YouTube API Key"]
34
+ url = "https://www.googleapis.com/youtube/v3/search"
35
+ params = {
36
+ "part": "snippet",
37
+ "q": query,
38
+ "type": "video",
39
+ "maxResults": max_results,
40
+ "key": YOUTUBE_API_KEY
41
+ }
42
+ resp = requests.get(url, params=params).json()
43
+ results = []
44
+ if "items" in resp:
45
+ for item in resp["items"]:
46
+ title = item["snippet"]["title"]
47
+ link = f"https://www.youtube.com/watch?v={item['id']['videoId']}"
48
+ results.append(f"{title} \nURL: {link}")
49
+ else:
50
+ results.append("⚠️ No results found")
51
+ return results
52
+
53
+ def google_cse_search(query, site_filter=None, max_results=3, region=None):
54
+ if not GOOGLE_API_KEY or not GOOGLE_CX:
55
+ return ["⚠️ Missing Google API credentials"]
56
  url = "https://www.googleapis.com/customsearch/v1"
57
  params = {
58
  "q": query,
59
  "key": GOOGLE_API_KEY,
60
  "cx": GOOGLE_CX,
61
+ "num": max_results
62
  }
63
+ if site_filter:
64
+ params["q"] = f"site:{site_filter} {query}"
65
+ if region:
66
+ params["gl"] = region # country code
67
+ resp = requests.get(url, params=params).json()
 
68
  results = []
69
+ if "items" in resp:
70
+ for item in resp["items"]:
 
71
  title = item.get("title", "")
72
+ link = item.get("link", "")
73
+ results.append(f"{title} \nURL: {link}")
 
74
  else:
75
+ results.append("⚠️ No results found")
76
+ return results
77
+
78
+ def recommend_channels(product_desc, region=None):
79
+ output = "Suggested Channels\n\n"
80
+ for ch in CHANNELS:
81
+ reason = generate_reason(ch, product_desc)
82
+ output += f"{ch} → {reason}\n\n"
83
+
84
+ # Fetch results per channel
85
+ if ch == "YouTube":
86
+ results = youtube_search(product_desc)
87
+ else:
88
+ # Map channel names to site domains
89
+ site_map = {
90
+ "TikTok": "tiktok.com",
91
+ "Instagram": "instagram.com",
92
+ "LinkedIn": "linkedin.com",
93
+ "Facebook": "facebook.com"
94
+ }
95
+ results = google_cse_search(product_desc, site_filter=site_map.get(ch), region=region)
96
+
97
+ for idx, r in enumerate(results, 1):
98
+ output += f"{idx}. {r}\n"
99
+ output += "\n"
 
 
 
 
 
 
 
 
 
 
100
  return output
101
 
 
102
  # -----------------------------
103
  # Gradio UI
104
  # -----------------------------
105
  with gr.Blocks() as demo:
106
  gr.Markdown("## 🌐 Social Media Channel Recommender AI")
107
+ gr.Markdown("Enter a short description of your product or campaign. The AI will suggest top social media platforms and accounts to follow.")
 
 
 
 
 
108
 
109
+ inp = gr.Textbox(label="Describe your product", placeholder="e.g., Vintage car exhibition")
110
+ region_input = gr.Textbox(label="Region (optional, ISO country code e.g., 'in')", placeholder="Leave blank for global")
 
 
 
 
111
 
112
+ out = gr.Markdown(label="Suggested Channels")
113
 
114
  btn = gr.Button("Recommend")
115
+ btn.click(recommend_channels, inputs=[inp, region_input], outputs=out)
116
 
117
  if __name__ == "__main__":
118
  demo.launch()