Spaces:
Sleeping
Sleeping
| import sqlite3 | |
| from datetime import datetime | |
| from cryptography.fernet import Fernet | |
| import os | |
| # Inicijalizacija baze i enkripcije | |
| def init_db(): | |
| """Inicijalizira SQLite bazu podataka""" | |
| conn = sqlite3.connect('memory.db') | |
| cursor = conn.cursor() | |
| cursor.execute(''' | |
| CREATE TABLE IF NOT EXISTS chat_history ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| timestamp TEXT, | |
| user_input TEXT, | |
| bot_response TEXT, | |
| backend_mode TEXT | |
| ) | |
| ''') | |
| conn.commit() | |
| conn.close() | |
| # Generiraj ili učitaj enkripcijski ključ | |
| def load_key(): | |
| key_path = "secrets/encryption_key.bin" | |
| if not os.path.exists(key_path): | |
| os.makedirs("secrets", exist_ok=True) | |
| key = Fernet.generate_key() | |
| with open(key_path, "wb") as key_file: | |
| key_file.write(key) | |
| return open(key_path, "rb").read() | |
| key = load_key() | |
| cipher = Fernet(key) | |
| def encrypt_data(data): | |
| """Šifriraj podatke prije pohrane""" | |
| return cipher.encrypt(data.encode()).decode() | |
| def decrypt_data(encrypted_data): | |
| """Dešifriraj podatke prije korištenja""" | |
| return cipher.decrypt(encrypted_data.encode()).decode() | |
| def get_history(limit=1000): | |
| """Dohvati povijest razgovora iz baze""" | |
| conn = sqlite3.connect('memory.db') | |
| cursor = conn.cursor() | |
| cursor.execute("SELECT * FROM chat_history ORDER BY id DESC LIMIT ?", (limit,)) | |
| history = cursor.fetchall() | |
| conn.close() | |
| return history | |
| def save_to_db(user_input, bot_response, mode): | |
| """Spremi razgovor u bazu""" | |
| conn = sqlite3.connect('memory.db') | |
| cursor = conn.cursor() | |
| timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
| cursor.execute( | |
| "INSERT INTO chat_history (timestamp, user_input, bot_response, backend_mode) VALUES (?, ?, ?, ?)", | |
| (timestamp, encrypt_data(user_input), encrypt_data(bot_response), mode) | |
| ) | |
| conn.commit() | |
| conn.close() | |
| # Inicijaliziraj bazu pri uvođenju modula | |
| init_db() |