documents.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. import json
  2. import logging
  3. import time
  4. from typing import Optional
  5. from open_webui.apps.webui.internal.db import Base, get_db
  6. from open_webui.env import SRC_LOG_LEVELS
  7. from pydantic import BaseModel, ConfigDict
  8. from sqlalchemy import BigInteger, Column, String, Text
  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. with get_db() as db:
  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 Exception:
  72. return None
  73. def get_doc_by_name(self, name: str) -> Optional[DocumentModel]:
  74. try:
  75. with get_db() as db:
  76. document = db.query(Document).filter_by(name=name).first()
  77. return DocumentModel.model_validate(document) if document else None
  78. except Exception:
  79. return None
  80. def get_docs(self) -> list[DocumentModel]:
  81. with get_db() as db:
  82. return [
  83. DocumentModel.model_validate(doc) for doc in db.query(Document).all()
  84. ]
  85. def update_doc_by_name(
  86. self, name: str, form_data: DocumentUpdateForm
  87. ) -> Optional[DocumentModel]:
  88. try:
  89. with get_db() as db:
  90. db.query(Document).filter_by(name=name).update(
  91. {
  92. "title": form_data.title,
  93. "name": form_data.name,
  94. "timestamp": int(time.time()),
  95. }
  96. )
  97. db.commit()
  98. return self.get_doc_by_name(form_data.name)
  99. except Exception as e:
  100. log.exception(e)
  101. return None
  102. def update_doc_content_by_name(
  103. self, name: str, updated: dict
  104. ) -> Optional[DocumentModel]:
  105. try:
  106. doc = self.get_doc_by_name(name)
  107. doc_content = json.loads(doc.content if doc.content else "{}")
  108. doc_content = {**doc_content, **updated}
  109. with get_db() as db:
  110. db.query(Document).filter_by(name=name).update(
  111. {
  112. "content": json.dumps(doc_content),
  113. "timestamp": int(time.time()),
  114. }
  115. )
  116. db.commit()
  117. return self.get_doc_by_name(name)
  118. except Exception as e:
  119. log.exception(e)
  120. return None
  121. def delete_doc_by_name(self, name: str) -> bool:
  122. try:
  123. with get_db() as db:
  124. db.query(Document).filter_by(name=name).delete()
  125. db.commit()
  126. return True
  127. except Exception:
  128. return False
  129. Documents = DocumentsTable()