Anupam251272 commited on
Commit
7aae5d8
1 Parent(s): 71bf850

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +419 -0
app.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import sqlite3
3
+ from datetime import datetime
4
+ import pandas as pd
5
+ from sqlalchemy import create_engine, text
6
+ from sqlalchemy.orm import sessionmaker
7
+ import logging
8
+ import json
9
+ import transformers
10
+ import torch
11
+ from transformers import pipeline
12
+
13
+ # Database Operations Class
14
+ class DatabaseManager:
15
+ def __init__(self, db_path='crm.db'):
16
+ self.db_path = db_path
17
+ self.engine = create_engine(f'sqlite:///{db_path}')
18
+ Session = sessionmaker(bind=self.engine)
19
+ self.session = Session()
20
+ self.setup_database()
21
+
22
+ def setup_database(self):
23
+ """Create database tables if they don't exist"""
24
+ queries = [
25
+ """
26
+ CREATE TABLE IF NOT EXISTS customers (
27
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
28
+ name TEXT NOT NULL,
29
+ email TEXT UNIQUE,
30
+ phone TEXT,
31
+ address TEXT,
32
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
33
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
34
+ )
35
+ """,
36
+ """
37
+ CREATE TABLE IF NOT EXISTS tickets (
38
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
39
+ customer_id INTEGER,
40
+ subject TEXT NOT NULL,
41
+ description TEXT,
42
+ status TEXT DEFAULT 'open',
43
+ priority TEXT DEFAULT 'medium',
44
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
45
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
46
+ FOREIGN KEY (customer_id) REFERENCES customers (id)
47
+ )
48
+ """,
49
+ """
50
+ CREATE TABLE IF NOT EXISTS interactions (
51
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
52
+ customer_id INTEGER,
53
+ ticket_id INTEGER,
54
+ message TEXT NOT NULL,
55
+ response TEXT,
56
+ sentiment_score FLOAT,
57
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
58
+ FOREIGN KEY (customer_id) REFERENCES customers (id),
59
+ FOREIGN KEY (ticket_id) REFERENCES tickets (id)
60
+ )
61
+ """
62
+ ]
63
+
64
+ conn = sqlite3.connect(self.db_path)
65
+ cursor = conn.cursor()
66
+ for query in queries:
67
+ cursor.execute(query)
68
+ conn.commit()
69
+ conn.close()
70
+
71
+ # Customer Operations
72
+ def add_customer(self, name, email, phone=None, address=None):
73
+ """Add a new customer"""
74
+ try:
75
+ query = """
76
+ INSERT INTO customers (name, email, phone, address)
77
+ VALUES (?, ?, ?, ?)
78
+ """
79
+ conn = sqlite3.connect(self.db_path)
80
+ cursor = conn.cursor()
81
+ cursor.execute(query, (name, email, phone, address))
82
+ customer_id = cursor.lastrowid
83
+ conn.commit()
84
+ conn.close()
85
+ return {"status": "success", "customer_id": customer_id}
86
+ except sqlite3.IntegrityError:
87
+ return {"status": "error", "message": "Email already exists"}
88
+ except Exception as e:
89
+ return {"status": "error", "message": str(e)}
90
+
91
+ def get_customer(self, customer_id):
92
+ """Get customer details"""
93
+ query = "SELECT * FROM customers WHERE id = ?"
94
+ conn = sqlite3.connect(self.db_path)
95
+ result = pd.read_sql_query(query, conn, params=(customer_id,))
96
+ conn.close()
97
+ return result.to_dict('records')[0] if not result.empty else None
98
+
99
+ def update_customer(self, customer_id, **kwargs):
100
+ """Update customer details"""
101
+ try:
102
+ set_clause = ", ".join([f"{k} = ?" for k in kwargs.keys()])
103
+ query = f"""
104
+ UPDATE customers
105
+ SET {set_clause}, updated_at = CURRENT_TIMESTAMP
106
+ WHERE id = ?
107
+ """
108
+ conn = sqlite3.connect(self.db_path)
109
+ cursor = conn.cursor()
110
+ cursor.execute(query, (*kwargs.values(), customer_id))
111
+ conn.commit()
112
+ conn.close()
113
+ return {"status": "success"}
114
+ except Exception as e:
115
+ return {"status": "error", "message": str(e)}
116
+
117
+ def delete_customer(self, customer_id):
118
+ """Delete a customer"""
119
+ try:
120
+ query = "DELETE FROM customers WHERE id = ?"
121
+ conn = sqlite3.connect(self.db_path)
122
+ cursor = conn.cursor()
123
+ cursor.execute(query, (customer_id,))
124
+ conn.commit()
125
+ conn.close()
126
+ return {"status": "success"}
127
+ except Exception as e:
128
+ return {"status": "error", "message": str(e)}
129
+
130
+ # Ticket Operations
131
+ def create_ticket(self, customer_id, subject, description, priority="medium"):
132
+ """Create a new support ticket"""
133
+ try:
134
+ query = """
135
+ INSERT INTO tickets (customer_id, subject, description, priority)
136
+ VALUES (?, ?, ?, ?)
137
+ """
138
+ conn = sqlite3.connect(self.db_path)
139
+ cursor = conn.cursor()
140
+ cursor.execute(query, (customer_id, subject, description, priority))
141
+ ticket_id = cursor.lastrowid
142
+ conn.commit()
143
+ conn.close()
144
+ return {"status": "success", "ticket_id": ticket_id}
145
+ except Exception as e:
146
+ return {"status": "error", "message": str(e)}
147
+
148
+ def get_ticket(self, ticket_id):
149
+ """Get ticket details"""
150
+ query = """
151
+ SELECT t.*, c.name as customer_name
152
+ FROM tickets t
153
+ JOIN customers c ON t.customer_id = c.id
154
+ WHERE t.id = ?
155
+ """
156
+ conn = sqlite3.connect(self.db_path)
157
+ result = pd.read_sql_query(query, conn, params=(ticket_id,))
158
+ conn.close()
159
+ return result.to_dict('records')[0] if not result.empty else None
160
+
161
+ def update_ticket(self, ticket_id, **kwargs):
162
+ """Update ticket details"""
163
+ try:
164
+ set_clause = ", ".join([f"{k} = ?" for k in kwargs.keys()])
165
+ query = f"""
166
+ UPDATE tickets
167
+ SET {set_clause}, updated_at = CURRENT_TIMESTAMP
168
+ WHERE id = ?
169
+ """
170
+ conn = sqlite3.connect(self.db_path)
171
+ cursor = conn.cursor()
172
+ cursor.execute(query, (*kwargs.values(), ticket_id))
173
+ conn.commit()
174
+ conn.close()
175
+ return {"status": "success"}
176
+ except Exception as e:
177
+ return {"status": "error", "message": str(e)}
178
+
179
+ # Interaction Operations
180
+ def add_interaction(self, customer_id, ticket_id, message, response=None, sentiment_score=None):
181
+ """Record a new interaction"""
182
+ try:
183
+ query = """
184
+ INSERT INTO interactions (customer_id, ticket_id, message, response, sentiment_score)
185
+ VALUES (?, ?, ?, ?, ?)
186
+ """
187
+ conn = sqlite3.connect(self.db_path)
188
+ cursor = conn.cursor()
189
+ cursor.execute(query, (customer_id, ticket_id, message, response, sentiment_score))
190
+ interaction_id = cursor.lastrowid
191
+ conn.commit()
192
+ conn.close()
193
+ return {"status": "success", "interaction_id": interaction_id}
194
+ except Exception as e:
195
+ return {"status": "error", "message": str(e)}
196
+
197
+ # Analytics Queries
198
+ def get_customer_history(self, customer_id):
199
+ """Get complete customer history"""
200
+ query = """
201
+ SELECT
202
+ t.id as ticket_id,
203
+ t.subject,
204
+ t.status,
205
+ t.priority,
206
+ i.message,
207
+ i.response,
208
+ i.sentiment_score,
209
+ i.created_at
210
+ FROM tickets t
211
+ LEFT JOIN interactions i ON t.id = i.ticket_id
212
+ WHERE t.customer_id = ?
213
+ ORDER BY i.created_at DESC
214
+ """
215
+ conn = sqlite3.connect(self.db_path)
216
+ result = pd.read_sql_query(query, conn, params=(customer_id,))
217
+ conn.close()
218
+ return result.to_dict('records')
219
+
220
+ def get_recent_interactions(self, customer_id, limit=10):
221
+ """Retrieve recent interactions for a specific customer"""
222
+ query = """
223
+ SELECT message, response, created_at
224
+ FROM interactions
225
+ WHERE customer_id = ?
226
+ ORDER BY created_at DESC
227
+ LIMIT ?
228
+ """
229
+ conn = sqlite3.connect(self.db_path)
230
+ result = pd.read_sql_query(query, conn, params=(customer_id, limit))
231
+ conn.close()
232
+ return result.to_dict('records')
233
+
234
+ # Sentiment Analysis Class
235
+ class SentimentAnalyzer:
236
+ def __init__(self):
237
+ try:
238
+ self.sentiment_pipeline = pipeline("sentiment-analysis")
239
+ except Exception as e:
240
+ print(f"Error loading sentiment analysis model: {e}")
241
+ self.sentiment_pipeline = None
242
+
243
+ def analyze_sentiment(self, text):
244
+ """Analyze sentiment of a given text"""
245
+ if not self.sentiment_pipeline:
246
+ return None
247
+ try:
248
+ result = self.sentiment_pipeline(text)[0]
249
+ return {
250
+ 'label': result['label'],
251
+ 'score': result['score']
252
+ }
253
+ except Exception as e:
254
+ print(f"Sentiment analysis error: {e}")
255
+ return None
256
+
257
+ # Gradio Interface
258
+ def create_database_interface():
259
+ db = DatabaseManager()
260
+ sentiment_analyzer = SentimentAnalyzer()
261
+
262
+ def customer_chat_interface(customer_id, message):
263
+ """Process customer chat message"""
264
+ try:
265
+ # First, check if customer exists
266
+ customer = db.get_customer(int(customer_id))
267
+ if not customer:
268
+ return "Error: Customer not found"
269
+
270
+ # Analyze sentiment of the message
271
+ sentiment = sentiment_analyzer.analyze_sentiment(message)
272
+ sentiment_score = sentiment['score'] if sentiment else None
273
+
274
+ # Simulate a simple bot response (you can replace with more advanced logic)
275
+ response = f"Thank you for your message. We'll get back to you soon about: {message}"
276
+
277
+ # Add interaction to database
278
+ interaction = db.add_interaction(
279
+ customer_id=int(customer_id),
280
+ ticket_id=None, # Optional: can link to an existing ticket
281
+ message=message,
282
+ response=response,
283
+ sentiment_score=sentiment_score
284
+ )
285
+
286
+ # Retrieve recent interactions for context
287
+ recent_interactions = db.get_recent_interactions(int(customer_id))
288
+
289
+ return json.dumps({
290
+ 'response': response,
291
+ 'interaction_id': interaction.get('interaction_id'),
292
+ 'sentiment': sentiment,
293
+ 'recent_interactions': recent_interactions
294
+ }, indent=2)
295
+
296
+ except Exception as e:
297
+ return f"Error processing chat: {str(e)}"
298
+
299
+ def add_customer_interface(name, email, phone, address):
300
+ result = db.add_customer(name, email, phone, address)
301
+ return json.dumps(result, indent=2)
302
+
303
+ def get_customer_interface(customer_id):
304
+ result = db.get_customer(int(customer_id))
305
+ return json.dumps(result, indent=2) if result else "Customer not found"
306
+
307
+ def update_customer_interface(customer_id, name, email, phone, address):
308
+ updates = {}
309
+ if name: updates['name'] = name
310
+ if email: updates['email'] = email
311
+ if phone: updates['phone'] = phone
312
+ if address: updates['address'] = address
313
+
314
+ result = db.update_customer(int(customer_id), **updates)
315
+ return json.dumps(result, indent=2)
316
+
317
+ def create_ticket_interface(customer_id, subject, description, priority):
318
+ result = db.create_ticket(int(customer_id), subject, description, priority)
319
+ return json.dumps(result, indent=2)
320
+
321
+ def get_customer_history_interface(customer_id):
322
+ result = db.get_customer_history(int(customer_id))
323
+ return json.dumps(result, indent=2)
324
+
325
+ # Create the interface
326
+ with gr.Blocks() as interface:
327
+ gr.Markdown("# CRM Database Operations")
328
+
329
+ with gr.Tab("Customer Management"):
330
+ gr.Markdown("### Add New Customer")
331
+ with gr.Row():
332
+ name_input = gr.Textbox(label="Name")
333
+ email_input = gr.Textbox(label="Email")
334
+ phone_input = gr.Textbox(label="Phone")
335
+ address_input = gr.Textbox(label="Address")
336
+ add_customer_button = gr.Button("Add Customer")
337
+ add_customer_output = gr.Textbox(label="Result")
338
+
339
+ gr.Markdown("### Get Customer Details")
340
+ customer_id_input = gr.Number(label="Customer ID")
341
+ get_customer_button = gr.Button("Get Customer")
342
+ get_customer_output = gr.Textbox(label="Customer Details")
343
+
344
+ gr.Markdown("### Update Customer")
345
+ update_id_input = gr.Number(label="Customer ID")
346
+ update_name = gr.Textbox(label="New Name (optional)")
347
+ update_email = gr.Textbox(label="New Email (optional)")
348
+ update_phone = gr.Textbox(label="New Phone (optional)")
349
+ update_address = gr.Textbox(label="New Address (optional)")
350
+ update_customer_button = gr.Button("Update Customer")
351
+ update_customer_output = gr.Textbox(label="Update Result")
352
+
353
+ with gr.Tab("Ticket Management"):
354
+ gr.Markdown("### Create New Ticket")
355
+ with gr.Row():
356
+ ticket_customer_id = gr.Number(label="Customer ID")
357
+ ticket_subject = gr.Textbox(label="Subject")
358
+ ticket_description = gr.Textbox(label="Description")
359
+ ticket_priority = gr.Dropdown(
360
+ choices=["low", "medium", "high"],
361
+ label="Priority"
362
+ )
363
+ create_ticket_button = gr.Button("Create Ticket")
364
+ create_ticket_output = gr.Textbox(label="Result")
365
+
366
+ with gr.Tab("Customer History"):
367
+ history_customer_id = gr.Number(label="Customer ID")
368
+ get_history_button = gr.Button("Get History")
369
+ history_output = gr.Textbox(label="Customer History")
370
+
371
+ with gr.Tab("Customer Chat"):
372
+ chat_customer_id = gr.Number(label="Customer ID")
373
+ chat_message = gr.Textbox(label="Your Message")
374
+ chat_submit_button = gr.Button("Send Message")
375
+ chat_output = gr.Textbox(label="Chat Response")
376
+
377
+ # Connect the buttons to their functions
378
+ add_customer_button.click(
379
+ add_customer_interface,
380
+ inputs=[name_input, email_input, phone_input, address_input],
381
+ outputs=add_customer_output
382
+ )
383
+
384
+ get_customer_button.click(
385
+ get_customer_interface,
386
+ inputs=[customer_id_input],
387
+ outputs=get_customer_output
388
+ )
389
+
390
+ update_customer_button.click(
391
+ update_customer_interface,
392
+ inputs=[update_id_input, update_name, update_email, update_phone, update_address],
393
+ outputs=update_customer_output
394
+ )
395
+
396
+ create_ticket_button.click(
397
+ create_ticket_interface,
398
+ inputs=[ticket_customer_id, ticket_subject, ticket_description, ticket_priority],
399
+ outputs=create_ticket_output
400
+ )
401
+
402
+ get_history_button.click(
403
+ get_customer_history_interface,
404
+ inputs=[history_customer_id],
405
+ outputs=history_output
406
+ )
407
+
408
+ chat_submit_button.click(
409
+ customer_chat_interface,
410
+ inputs=[chat_customer_id, chat_message],
411
+ outputs=chat_output
412
+ )
413
+
414
+ return interface
415
+
416
+ # Launch the interface
417
+ if __name__ == "__main__":
418
+ interface = create_database_interface()
419
+ interface.launch(share=True)