aromidvar commited on
Commit
6d5ecc7
·
verified ·
1 Parent(s): ce38bb4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -116
app.py CHANGED
@@ -1,125 +1,95 @@
1
  import os
2
- import random
3
  import logging
4
- from datetime import datetime, timedelta
5
- from pathlib import Path
6
- import asyncio
7
  import requests
8
  import gradio as gr
 
9
  from dotenv import load_dotenv
10
 
11
  # Load environment variables
12
  load_dotenv()
13
 
14
- # Configure logging
15
- logging.basicConfig(
16
- level=logging.INFO,
17
- format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
18
- handlers=[logging.FileHandler("app.log"), logging.StreamHandler()],
19
- )
20
- logger = logging.getLogger("DashboardBot")
21
-
22
- # Proxy Manager
23
- class ProxyManager:
24
- def __init__(self, proxy_list=None):
25
- self.proxy_list = proxy_list or []
26
- self.current_proxy = None
27
- self.last_rotation = datetime.now()
28
- self.rotation_interval = timedelta(minutes=30)
29
-
30
- def rotate(self):
31
- if not self.proxy_list:
32
- return None
33
- self.current_proxy = random.choice(self.proxy_list)
34
- self.last_rotation = datetime.now()
35
- return {"http": self.current_proxy, "https": self.current_proxy}
36
-
37
- proxy_manager = ProxyManager(proxy_list=os.getenv("PROXY_LIST", "").split(","))
38
-
39
- # Content Generator
40
- class ContentGenerator:
41
- def __init__(self, api_key):
42
- self.api_key = api_key
43
-
44
- async def generate_content(self, topic, audience, tone):
45
- proxy = proxy_manager.rotate()
46
- prompt = (
47
- f"Generate 3 engaging content ideas for '{topic}'. "
48
- f"Audience: {audience}, Tone: {tone}."
49
- )
50
- try:
51
- response = requests.post(
52
- "https://openrouter.ai/api/v1/chat/completions",
53
- headers={"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"},
54
- json={
55
- "model": "openai/gpt-4o-2024-11-20",
56
- "messages": [{"role": "user", "content": prompt}],
57
- "max_tokens": 1500,
58
- },
59
- proxies=proxy,
60
- timeout=30,
61
- )
62
- response.raise_for_status()
63
- data = response.json()
64
- return data["choices"][0]["message"]["content"]
65
- except Exception as e:
66
- logger.error(f"Error generating content: {e}")
67
- return "Error generating content."
68
-
69
- content_generator = ContentGenerator(api_key=os.getenv("OPENROUTER_API_KEY"))
70
-
71
- # Zapier Integration
72
- class ZapierIntegration:
73
- def __init__(self, webhook_url):
74
- self.webhook_url = webhook_url
75
-
76
- async def notify_zapier(self, content):
77
- try:
78
- payload = {"content": content, "timestamp": datetime.now().isoformat()}
79
- response = requests.post(self.webhook_url, json=payload, timeout=10)
80
- response.raise_for_status()
81
- return {"status": "success", "message": "Notified Zapier"}
82
- except Exception as e:
83
- logger.error(f"Error notifying Zapier: {e}")
84
- return {"status": "error", "message": str(e)}
85
-
86
- zapier = ZapierIntegration(webhook_url=os.getenv("ZAPIER_WEBHOOK_URL"))
87
-
88
- # Gradio Interface
89
- def create_dashboard():
90
- with gr.Blocks(title="Integrated Dashboard Bot") as dashboard:
91
- gr.Markdown("# Content Automation Dashboard")
92
-
93
- # Content Generation
94
- topic = gr.Textbox(label="Content Topic", placeholder="Enter topic")
95
- audience = gr.Dropdown(
96
- label="Audience", choices=["General", "Professional", "Youth"], value="General"
97
- )
98
- tone = gr.Dropdown(
99
- label="Tone", choices=["Casual", "Professional", "Luxury"], value="Professional"
100
- )
101
- generate_btn = gr.Button("Generate Content")
102
- content_output = gr.Textbox(label="Generated Content", interactive=False)
103
-
104
- # Zapier
105
- zapier_btn = gr.Button("Send to Zapier")
106
- zapier_status = gr.Textbox(label="Zapier Status", interactive=False)
107
-
108
- async def handle_generate(topic, audience, tone):
109
- return await content_generator.generate_content(topic, audience, tone)
110
-
111
- async def handle_zapier(content):
112
- if not content:
113
- return "No content to send to Zapier."
114
- result = await zapier.notify_zapier(content)
115
- return result["message"]
116
-
117
- generate_btn.click(handle_generate, inputs=[topic, audience, tone], outputs=content_output)
118
- zapier_btn.click(handle_zapier, inputs=[content_output], outputs=zapier_status)
119
-
120
- return dashboard
121
-
122
-
123
- if __name__ == "__main__":
124
- dashboard = create_dashboard()
125
- dashboard.launch(server_name="0.0.0.0", server_port=7860, share=True)
 
1
  import os
 
2
  import logging
 
 
 
3
  import requests
4
  import gradio as gr
5
+ from sentence_transformers import SentenceTransformer, util
6
  from dotenv import load_dotenv
7
 
8
  # Load environment variables
9
  load_dotenv()
10
 
11
+ # Logging configuration
12
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(message)s")
13
+
14
+ # HuggingFace model for semantic similarity
15
+ model = SentenceTransformer("all-MiniLM-L6-v2")
16
+
17
+ # API Keys and Webhook URLs
18
+ PHANTOMBUSTER_API_KEY = os.getenv("PHANTOMBUSTER_API_KEY")
19
+ PHANTOMBUSTER_AGENT_ID = os.getenv("PHANTOMBUSTER_AGENT_ID")
20
+ MAKE_WEBHOOK_URL = os.getenv("MAKE_WEBHOOK_URL")
21
+
22
+ # Functions
23
+ def fetch_phantombuster_data():
24
+ """Fetch hashtags from PhantomBuster output."""
25
+ url = f"https://phantombuster.com/api/v2/agents/{PHANTOMBUSTER_AGENT_ID}/output"
26
+ headers = {"X-Phantombuster-Key-1": PHANTOMBUSTER_API_KEY}
27
+ try:
28
+ response = requests.get(url, headers=headers)
29
+ response.raise_for_status()
30
+ data = response.json()
31
+ hashtags = []
32
+ for post in data.get("data", []):
33
+ if "caption" in post:
34
+ hashtags.extend([tag for tag in post["caption"].split() if tag.startswith("#")])
35
+ return list(set(hashtags)) # Remove duplicates
36
+ except Exception as e:
37
+ logging.error(f"Error fetching PhantomBuster data: {e}")
38
+ return ["Error fetching hashtags."]
39
+
40
+ def filter_relevant_hashtags(hashtags, keywords):
41
+ """Filter hashtags based on semantic relevance."""
42
+ hashtags_embeddings = model.encode(hashtags, convert_to_tensor=True)
43
+ keywords_embedding = model.encode(keywords, convert_to_tensor=True)
44
+ cosine_scores = util.pytorch_cos_sim(hashtags_embeddings, keywords_embedding)
45
+ relevant = [
46
+ hashtags[i]
47
+ for i in range(len(hashtags))
48
+ if cosine_scores[i].max() > 0.5
49
+ ]
50
+ return relevant
51
+
52
+ def send_to_make_webhook(payload):
53
+ """Send data to Make.com webhook."""
54
+ try:
55
+ response = requests.post(MAKE_WEBHOOK_URL, json=payload, timeout=10)
56
+ response.raise_for_status()
57
+ return "Data sent successfully to Make.com!"
58
+ except Exception as e:
59
+ logging.error(f"Error sending to Make.com: {e}")
60
+ return "Error sending data to Make.com."
61
+
62
+ # Gradio Dashboard
63
+ with gr.Blocks() as dashboard:
64
+ gr.Markdown("# Instagram Hashtag Monitoring Dashboard")
65
+
66
+ # Hashtag Extraction
67
+ competitor_username = gr.Textbox(label="Competitor Username", placeholder="e.g., competitor1")
68
+ extract_btn = gr.Button("Extract Hashtags")
69
+ extracted_hashtags = gr.Textbox(label="Extracted Hashtags", interactive=False)
70
+
71
+ # Hashtag Filtering
72
+ niche_keywords = gr.Textbox(label="Niche Keywords", placeholder="e.g., sustainability, eco-friendly")
73
+ filter_btn = gr.Button("Filter Relevant Hashtags")
74
+ relevant_hashtags = gr.Textbox(label="Relevant Hashtags", interactive=False)
75
+
76
+ # Send to Make.com
77
+ send_btn = gr.Button("Send to Make.com")
78
+ make_status = gr.Textbox(label="Webhook Status", interactive=False)
79
+
80
+ # Handlers
81
+ def handle_extract(username):
82
+ return fetch_phantombuster_data()
83
+
84
+ def handle_filter(hashtags, keywords):
85
+ return filter_relevant_hashtags(hashtags.split(","), keywords.split(","))
86
+
87
+ def handle_send_to_make(hashtags):
88
+ payload = {"hashtags": hashtags.split(","), "action": "monitor"}
89
+ return send_to_make_webhook(payload)
90
+
91
+ extract_btn.click(handle_extract, inputs=[competitor_username], outputs=[extracted_hashtags])
92
+ filter_btn.click(handle_filter, inputs=[extracted_hashtags, niche_keywords], outputs=[relevant_hashtags])
93
+ send_btn.click(handle_send_to_make, inputs=[relevant_hashtags], outputs=[make_status])
94
+
95
+ dashboard.launch(server_name="0.0.0.0", server_port=7860, share=True)