summaryrefslogtreecommitdiff
path: root/rag/db/documents.py
blob: bdbf5a4e2e39ab1b9ddf07ffc4ec9c5847422330 (plain)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import os
from typing import List
import hashlib
import psycopg
from langchain_core.documents.base import Document

TABLES = """
CREATE TABLE IF NOT EXISTS chunk (
        id serial PRIMARY KEY,
        data text)

CREATE TABLE IF NOT EXISTS document (
        hash text PRIMARY KEY)
"""


class Documents:
    def __init__(self) -> None:
        self.conn = psycopg.connect(
            f"dbname={os.environ['RAG_DB_NAME']} user={os.environ['RAG_USER']}"
        )
        self.__create_content_table()

    def close(self):
        self.conn.close()

    def __create_content_table(self):
        with self.conn.cursor() as cur:
            cur.execute(TABLES)
            self.conn.commit()

    def __hash(self, chunks: List[Document]) -> str:
        document = str.encode("".join([chunk.page_content for chunk in chunks]))
        return hashlib.sha256(document).hexdigest()

    def add_document(self, chunks: List[Document]) -> bool:
        with self.conn.cursor() as cur:
            hash = self.__hash(chunks)
            cur.execute(
                """
                        SELECT * FROM document 
                        WHERE
                        hash = %s
                        """,
                hash,
            )
            exist = cur.fetchone()
            if exist is None:
                cur.execute(
                    """
                            INSERT INTO document 
                            (hash) VALUES 
                            (%s)
                            """,
                    hash,
                )
            self.conn.commit()
        return exist is not None


    def add_chunk(self, data: str):
        with self.conn.cursor() as cur:
            cur.execute(
                """
                        INSERT INTO chunk 
                        (data) VALUES 
                        (%s)
                        """,
                data,
            )
            self.conn.commit()

    def get_chunk(self, id: int):
        with self.conn.cursor() as cur:
            cur.execute(
                """
                        SELECT * FROM chunk 
                        WHERE
                        id = %s
                        """,
                str(id),
            )
            chunk = cur.fetchone()
            self.conn.commit()
        return chunk