2023-05-31 21:42:07 +02:00
|
|
|
import logging
|
|
|
|
import os.path
|
2023-05-31 18:53:14 +02:00
|
|
|
import sqlite3
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
|
|
|
|
def create_database():
|
|
|
|
"""Creates the database."""
|
|
|
|
|
2023-05-31 21:42:07 +02:00
|
|
|
# Check if the database already exists
|
|
|
|
if os.path.exists(Path(__file__).parent / "jarvis-commands-memory.sqlite"):
|
|
|
|
logging.debug("Database already exists, skipping creation")
|
|
|
|
return
|
|
|
|
|
2023-05-31 18:53:14 +02:00
|
|
|
with open(Path(__file__).parent / "create_empty_database.sql", "r") as create_database_script:
|
|
|
|
create_database_script = create_database_script.read()
|
|
|
|
|
|
|
|
db = sqlite3.connect(Path(__file__).parent / "jarvis-commands-memory.sqlite")
|
|
|
|
cursor = db.cursor()
|
|
|
|
cursor.executescript(create_database_script)
|
|
|
|
db.commit()
|
|
|
|
db.close()
|
|
|
|
|
2023-05-31 21:42:07 +02:00
|
|
|
logging.info("Database created")
|
|
|
|
|
2023-05-31 18:53:14 +02:00
|
|
|
|
|
|
|
def do_request(request, args=None):
|
|
|
|
"""Execute SQL request and return result"""
|
|
|
|
|
|
|
|
conn = sqlite3.connect(Path(__file__).parent / "jarvis-commands-memory.sqlite")
|
|
|
|
cursor = conn.cursor()
|
|
|
|
|
|
|
|
if not args:
|
|
|
|
cursor.execute(request)
|
|
|
|
else:
|
|
|
|
cursor.execute(request, args)
|
|
|
|
|
|
|
|
conn.commit()
|
|
|
|
result = cursor.fetchall()
|
|
|
|
conn.close()
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
2023-05-31 21:42:07 +02:00
|
|
|
def add_response(response):
|
|
|
|
"""Add a response to the database"""
|
|
|
|
|
|
|
|
# Check if the response is already in the database
|
|
|
|
request = do_request("SELECT * FROM responses WHERE response=?", (response,))
|
|
|
|
if request:
|
|
|
|
response_id = request[0][0]
|
|
|
|
logging.debug("Response already in database (id: " + str(response_id) + ")")
|
|
|
|
|
|
|
|
# If not, add it
|
|
|
|
else:
|
|
|
|
do_request("INSERT INTO responses (response) VALUES (?)", (response,))
|
|
|
|
response_id = do_request("SELECT * FROM responses WHERE response=?", (response,))[0][0]
|
|
|
|
logging.debug("Response added to database with id " + str(response_id) + ": " + str(response))
|
|
|
|
|
|
|
|
return response_id
|
|
|
|
|
|
|
|
|
|
|
|
def add_command(original_command, simplified_command, response):
|
|
|
|
"""Add a command to the database"""
|
2023-05-31 18:53:14 +02:00
|
|
|
|
2023-05-31 21:42:07 +02:00
|
|
|
do_request("INSERT INTO commands (original_command, simplified_command, response) VALUES (?, ?, ?)",
|
|
|
|
(original_command, simplified_command, add_response(response)))
|
|
|
|
logging.debug("Query added to database: " + original_command + " -> " + response)
|