File size: 1,775 Bytes
ee20381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import sqlite3
from pathlib import Path


class Database:
    def __init__(self, db_path=None):
        if db_path is None:
            raise ValueError("db_path must be provided")
        self.db_path = db_path
        self.db_file = self.db_path / "cache.db"
        if not self.db_file.exists():
            print("Creating database")
            print("DB_FILE", self.db_file)
            db = sqlite3.connect(self.db_file)
            with open(Path("schema.sql"), "r") as f:
                db.executescript(f.read())
            db.commit()
            db.close()

    def get_db(self):
        db = sqlite3.connect(self.db_file, check_same_thread=False)
        db.row_factory = sqlite3.Row
        return db

    def __enter__(self):
        self.db = self.get_db()
        return self.db

    def __exit__(self, exc_type, exc_value, traceback):
        self.db.close()

    def __call__(self):
        return self

    def insert(self, prompt: str, negative_prompt: str, image_path: str, seed: int):
        with self() as db:
            cursor = db.cursor()
            cursor.execute(
                "INSERT INTO cache (prompt, negative_prompt, image_path, seed) VALUES (?, ?, ?, ?)",
                (prompt, negative_prompt, image_path, seed),
            )
            db.commit()

    def check(self, prompt: str, negative_prompt: str, seed: int):
        with self() as db:
            cursor = db.cursor()
            cursor.execute(
                "SELECT image_path FROM cache WHERE prompt = ? AND negative_prompt = ?  AND seed = ? ORDER BY RANDOM() LIMIT 1",
                (prompt, negative_prompt, seed),
            )
            image_path = cursor.fetchone()
            if image_path:
                return image_path
            return False