documents.py 4.19 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
7
from sqlalchemy import String, Column, BigInteger
from sqlalchemy.orm import Session
Timothy J. Baek's avatar
Timothy J. Baek committed
8

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

import json

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

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

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


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

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


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

Timothy J. Baek's avatar
Timothy J. Baek committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
    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
52
53
54
55
56
57
58
59
60
61
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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(
76
        self, user_id: str, form_data: DocumentForm
Timothy J. Baek's avatar
Timothy J. Baek committed
77
78
79
80
81
82
83
84
85
86
    ) -> Optional[DocumentModel]:
        document = DocumentModel(
            **{
                **form_data.model_dump(),
                "user_id": user_id,
                "timestamp": int(time.time()),
            }
        )

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

99
    def get_doc_by_name(self, name: str) -> Optional[DocumentModel]:
Timothy J. Baek's avatar
Timothy J. Baek committed
100
        try:
101
102
103
            with get_session() as db:
                document = db.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
104
105
106
        except:
            return None

107
108
109
    def get_docs(self) -> List[DocumentModel]:
        with get_session() as db:
            return [DocumentModel.model_validate(doc) for doc in db.query(Document).all()]
Timothy J. Baek's avatar
Timothy J. Baek committed
110
111

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

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

                db.query(Document).filter_by(name=name).update(
                    {
                        "content": json.dumps(doc_content),
                        "timestamp": int(time.time()),
                    }
                )
                db.commit()
                return self.get_doc_by_name(name)
Timothy J. Baek's avatar
Timothy J. Baek committed
146
        except Exception as e:
147
            log.exception(e)
Timothy J. Baek's avatar
Timothy J. Baek committed
148
149
            return None

150
    def delete_doc_by_name(self, name: str) -> bool:
Timothy J. Baek's avatar
Timothy J. Baek committed
151
        try:
152
153
            with get_session() as db:
                db.query(Document).filter_by(name=name).delete()
Timothy J. Baek's avatar
Timothy J. Baek committed
154
155
156
157
158
            return True
        except:
            return False


159
Documents = DocumentsTable()