aromidvar commited on
Commit
bcbbf40
·
verified ·
1 Parent(s): 73c48c0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -87
app.py CHANGED
@@ -1,127 +1,118 @@
1
- # app.py (Gradio GPT Newsletter with Mautic Integration)
2
  import gradio as gr
3
- import openai
4
  import os
5
- import requests
6
  import re
 
7
  from dotenv import load_dotenv
8
  from openai import OpenAI
9
 
10
- # Load secrets from .env
11
  load_dotenv()
12
- openai.api_key = os.getenv("OPENAI_API_KEY")
 
 
13
  MAUTIC_BASE_URL = os.getenv("MAUTIC_BASE_URL")
14
  MAUTIC_USERNAME = os.getenv("MAUTIC_USERNAME")
15
  MAUTIC_PASSWORD = os.getenv("MAUTIC_PASSWORD")
16
 
 
 
 
 
 
 
 
 
 
17
  PROMPTS = {
18
- "Law": "Generate a UK cybersecurity insight for professionals in the legal sector.",
19
- "HR": "Generate a UK cybersecurity update for HR professionals.",
20
- "Marketing": "Generate a UK cybersecurity tip for marketing professionals.",
21
- "General": "Generate a brief UK-relevant cybersecurity insight for business users."
22
  }
23
 
 
 
24
  def moderate_content(text):
25
- spam_keywords = ["free money", "urgent click", "buy now", "no cost"]
26
- for keyword in spam_keywords:
27
- if re.search(keyword, text, re.IGNORECASE):
28
- return False
29
- return True
30
 
31
- def send_to_mautic(name, email):
32
  try:
33
- url = f"{MAUTIC_BASE_URL}/api/contacts/new"
34
- data = {
35
  "firstname": name,
36
  "email": email,
37
- "tags": "GPT Generated"
 
 
38
  }
39
- response = requests.post(url, auth=(MAUTIC_USERNAME, MAUTIC_PASSWORD), data=data)
40
- return response.status_code == 200
 
 
 
 
 
 
 
41
  except Exception as e:
42
- return False
43
 
44
-
45
- client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
46
  def generate_insight(name, email, sector, tone, temperature):
47
- base_prompt = PROMPTS.get(sector, PROMPTS["General"])
48
- tone_injection = f" The tone should be {tone.lower()} and professional."
49
- full_prompt = base_prompt + tone_injection
50
 
51
  try:
52
  response = client.chat.completions.create(
53
  model="gpt-4",
54
  messages=[
55
- {"role": "system", "content": "You are a UK-based cybersecurity assistant."},
56
  {"role": "user", "content": full_prompt}
57
  ],
58
  temperature=temperature,
59
  max_tokens=300
60
  )
61
-
62
- # This is the correct way to access the message content
63
  insight = response.choices[0].message.content.strip()
64
 
65
  if not moderate_content(insight):
66
- return "<p style='color:red;'>Insight flagged as potentially spammy. Please regenerate or adjust tone/temperature.</p>"
67
-
68
- send_to_mautic(name, email)
69
-
70
- html_template = f"""
71
- <html>
72
- <body style='font-family:Arial; color:#333;'>
73
- <div style='max-width:600px; margin:auto; background:#f9f9f9; padding:20px; border-radius:8px;'>
74
- <h2 style='background:#004080; color:white; padding:10px;'>Cyber Insight Briefing - {sector}</h2>
75
- <p>Hello {name},</p>
76
- <p>Here are the latest cybersecurity insights tailored for your sector ({sector}) with a {tone.lower()} tone:</p>
77
- <p><strong>AI Insight:</strong><br>{insight}</p>
78
- <p>Stay secure,<br>CyberIntel UK</p>
79
- <hr>
80
- <p style='font-size:12px;'>You are receiving this because you subscribed to CyberIntel. <a href='#'>Unsubscribe</a> | <a href='#'>Manage Preferences</a></p>
81
- </div>
82
- </body>
83
- </html>
84
- """
85
-
86
- return html_template
87
- except Exception as e:
88
- return f"<p style='color:red;'>Error: {str(e)}</p>"
89
-
90
- with gr.Blocks() as demo:
91
- with gr.Tab("Home"):
92
- gr.Markdown("""
93
- # UK Cybersecurity Newsletter Demo
94
- Use this tool to generate AI-powered, sector-specific insights with compliance filters, tone control, and automatic Mautic contact creation.
95
- """)
96
-
97
- with gr.Tab("Generate Newsletter"):
98
- with gr.Row():
99
- name = gr.Textbox(label="Your Name", placeholder="e.g., Alice")
100
- email = gr.Textbox(label="Your Email", placeholder="alice@example.com")
101
-
102
- sector = gr.Dropdown(label="Choose Sector", choices=["Law", "HR", "Marketing"], value="Law")
103
- tone = gr.Radio(label="Tone", choices=["Formal", "Friendly", "Urgent", "Compliant"], value="Formal")
104
- temperature = gr.Slider(0.0, 1.0, value=0.7, step=0.1, label="Creativity (Temperature)")
105
-
106
- generate_btn = gr.Button("Generate Email Insight")
107
- email_preview = gr.HTML(label="HTML Email Preview")
108
-
109
- generate_btn.click(
110
- generate_insight,
111
- inputs=[name, email, sector, tone, temperature],
112
- outputs=email_preview
113
- )
114
-
115
- with gr.Tab("About"):
116
- gr.Markdown("""
117
- This demo integrates GPT-4 with tone and moderation control to generate UK-sector-focused cybersecurity insights.
118
- Includes Mautic contact sync.
119
- """)
120
-
121
- if __name__ == "__main__":
122
- demo.launch()
123
-
124
 
 
125
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
 
 
 
127
 
 
 
1
  import gradio as gr
 
2
  import os
 
3
  import re
4
+ import requests
5
  from dotenv import load_dotenv
6
  from openai import OpenAI
7
 
 
8
  load_dotenv()
9
+
10
+ # Environment variables
11
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
12
  MAUTIC_BASE_URL = os.getenv("MAUTIC_BASE_URL")
13
  MAUTIC_USERNAME = os.getenv("MAUTIC_USERNAME")
14
  MAUTIC_PASSWORD = os.getenv("MAUTIC_PASSWORD")
15
 
16
+ client = OpenAI(api_key=OPENAI_API_KEY)
17
+
18
+ SECTORS = [
19
+ "Law", "HR", "Marketing", "Finance", "Healthcare", "Education", "Retail",
20
+ "Manufacturing", "Real Estate", "Construction", "Transport", "Hospitality",
21
+ "Media", "Entertainment", "Telecom", "Government", "Energy", "Insurance",
22
+ "Agriculture", "Technology"
23
+ ]
24
+
25
  PROMPTS = {
26
+ sector: f"Generate a UK cybersecurity insight for the {sector} sector." for sector in SECTORS
 
 
 
27
  }
28
 
29
+ # Spam moderation
30
+ SPAM_KEYWORDS = ["free money", "urgent click", "buy now", "no cost"]
31
  def moderate_content(text):
32
+ return not any(re.search(kw, text, re.IGNORECASE) for kw in SPAM_KEYWORDS)
 
 
 
 
33
 
34
+ def send_to_mautic(name, email, content):
35
  try:
36
+ contact_data = {
 
37
  "firstname": name,
38
  "email": email,
39
+ "tags": "A",
40
+ "custom_fields[ai_insight]": content,
41
+ "segment[]": ["ai-contacts"]
42
  }
43
+ response = requests.post(
44
+ f"{MAUTIC_BASE_URL}/api/contacts/new",
45
+ auth=(MAUTIC_USERNAME, MAUTIC_PASSWORD),
46
+ data=contact_data
47
+ )
48
+ if response.status_code in [200, 201]:
49
+ return True, "Contact synced and added to Mautic."
50
+ else:
51
+ return False, f"Mautic error: {response.text}"
52
  except Exception as e:
53
+ return False, f"Error syncing to Mautic: {str(e)}"
54
 
 
 
55
  def generate_insight(name, email, sector, tone, temperature):
56
+ base_prompt = PROMPTS.get(sector, PROMPTS["Technology"])
57
+ tone_prompt = f" Make the tone {tone.lower()} and professional."
58
+ full_prompt = base_prompt + tone_prompt
59
 
60
  try:
61
  response = client.chat.completions.create(
62
  model="gpt-4",
63
  messages=[
64
+ {"role": "system", "content": "You are a UK cybersecurity newsletter assistant."},
65
  {"role": "user", "content": full_prompt}
66
  ],
67
  temperature=temperature,
68
  max_tokens=300
69
  )
 
 
70
  insight = response.choices[0].message.content.strip()
71
 
72
  if not moderate_content(insight):
73
+ return "", "Content flagged as spammy. Please retry."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
+ return insight, "AI-generated content ready. You can edit before sending."
76
 
77
+ except Exception as e:
78
+ return "", f"OpenAI error: {str(e)}"
79
+
80
+ # Gradio UI
81
+ def build_interface():
82
+ with gr.Blocks() as demo:
83
+ with gr.Tab("Generate Insight"):
84
+ name = gr.Textbox(label="Name")
85
+ email = gr.Textbox(label="Email")
86
+ sector = gr.Dropdown(SECTORS, label="Sector", value="Law")
87
+ tone = gr.Radio(["Formal", "Friendly", "Urgent", "Compliant"], label="Tone", value="Formal")
88
+ temperature = gr.Slider(0.1, 1.0, value=0.7, step=0.1, label="Creativity")
89
+ generate_btn = gr.Button("Generate Insight")
90
+ status = gr.Textbox(label="Status", interactive=False)
91
+ raw_output = gr.Textbox(label="Generated Content", lines=10)
92
+
93
+ generate_btn.click(fn=generate_insight,
94
+ inputs=[name, email, sector, tone, temperature],
95
+ outputs=[raw_output, status])
96
+
97
+ with gr.Tab("Preview & Send"):
98
+ edited = gr.Textbox(label="Editable Email Content", lines=10)
99
+ send_btn = gr.Button("Send via Mautic")
100
+ send_status = gr.Textbox(label="Mautic Send Log")
101
+
102
+ send_btn.click(fn=send_to_mautic,
103
+ inputs=[name, email, edited],
104
+ outputs=[None, send_status])
105
+
106
+ with gr.Tab("About"):
107
+ gr.Markdown("""
108
+ ### AI Cybersecurity Newsletter Demo
109
+ This app uses OpenAI GPT to generate sector-specific insights, allows editing, and integrates with Mautic.
110
+
111
+ Contacts are added to the `ai-contacts` segment and emailed through `Campaign A` using the `Email Test` template.
112
+ """)
113
+
114
+ return demo
115
 
116
+ if __name__ == "__main__":
117
+ build_interface().launch()
118