File size: 1,659 Bytes
aa1c1e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import os
from datetime import datetime
from .db import get_connection


def create_session(session_id, image_path, result_paths):
    conn = get_connection()
    c = conn.cursor()
    c.execute(
        "INSERT INTO sessions (session_id, image_path, result_paths, created_at) VALUES (?, ?, ?, ?)",
        (session_id, image_path, json.dumps(result_paths), datetime.utcnow().isoformat())
    )
    conn.commit()
    conn.close()


def get_session(session_id):
    conn = get_connection()
    c = conn.cursor()
    c.execute("SELECT image_path, result_paths FROM sessions WHERE session_id = ?", (session_id,))
    row = c.fetchone()
    conn.close()

    if row:
        image_path, result_paths_json = row
        return {
            "image_path": image_path,
            "result_paths": json.loads(result_paths_json)
        }
    return None


def delete_session(session_id):
    session = get_session(session_id)
    if session:

        # Delete input image
        if os.path.exists(session["image_path"]):
            os.remove(session["image_path"])

        # Delete output images
        for path in session["result_paths"]:
            if os.path.exists(path):
                os.remove(path)

        # Delete empty temporary folder
        if session["result_paths"]:
            session_dir = os.path.dirname(session["result_paths"][0])
            if os.path.exists(session_dir) and not os.listdir(session_dir):
                os.rmdir(session_dir)

    # Delete from DB
    conn = get_connection()
    c = conn.cursor()
    c.execute("DELETE FROM sessions WHERE session_id = ?", (session_id,))
    conn.commit()
    conn.close()