documents.py 3.9 KB

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