Spaces:
Sleeping
Sleeping
Update backend/ai/database.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404113 unmodified lines5556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221234 unmodified lines128129130131132133134135136137138# database.pyimport sqlite3import datetimeimport os# --- Đường dẫn DB trên Hugging Face Space ---DB_NAME = os.path.join("/tmp", "vnpt_call_center.db")# --- 20 DATA MẪU ---INITIAL_DATA = [{"customer_id": "CUS_001", "call_id": "CALL_0001", "call_timestamp": "2025-01-20T08:15:00+07:00", "call_duration_seconds": 78, "intent": "network_issue", "sentiment": "positive", "ai_resolved": True, "upsell_success": False, "csat": 5, "cost_per_call_vnd": 2350},{"customer_id": "CUS_002", "call_id": "CALL_0002", "call_timestamp": "2025-01-20T08:35:00+07:00", "call_duration_seconds": 92, "intent": "cancel_package", "sentiment": "neutral", "ai_resolved": True, "upsell_success": True, "csat": 4, "cost_per_call_vnd": 2480},{"customer_id": "CUS_003", "call_id": "CALL_0003", "call_timestamp": "2025-01-20T09:05:00+07:00", "call_duration_seconds": 110, "intent": "competitor", "sentiment": "negative", "ai_resolved": False, "upsell_success": False, "csat": 3, "cost_per_call_vnd": 2650},{"customer_id": "CUS_004", "call_id": "CALL_0004", "call_timestamp": "2025-01-20T09:40:00+07:00", "call_duration_seconds": 70, "intent": "network_issue", "sentiment": "positive", "ai_resolved": True, "upsell_success": False, "csat": 5, "cost_per_call_vnd": 2300},{"customer_id": "CUS_005", "call_id": "CALL_0005", "call_timestamp": "2025-01-20T10:10:00+07:00", "call_duration_seconds": 88, "intent": "cancel_package", "sentiment": "neutral", "ai_resolved": True, "upsell_success": True, "csat": 4, "cost_per_call_vnd": 2450},{"customer_id": "CUS_006", "call_id": "CALL_0006", "call_timestamp": "2025-01-20T10:45:00+07:00", "call_duration_seconds": 80, "intent": "network_issue", "sentiment": "positive", "ai_resolved": True, "upsell_success": False, "csat": 5, "cost_per_call_vnd": 2380},{"customer_id": "CUS_007", "call_id": "CALL_0007", "call_timestamp": "2025-01-18T14:20:00+07:00", "call_duration_seconds": 95, "intent": "cancel_package", "sentiment": "neutral", "ai_resolved": True, "upsell_success": True, "csat": 4, "cost_per_call_vnd": 2500},{"customer_id": "CUS_008", "call_id": "CALL_0008", "call_timestamp": "2025-01-18T16:05:00+07:00", "call_duration_seconds": 72, "intent": "network_issue", "sentiment": "positive", "ai_resolved": True, "upsell_success": False, "csat": 5, "cost_per_call_vnd": 2320},{"customer_id": "CUS_009", "call_id": "CALL_0009", "call_timestamp": "2025-01-17T10:30:00+07:00", "call_duration_seconds": 105, "intent": "competitor", "sentiment": "negative", "ai_resolved": False, "upsell_success": False, "csat": 3, "cost_per_call_vnd": 2680},{"customer_id": "CUS_010", "call_id": "CALL_0010", "call_timestamp": "2025-01-17T15:10:00+07:00", "call_duration_seconds": 85, "intent": "network_issue", "sentiment": "positive", "ai_resolved": True, "upsell_success": False, "csat": 5, "cost_per_call_vnd": 2400},{"customer_id": "CUS_011", "call_id": "CALL_0011", "call_timestamp": "2025-01-16T09:45:00+07:00", "call_duration_seconds": 90, "intent": "cancel_package", "sentiment": "neutral", "ai_resolved": True, "upsell_success": True, "csat": 4, "cost_per_call_vnd": 2480},{"customer_id": "CUS_012", "call_id": "CALL_0012", "call_timestamp": "2025-01-16T11:20:00+07:00", "call_duration_seconds": 76, "intent": "network_issue", "sentiment": "positive", "ai_resolved": True, "upsell_success": False, "csat": 5, "cost_per_call_vnd": 2350},{"customer_id": "CUS_013", "call_id": "CALL_0013", "call_timestamp": "2025-01-15T14:55:00+07:00", "call_duration_seconds": 108, "intent": "competitor", "sentiment": "negative", "ai_resolved": False, "upsell_success": False, "csat": 3, "cost_per_call_vnd": 2620},{"customer_id": "CUS_014", "call_id": "CALL_0014", "call_timestamp": "2025-01-15T16:40:00+07:00", "call_duration_seconds": 82, "intent": "network_issue", "sentiment": "positive", "ai_resolved": True, "upsell_success": False, "csat": 5, "cost_per_call_vnd": 2380},{"customer_id": "CUS_015", "call_id": "CALL_0015", "call_timestamp": "2025-01-10T10:15:00+07:00", "call_duration_seconds": 88, "intent": "cancel_package", "sentiment": "neutral", "ai_resolved": True, "upsell_success": True, "csat": 4, "cost_per_call_vnd": 2450},{"customer_id": "CUS_016", "call_id": "CALL_0016", "call_timestamp": "2025-01-08T14:30:00+07:00", "call_duration_seconds": 74, "intent": "network_issue", "sentiment": "positive", "ai_resolved": True, "upsell_success": False, "csat": 5, "cost_per_call_vnd": 2350},{"customer_id": "CUS_017", "call_id": "CALL_0017", "call_timestamp": "2025-01-05T09:50:00+07:00", "call_duration_seconds": 112, "intent": "competitor", "sentiment": "negative", "ai_resolved": False, "upsell_success": False, "csat": 3, "cost_per_call_vnd": 2700},{"customer_id": "CUS_018", "call_id": "CALL_0018", "call_timestamp": "2025-01-04T15:05:00+07:00", "call_duration_seconds": 80, "intent": "network_issue", "sentiment": "positive", "ai_resolved": True, "upsell_success": False, "csat": 5, "cost_per_call_vnd": 2380},{"customer_id": "CUS_019", "call_id": "CALL_0019", "call_timestamp": "2025-01-03T11:40:00+07:00", "call_duration_seconds": 96, "intent": "cancel_package", "sentiment": "neutral", "ai_resolved": True, "upsell_success": True, "csat": 4, "cost_per_call_vnd": 2500},{"customer_id": "CUS_020", "call_id": "CALL_0020", "call_timestamp": "2024-12-28T16:10:00+07:00", "call_duration_seconds": 85, "intent": "network_issue", "sentiment": "positive", "ai_resolved": True, "upsell_success": False, "csat": 5, "cost_per_call_vnd": 2400}]class Database:def __init__(self):self._init_db()def _get_conn(self):return sqlite3.connect(DB_NAME, check_same_thread=False)def _init_db(self):conn = self._get_conn()13 unmodified linescost INTEGER)''')# Seed nếu DB trốngcursor.execute("SELECT count(*) FROM calls")if cursor.fetchone()[0] == 0:print(" [DB] Database trống. Đang nạp 20 bản ghi mẫu...")self._seed_data(cursor)conn.commit()conn.close()def _seed_data(self, cursor):for item in INITIAL_DATA:cursor.execute('''INSERT INTO calls (customer_id, call_id, call_timestamp, duration, intent, sentiment, ai_resolved, upsell, csat, cost)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', (item['customer_id'],item['call_id'],item['call_timestamp'],item['call_duration_seconds'],item['intent'],item['sentiment'],item['ai_resolved'],item['upsell_success'],item['csat'],item['cost_per_call_vnd']))def get_all_calls(self):conn = self._get_conn()cursor = conn.cursor()cursor.execute("SELECT * FROM calls ORDER BY call_timestamp DESC")rows = cursor.fetchall()conn.close()result = []for r in rows:result.append({"id": r[1], # customer_id"time": r[3], # timestamp"dur": r[4], # duration"intent": r[5],"sent": r[6],"ai": bool(r[7]),"upsell": bool(r[8]),"csat": r[9],"cost": r[10]})return resultdef add_call(self, customer_id, duration, intent, sentiment, ai_resolved, upsell, cost):conn = self._get_conn()cursor = conn.cursor()call_id = f"LIVE_{int(datetime.datetime.now().timestamp())}"timestamp = datetime.datetime.now().isoformat()cursor.execute('''INSERT INTO calls (customer_id, call_id, call_timestamp, duration, intent, sentiment, ai_resolved, upsell, csat, cost)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', (customer_id, call_id, timestamp, duration, intent, sentiment, ai_resolved, upsell, cost['csat'], cost['value']))conn.commit()conn.close()def update_call_rating(self, customer_id, stars):conn = self._get_conn()cursor = conn.cursor()try:cursor.execute('''SELECT id FROM callsWHERE customer_id = ?4 unmodified linesif row:cursor.execute('UPDATE calls SET csat = ? WHERE id = ?', (int(stars), row[0]))conn.commit()print(f" [DB] Cập nhật CSAT={stars} cho {customer_id}")except Exception as e:print(f" [DB Error] Update Rating: {e}")finally:conn.close()# Singletondb = Database()12345678910111213141516171819202122232425262728293031323334353637383913 unmodified lines53545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381394 unmodified lines144145146147148149150151152153154155156# database_debug.pyimport sqlite3import datetimeimport osimport traceback# --- Đường dẫn DB trên Hugging Face Space ---DB_NAME = os.path.join("/tmp", "vnpt_call_center.db")print(f"[DB DEBUG] Database path: {DB_NAME}")# --- 20 DATA MẪU ---INITIAL_DATA = [{"customer_id": "CUS_001", "call_id": "CALL_0001", "call_timestamp": "2025-01-20T08:15:00+07:00", "call_duration_seconds": 78, "intent": "network_issue", "sentiment": "positive", "ai_resolved": True, "upsell_success": False, "csat": 5, "cost_per_call_vnd": 2350},{"customer_id": "CUS_002", "call_id": "CALL_0002", "call_timestamp": "2025-01-20T08:35:00+07:00", "call_duration_seconds": 92, "intent": "cancel_package", "sentiment": "neutral", "ai_resolved": True, "upsell_success": True, "csat": 4, "cost_per_call_vnd": 2480},# ... giữ nguyên 20 record mẫu ...]class Database:def __init__(self):try:print("[DB DEBUG] Khởi tạo Database...")self._init_db()print("[DB DEBUG] Database khởi tạo xong.")except Exception as e:print(f"[DB ERROR] Init DB failed: {e}")traceback.print_exc()def _get_conn(self):try:conn = sqlite3.connect(DB_NAME, check_same_thread=False)print("[DB DEBUG] Kết nối SQLite mở thành công.")return connexcept Exception as e:print(f"[DB ERROR] Không thể mở kết nối DB: {e}")traceback.print_exc()raisedef _init_db(self):conn = self._get_conn()13 unmodified linescost INTEGER)''')conn.commit()cursor.execute("SELECT count(*) FROM calls")count = cursor.fetchone()[0]print(f"[DB DEBUG] Số bản ghi hiện tại: {count}")if count == 0:print(" [DB DEBUG] Database trống. Đang nạp 20 bản ghi mẫu...")self._seed_data(cursor)conn.commit()print(" [DB DEBUG] Seed dữ liệu xong.")conn.close()def _seed_data(self, cursor):for item in INITIAL_DATA:try:cursor.execute('''INSERT INTO calls (customer_id, call_id, call_timestamp, duration, intent, sentiment, ai_resolved, upsell, csat, cost)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', (item['customer_id'],item['call_id'],item['call_timestamp'],item['call_duration_seconds'],item['intent'],item['sentiment'],item['ai_resolved'],item['upsell_success'],item['csat'],item['cost_per_call_vnd']))except Exception as e:print(f"[DB ERROR] Seed record {item['call_id']} thất bại: {e}")traceback.print_exc()def get_all_calls(self):try:conn = self._get_conn()cursor = conn.cursor()cursor.execute("SELECT * FROM calls ORDER BY call_timestamp DESC")rows = cursor.fetchall()conn.close()result = []for r in rows:result.append({"id": r[1], # customer_id"time": r[3], # timestamp"dur": r[4], # duration"intent": r[5],"sent": r[6],"ai": bool(r[7]),"upsell": bool(r[8]),"csat": r[9],"cost": r[10]})print(f"[DB DEBUG] Lấy {len(result)} bản ghi thành công.")return resultexcept Exception as e:print(f"[DB ERROR] Lấy tất cả calls thất bại: {e}")traceback.print_exc()return []def add_call(self, customer_id, duration, intent, sentiment, ai_resolved, upsell, cost):try:conn = self._get_conn()cursor = conn.cursor()call_id = f"LIVE_{int(datetime.datetime.now().timestamp())}"timestamp = datetime.datetime.now().isoformat()cursor.execute('''INSERT INTO calls (customer_id, call_id, call_timestamp, duration, intent, sentiment, ai_resolved, upsell, csat, cost)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', (customer_id, call_id, timestamp, duration, intent, sentiment, ai_resolved, upsell, cost['csat'], cost['value']))conn.commit()conn.close()print(f"[DB DEBUG] Thêm call {call_id} cho customer {customer_id} thành công.")except Exception as e:print(f"[DB ERROR] Thêm call thất bại: {e}")traceback.print_exc()def update_call_rating(self, customer_id, stars):try:conn = self._get_conn()cursor = conn.cursor()cursor.execute('''SELECT id FROM callsWHERE customer_id = ?4 unmodified linesif row:cursor.execute('UPDATE calls SET csat = ? WHERE id = ?', (int(stars), row[0]))conn.commit()print(f"[DB DEBUG] Cập nhật CSAT={stars} cho {customer_id}")else:print(f"[DB DEBUG] Không tìm thấy call nào để cập nhật CSAT cho {customer_id}")conn.close()except Exception as e:print(f"[DB ERROR] Update Rating: {e}")traceback.print_exc()# Singleton debugdb = Database()
backend/ai/database.py+93-75