File size: 2,000 Bytes
145d6f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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()