Siergej commited on
Commit
36151a9
Β·
verified Β·
1 Parent(s): a1e1c13

Update app.py

Browse files

* Auto‑reply templates + configurable system‑prompt
* Markdown‑FAQ loading (default `faq.md`)
* SQLite order log (`orders.db`) with in‑UI viewer
* Order export β†’ JSON / CSV / SQLite / XLSX
* Email notifications (Gmail SMTP) for client and/or manager
* Manual β€œNotify manager” button

Files changed (1) hide show
  1. app.py +294 -41
app.py CHANGED
@@ -1,64 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
 
 
2
  from huggingface_hub import InferenceClient
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
 
 
 
17
  ):
18
- messages = [{"role": "system", "content": system_message}]
 
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
 
 
 
25
 
26
  messages.append({"role": "user", "content": message})
27
 
28
- response = ""
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
  max_tokens=max_tokens,
33
- stream=True,
34
  temperature=temperature,
35
  top_p=top_p,
 
36
  ):
37
- token = message.choices[0].delta.content
 
 
38
 
39
- response += token
40
- yield response
41
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  if __name__ == "__main__":
64
  demo.launch()
 
 
1
+ """
2
+ app.py β€” Moops CRM Assistant
3
+ ---------------------------------------
4
+
5
+ A full‑featured CRM web application (GradioΒ 5.x):
6
+
7
+ * LLM (HuggingFaceβ€―Zephyr‑7B) with streaming
8
+ * Auto‑reply templates + configurable system‑prompt
9
+ * Markdown‑FAQ loading (default `faq.md`)
10
+ * SQLite order log (`orders.db`) with in‑UI viewer
11
+ * Order export β†’ JSON / CSV / SQLite / XLSX
12
+ * Email notifications (Gmail SMTP) for client and/or manager
13
+ * Manual β€œNotify manager” button
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import csv
19
+ import datetime
20
+ import json
21
+ import os
22
+ import sqlite3
23
+ import smtplib
24
+ from email.message import EmailMessage
25
+ from pathlib import Path
26
+ from typing import List, Dict
27
+
28
  import gradio as gr
29
+ import pandas as pd
30
+ from dotenv import load_dotenv, find_dotenv
31
  from huggingface_hub import InferenceClient
32
 
 
 
 
 
33
 
34
+ # ───────────────────────────────────────────────
35
+ # βœ‰οΈ Email helpers (credentials come from .env)
36
+ # ───────────────────────────────────────────────
37
+
38
+ # Load .env (the first file found, or explicit path)
39
+ load_dotenv(find_dotenv(filename=".env", raise_error_if_not_found=False))
40
+
41
+ # Read environment variables
42
+ MANAGER_EMAIL = os.getenv("MANAGER_EMAIL")
43
+ GMAIL_LOGIN = os.getenv("GMAIL_LOGIN")
44
+ GMAIL_APP_PASS = os.getenv("GMAIL_APP_PASS")
45
+
46
+ # Fail fast if any creds are missing
47
+ missing = [name for name, val in {
48
+ "MANAGER_EMAIL": MANAGER_EMAIL,
49
+ "GMAIL_LOGIN": GMAIL_LOGIN,
50
+ "GMAIL_APP_PASS": GMAIL_APP_PASS,
51
+ }.items() if not val]
52
+
53
+ if missing:
54
+ raise RuntimeError(
55
+ f"Missing email credentials in .env: {', '.join(missing)}.\n"
56
+ "Create a .env file with:\n"
57
+ "MANAGER_EMAIL=manager@example.com\n"
58
+ "GMAIL_LOGIN=your_gmail@gmail.com\n"
59
+ "GMAIL_APP_PASS=app_password_16_chars"
60
+ )
61
+
62
+ def send_email_notification(subject: str, body: str, to_email: str | None = None) -> None:
63
+ """Send an email via Gmail SMTP (SSL, portβ€―465)."""
64
+ msg = EmailMessage()
65
+ msg["From"] = GMAIL_LOGIN
66
+ msg["To"] = to_email or MANAGER_EMAIL
67
+ msg["Subject"] = subject
68
+ msg.set_content(body)
69
+
70
+ with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
71
+ smtp.login(GMAIL_LOGIN, GMAIL_APP_PASS)
72
+ smtp.send_message(msg)
73
+
74
+ def send_notification_to_manager(subject: str, body: str) -> None:
75
+ """Shortcut β†’ always deliver to MANAGER_EMAIL."""
76
+ send_email_notification(subject, body, MANAGER_EMAIL)
77
+
78
+
79
+ # ──────────────────────────────────────────
80
+ # βš™οΈ Constants and Hugging Face client
81
+ # ──────────────────────────────────────────
82
+ DB_FILE = "orders.db"
83
+ FAQ_DEFAULT_PATH = "faq.md"
84
+ orders_log: List[Dict] = []
85
+
86
+ auto_templates = {
87
+ "Greeting": "Hello! πŸ‘‹ Welcome to our service. How can I assist you today?",
88
+ "Pricing Info": "Our base pricing starts from **$10 per item**, with a minimum order of "
89
+ "**50 units**. Discounts apply for larger orders. Would you like a quote?",
90
+ "Thank you": "Thank you for reaching out. We look forward to helping you. Have a great day!",
91
+ "Custom T-shirt Quote": "Sure! Please provide the number of shirts and colors in the design and "
92
+ "we’ll send you a detailed quote."
93
+ }
94
+
95
+ HF_TOKEN = os.getenv("HF_TOKEN")
96
+ client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=HF_TOKEN)
97
+
98
+ # ──────────────────────────────────────────
99
+ # πŸ—„οΈ SQLite initialization
100
+ # ──────────────────────────────────────────
101
+ def init_db() -> None:
102
+ conn = sqlite3.connect(DB_FILE)
103
+ conn.execute(
104
+ """
105
+ CREATE TABLE IF NOT EXISTS orders (
106
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
107
+ timestamp TEXT,
108
+ email TEXT,
109
+ user TEXT,
110
+ assistant TEXT
111
+ )
112
+ """
113
+ )
114
+ conn.close()
115
+
116
+ init_db()
117
+
118
+ # ──────────────────────────────────────────
119
+ # πŸ“„ FAQ helpers
120
+ # ──────────────────────────────────────────
121
+ def load_faq_text(md_file) -> str:
122
+ if md_file is None:
123
+ return "No FAQ file uploaded."
124
+ return Path(md_file.name).read_text(encoding="utf-8")
125
+
126
+ def load_default_faq() -> str:
127
+ p = Path(FAQ_DEFAULT_PATH)
128
+ return p.read_text(encoding="utf-8") if p.exists() else ""
129
+
130
+ # ──────────────────────────────────────────
131
+ # πŸ’Ύ Export helpers
132
+ # ──────────────────────────────────────────
133
+ def save_to_json() -> str:
134
+ fname = f"orders_{datetime.datetime.now():%Y%m%d_%H%M%S}.json"
135
+ Path(fname).write_text(json.dumps(orders_log, ensure_ascii=False, indent=2), encoding="utf-8")
136
+ return f"βœ… Saved {fname}"
137
+
138
+ def export_to_csv() -> str:
139
+ fname = f"orders_{datetime.datetime.now():%Y%m%d_%H%M%S}.csv"
140
+ with open(fname, "w", newline="", encoding="utf-8") as f:
141
+ writer = csv.DictWriter(f, fieldnames=["timestamp", "email", "user", "assistant"])
142
+ writer.writeheader()
143
+ writer.writerows(orders_log)
144
+ return f"πŸ“„ Saved {fname}"
145
 
146
+ def export_to_sqlite() -> str:
147
+ conn = sqlite3.connect(DB_FILE)
148
+ with conn:
149
+ for row in orders_log:
150
+ conn.execute(
151
+ "INSERT INTO orders (timestamp, email, user, assistant) VALUES (?, ?, ?, ?)",
152
+ (row["timestamp"], row["email"], row["user"], row["assistant"]),
153
+ )
154
+ return f"πŸ“¦ Flushed to {DB_FILE}"
155
+
156
+ def export_to_xlsx() -> str:
157
+ conn = sqlite3.connect(DB_FILE)
158
+ df = pd.read_sql_query("SELECT * FROM orders ORDER BY id", conn)
159
+ conn.close()
160
+ fname = f"orders_{datetime.datetime.now():%Y%m%d_%H%M%S}.xlsx"
161
+ df.to_excel(fname, index=False)
162
+ return f"πŸ“— Saved {fname}"
163
+
164
+ # ──────────────────────────────────────────
165
+ # πŸ” View DB helper
166
+ # ──────────────────────────────────────────
167
+ def view_db_contents() -> str:
168
+ conn = sqlite3.connect(DB_FILE)
169
+ df = pd.read_sql_query("SELECT * FROM orders ORDER BY id DESC", conn)
170
+ conn.close()
171
+ return df.to_markdown(index=False)
172
+
173
+ # ──────────────────────────────────────────
174
+ # πŸ€– Main respond function
175
+ # ──────────────────────────────────────────
176
  def respond(
177
+ message: str,
178
+ history: list[dict] | None,
179
+ email: str,
180
+ strategy_text: str,
181
+ template_choice: str,
182
+ faq_content: str,
183
+ max_tokens: int,
184
+ temperature: float,
185
+ top_p: float,
186
  ):
187
+ """
188
+ Generate assistant reply, log the order, send notifications.
189
 
190
+ Returns
191
+ -------
192
+ (updated_history, gr.update("")) -> clears the input box.
193
+ """
194
+ system_message = strategy_text.strip() or "You are a helpful assistant."
195
+ if faq_content:
196
+ system_message += f"\n\nAdditional info from FAQ:\n{faq_content.strip()}"
197
+ if template_choice:
198
+ system_message += f"\n\n[Template]: {auto_templates.get(template_choice, template_choice)}"
199
+
200
+ messages = [{"role": "system", "content": system_message}]
201
+ if history:
202
+ messages.extend(m for m in history if m["role"] in ("user", "assistant"))
203
 
204
  messages.append({"role": "user", "content": message})
205
 
206
+ partial_reply = ""
207
+ visual_history = history or []
208
+ visual_history += [{"role": "user", "content": message}]
209
 
210
+ for chunk in client.chat_completion(
211
+ messages=messages,
212
  max_tokens=max_tokens,
 
213
  temperature=temperature,
214
  top_p=top_p,
215
+ stream=True,
216
  ):
217
+ delta = chunk.choices[0].delta.content or ""
218
+ partial_reply += delta
219
+ yield visual_history + [{"role": "assistant", "content": partial_reply}], gr.update(value="")
220
 
221
+ # Finalize the history
222
+ final_history = visual_history + [{"role": "assistant", "content": partial_reply}]
223
 
224
+ # Store order
225
+ order_row = {
226
+ "timestamp": datetime.datetime.now().isoformat(),
227
+ "email": email,
228
+ "user": message,
229
+ "assistant": partial_reply,
230
+ }
231
+ orders_log.append(order_row)
232
 
233
+ conn = sqlite3.connect(DB_FILE)
234
+ with conn:
235
+ conn.execute(
236
+ "INSERT INTO orders (timestamp, email, user, assistant) VALUES (?, ?, ?, ?)",
237
+ (order_row["timestamp"], email, message, partial_reply),
238
+ )
239
+
240
+ # Email manager/client
241
+ try:
242
+ subj = f"πŸ“© New CRM interaction from {email or 'anonymous'}"
243
+ body = (
244
+ f"Customer:\n{message}\n\nAssistant:\n{partial_reply}\n\n"
245
+ f"Strategy:\n{strategy_text}\nTemplate:\n{template_choice}"
246
+ )
247
+ send_email_notification(subj, body)
248
+ except Exception as exc:
249
+ print(f"❌ Email send failed: {exc}")
250
+
251
+ yield final_history, gr.update(value="")
252
+
253
+ # ──────────────────────────────────────────
254
+ # πŸ“¨ Manual manager notification
255
+ # ──────────────────────────────────────────
256
+ def notify_manager_click() -> str:
257
+ subj = "πŸ“¬ Manual Moops CRM Notification"
258
+ msg = f"Manual trigger at {datetime.datetime.now():%Y-%m-%d %H:%M:%S}"
259
+ try:
260
+ send_notification_to_manager(subj, msg)
261
+ return "πŸ“§ Manager notified."
262
+ except Exception as exc:
263
+ return f"❌ Notification failed: {exc}"
264
 
265
+ # ──────────────────────────────────────────
266
+ # 🌐 Gradio UI
267
+ # ──────────────────────────────────────────
268
+ with gr.Blocks(title="Moops CRM All‑in‑One") as demo:
269
+ gr.Markdown("# πŸ›οΈ Moops CRM Assistant β€” All‑in‑One")
270
+
271
+ # Input controls
272
+ with gr.Row():
273
+ client_email = gr.Textbox(label="Client Email", placeholder="client@example.com")
274
+ strategy_text = gr.Textbox(label="Assistant Strategy", value="You are a polite business assistant...")
275
+
276
+ template_choice = gr.Radio(list(auto_templates.keys()), value="Greeting", label="πŸ“‹ Auto‑reply Template")
277
+
278
+ with gr.Row():
279
+ faq_upload = gr.File(label="πŸ“„ Upload FAQ (Markdown)", file_types=[".md"])
280
+ faq_textbox = gr.Textbox(label="FAQ Content", lines=10, value=load_default_faq())
281
+
282
+ gr.Button("πŸ“‚ Load uploaded FAQ").click(load_faq_text, faq_upload, faq_textbox)
283
+
284
+ # Chat interface
285
+ chatbot = gr.Chatbot(render_markdown=True, type="messages", label="πŸ’¬ Chatbot")
286
+ user_input = gr.Textbox(label="πŸ’¬ User Message")
287
+
288
+ with gr.Row():
289
+ max_tokens = gr.Slider(1, 4096, value=1024, label="Max tokens")
290
+ temperature = gr.Slider(0.1, 4.0, value=0.7, step=0.1, label="Temperature")
291
+ top_p = gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top‑p")
292
+
293
+ template_choice.change(lambda t: auto_templates[t], template_choice, user_input)
294
+
295
+ user_input.submit(
296
+ respond,
297
+ [user_input, chatbot, client_email, strategy_text, template_choice, faq_textbox,
298
+ max_tokens, temperature, top_p],
299
+ [chatbot, user_input],
300
+ )
301
+
302
+ # Export/DB/Notification controls
303
+ gr.Markdown("### πŸ’Ύ Export")
304
+ gr.Button("πŸ’Ύ JSON").click(lambda: save_to_json(), None, gr.Textbox(lines=1))
305
+ gr.Button("πŸ“„ CSV").click(lambda: export_to_csv(), None, gr.Textbox(lines=1))
306
+ gr.Button("πŸ“¦ Flush to SQLite").click(lambda: export_to_sqlite(), None, gr.Textbox(lines=1))
307
+ gr.Button("πŸ“— XLSX").click(lambda: export_to_xlsx(), None, gr.Textbox(lines=1))
308
+
309
+ gr.Markdown("### πŸ“Š View DB")
310
+ gr.Button("πŸ” View orders.db").click(lambda: view_db_contents(), None, gr.Textbox(lines=15))
311
+
312
+ gr.Markdown("### πŸ“« Notify")
313
+ gr.Button("πŸ“© Notify manager").click(lambda: notify_manager_click(), None, gr.Textbox(lines=1))
314
 
315
  if __name__ == "__main__":
316
  demo.launch()
317
+