documents.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. from pydantic import BaseModel, ConfigDict
  2. from typing import List, Optional
  3. import time
  4. import logging
  5. from sqlalchemy import String, Column, BigInteger, Text
  6. from apps.webui.internal.db import Base, Session
  7. import json
  8. from config import SRC_LOG_LEVELS
  9. log = logging.getLogger(__name__)
  10. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  11. ####################
  12. # Documents DB Schema
  13. ####################
  14. class Document(Base):
  15. __tablename__ = "document"
  16. collection_name = Column(String, primary_key=True)
  17. name = Column(String, unique=True)
  18. title = Column(Text)
  19. filename = Column(Text)
  20. content = Column(Text, nullable=True)
  21. user_id = Column(String)
  22. timestamp = Column(BigInteger)
  23. class DocumentModel(BaseModel):
  24. model_config = ConfigDict(from_attributes=True)
  25. collection_name: str
  26. name: str
  27. title: str
  28. filename: str
  29. content: Optional[str] = None
  30. user_id: str
  31. timestamp: int # timestamp in epoch
  32. ####################
  33. # Forms
  34. ####################
  35. class DocumentResponse(BaseModel):
  36. collection_name: str
  37. name: str
  38. title: str
  39. filename: str
  40. content: Optional[dict] = None
  41. user_id: str
  42. timestamp: int # timestamp in epoch
  43. class DocumentUpdateForm(BaseModel):
  44. name: str
  45. title: str
  46. class DocumentForm(DocumentUpdateForm):
  47. collection_name: str
  48. filename: str
  49. content: Optional[str] = None
  50. class DocumentsTable:
  51. def insert_new_doc(
  52. self, user_id: str, form_data: DocumentForm
  53. ) -> Optional[DocumentModel]:
  54. document = DocumentModel(
  55. **{
  56. **form_data.model_dump(),
  57. "user_id": user_id,
  58. "timestamp": int(time.time()),
  59. }
  60. )
  61. try:
  62. result = Document(**document.model_dump())
  63. Session.add(result)
  64. Session.commit()
  65. Session.refresh(result)
  66. if result:
  67. return DocumentModel.model_validate(result)
  68. else:
  69. return None
  70. except:
  71. return None
  72. def get_doc_by_name(self, name: str) -> Optional[DocumentModel]:
  73. try:
  74. document = Session.query(Document).filter_by(name=name).first()
  75. return DocumentModel.model_validate(document) if document else None
  76. except:
  77. return None
  78. def get_docs(self) -> List[DocumentModel]:
  79. return [
  80. DocumentModel.model_validate(doc) for doc in Session.query(Document).all()
  81. ]
  82. def update_doc_by_name(
  83. self, name: str, form_data: DocumentUpdateForm
  84. ) -> Optional[DocumentModel]:
  85. try:
  86. Session.query(Document).filter_by(name=name).update(
  87. {
  88. "title": form_data.title,
  89. "name": form_data.name,
  90. "timestamp": int(time.time()),
  91. }
  92. )
  93. Session.commit()
  94. return self.get_doc_by_name(form_data.name)
  95. except Exception as e:
  96. log.exception(e)
  97. return None
  98. def update_doc_content_by_name(
  99. self, name: str, updated: dict
  100. ) -> Optional[DocumentModel]:
  101. try:
  102. doc = self.get_doc_by_name(name)
  103. doc_content = json.loads(doc.content if doc.content else "{}")
  104. doc_content = {**doc_content, **updated}
  105. Session.query(Document).filter_by(name=name).update(
  106. {
  107. "content": json.dumps(doc_content),
  108. "timestamp": int(time.time()),
  109. }
  110. )
  111. Session.commit()
  112. return self.get_doc_by_name(name)
  113. except Exception as e:
  114. log.exception(e)
  115. return None
  116. def delete_doc_by_name(self, name: str) -> bool:
  117. try:
  118. Session.query(Document).filter_by(name=name).delete()
  119. return True
  120. except:
  121. return False
  122. Documents = DocumentsTable()