Spaces:
Sleeping
Sleeping
Upload memory_db.py with huggingface_hub
Browse files- memory_db.py +43 -0
memory_db.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# memory_db.py - TiDB Database Operations
|
| 2 |
+
import pymysql
|
| 3 |
+
from config import settings
|
| 4 |
+
|
| 5 |
+
class MemoryDB:
|
| 6 |
+
def __init__(self):
|
| 7 |
+
self.connection = pymysql.connect(
|
| 8 |
+
host=settings.TIDB_HOST,
|
| 9 |
+
port=settings.TIDB_PORT,
|
| 10 |
+
user=settings.TIDB_USER,
|
| 11 |
+
password=settings.TIDB_PASSWORD,
|
| 12 |
+
database=settings.TIDB_DATABASE,
|
| 13 |
+
ssl={'ssl': {'ca': ''}} # TiDB SSL
|
| 14 |
+
)
|
| 15 |
+
self.create_tables()
|
| 16 |
+
|
| 17 |
+
def create_tables(self):
|
| 18 |
+
with self.connection.cursor() as cursor:
|
| 19 |
+
cursor.execute("""
|
| 20 |
+
CREATE TABLE IF NOT EXISTS chat_history (
|
| 21 |
+
id INT AUTO_INCREMENT PRIMARY KEY,
|
| 22 |
+
user_input TEXT,
|
| 23 |
+
ai_response MEDIUMTEXT,
|
| 24 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 25 |
+
)
|
| 26 |
+
""")
|
| 27 |
+
self.connection.commit()
|
| 28 |
+
|
| 29 |
+
def save_conversation(self, user_input, ai_response):
|
| 30 |
+
with self.connection.cursor() as cursor:
|
| 31 |
+
cursor.execute(
|
| 32 |
+
"INSERT INTO chat_history (user_input, ai_response) VALUES (%s, %s)",
|
| 33 |
+
(user_input, ai_response)
|
| 34 |
+
)
|
| 35 |
+
self.connection.commit()
|
| 36 |
+
|
| 37 |
+
def get_recent_conversations(self, limit=10):
|
| 38 |
+
with self.connection.cursor() as cursor:
|
| 39 |
+
cursor.execute(
|
| 40 |
+
"SELECT user_input, ai_response FROM chat_history ORDER BY created_at DESC LIMIT %s",
|
| 41 |
+
(limit,)
|
| 42 |
+
)
|
| 43 |
+
return cursor.fetchall()
|