documents.py 3.88 KB
Newer Older
1
2
from pydantic import BaseModel, ConfigDict
from typing import List, Optional
Timothy J. Baek's avatar
Timothy J. Baek committed
3
import time
4
import logging
Timothy J. Baek's avatar
Timothy J. Baek committed
5

6
from sqlalchemy import String, Column, BigInteger, Text
Timothy J. Baek's avatar
Timothy J. Baek committed
7

8
from apps.webui.internal.db import Base, Session
Timothy J. Baek's avatar
Timothy J. Baek committed
9
10
11

import json

12
from config import SRC_LOG_LEVELS
Timothy J. Baek's avatar
Timothy J. Baek committed
13

14
15
16
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["MODELS"])

Timothy J. Baek's avatar
Timothy J. Baek committed
17
18
19
20
21
####################
# Documents DB Schema
####################


22
23
class Document(Base):
    __tablename__ = "document"
Timothy J. Baek's avatar
Timothy J. Baek committed
24

25
26
    collection_name = Column(String, primary_key=True)
    name = Column(String, unique=True)
27
28
29
    title = Column(Text)
    filename = Column(Text)
    content = Column(Text, nullable=True)
30
31
    user_id = Column(String)
    timestamp = Column(BigInteger)
Timothy J. Baek's avatar
Timothy J. Baek committed
32
33
34


class DocumentModel(BaseModel):
35
36
    model_config = ConfigDict(from_attributes=True)

Timothy J. Baek's avatar
Timothy J. Baek committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
    collection_name: str
    name: str
    title: str
    filename: str
    content: Optional[str] = None
    user_id: str
    timestamp: int  # timestamp in epoch


####################
# Forms
####################


Timothy J. Baek's avatar
Timothy J. Baek committed
51
52
53
54
55
56
57
58
59
60
class DocumentResponse(BaseModel):
    collection_name: str
    name: str
    title: str
    filename: str
    content: Optional[dict] = None
    user_id: str
    timestamp: int  # timestamp in epoch


Timothy J. Baek's avatar
Timothy J. Baek committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class DocumentUpdateForm(BaseModel):
    name: str
    title: str


class DocumentForm(DocumentUpdateForm):
    collection_name: str
    filename: str
    content: Optional[str] = None


class DocumentsTable:

    def insert_new_doc(
75
        self, user_id: str, form_data: DocumentForm
Timothy J. Baek's avatar
Timothy J. Baek committed
76
77
78
79
80
81
82
83
84
85
    ) -> Optional[DocumentModel]:
        document = DocumentModel(
            **{
                **form_data.model_dump(),
                "user_id": user_id,
                "timestamp": int(time.time()),
            }
        )

        try:
86
87
88
89
90
91
92
93
            result = Document(**document.model_dump())
            Session.add(result)
            Session.commit()
            Session.refresh(result)
            if result:
                return DocumentModel.model_validate(result)
            else:
                return None
Timothy J. Baek's avatar
Timothy J. Baek committed
94
95
96
        except:
            return None

97
    def get_doc_by_name(self, name: str) -> Optional[DocumentModel]:
Timothy J. Baek's avatar
Timothy J. Baek committed
98
        try:
99
100
            document = Session.query(Document).filter_by(name=name).first()
            return DocumentModel.model_validate(document) if document else None
Timothy J. Baek's avatar
Timothy J. Baek committed
101
102
103
        except:
            return None

104
    def get_docs(self) -> List[DocumentModel]:
105
106
107
        return [
            DocumentModel.model_validate(doc) for doc in Session.query(Document).all()
        ]
Timothy J. Baek's avatar
Timothy J. Baek committed
108
109

    def update_doc_by_name(
110
        self, name: str, form_data: DocumentUpdateForm
Timothy J. Baek's avatar
Timothy J. Baek committed
111
112
    ) -> Optional[DocumentModel]:
        try:
113
114
115
116
117
118
119
120
121
            Session.query(Document).filter_by(name=name).update(
                {
                    "title": form_data.title,
                    "name": form_data.name,
                    "timestamp": int(time.time()),
                }
            )
            Session.commit()
            return self.get_doc_by_name(form_data.name)
122
        except Exception as e:
123
            log.exception(e)
Timothy J. Baek's avatar
Timothy J. Baek committed
124
125
            return None

Timothy J. Baek's avatar
Timothy J. Baek committed
126
    def update_doc_content_by_name(
127
        self, name: str, updated: dict
Timothy J. Baek's avatar
Timothy J. Baek committed
128
129
    ) -> Optional[DocumentModel]:
        try:
130
131
132
133
134
135
136
137
138
139
140
141
            doc = self.get_doc_by_name(name)
            doc_content = json.loads(doc.content if doc.content else "{}")
            doc_content = {**doc_content, **updated}

            Session.query(Document).filter_by(name=name).update(
                {
                    "content": json.dumps(doc_content),
                    "timestamp": int(time.time()),
                }
            )
            Session.commit()
            return self.get_doc_by_name(name)
Timothy J. Baek's avatar
Timothy J. Baek committed
142
        except Exception as e:
143
            log.exception(e)
Timothy J. Baek's avatar
Timothy J. Baek committed
144
145
            return None

146
    def delete_doc_by_name(self, name: str) -> bool:
Timothy J. Baek's avatar
Timothy J. Baek committed
147
        try:
148
            Session.query(Document).filter_by(name=name).delete()
Timothy J. Baek's avatar
Timothy J. Baek committed
149
150
151
152
153
            return True
        except:
            return False


154
Documents = DocumentsTable()