files.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import logging
  2. import time
  3. from typing import Optional
  4. from open_webui.apps.webui.internal.db import Base, JSONField, get_db
  5. from open_webui.env import SRC_LOG_LEVELS
  6. from pydantic import BaseModel, ConfigDict
  7. from sqlalchemy import BigInteger, Column, String, Text, JSON
  8. log = logging.getLogger(__name__)
  9. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  10. ####################
  11. # Files DB Schema
  12. ####################
  13. class File(Base):
  14. __tablename__ = "file"
  15. id = Column(String, primary_key=True)
  16. user_id = Column(String)
  17. hash = Column(String)
  18. filename = Column(Text)
  19. data = Column(JSON)
  20. meta = Column(JSONField)
  21. created_at = Column(BigInteger)
  22. updated_at = Column(BigInteger)
  23. class FileModel(BaseModel):
  24. model_config = ConfigDict(from_attributes=True)
  25. id: str
  26. user_id: str
  27. hash: str
  28. filename: str
  29. data: dict
  30. meta: dict
  31. created_at: int # timestamp in epoch
  32. updated_at: int # timestamp in epoch
  33. ####################
  34. # Forms
  35. ####################
  36. class FileModelResponse(BaseModel):
  37. id: str
  38. user_id: str
  39. hash: str
  40. filename: str
  41. data: dict
  42. meta: dict
  43. created_at: int # timestamp in epoch
  44. updated_at: int # timestamp in epoch
  45. class FileForm(BaseModel):
  46. id: str
  47. filename: str
  48. meta: dict = {}
  49. class FilesTable:
  50. def insert_new_file(self, user_id: str, form_data: FileForm) -> Optional[FileModel]:
  51. with get_db() as db:
  52. file = FileModel(
  53. **{
  54. **form_data.model_dump(),
  55. "user_id": user_id,
  56. "created_at": int(time.time()),
  57. "updated_at": int(time.time()),
  58. }
  59. )
  60. try:
  61. result = File(**file.model_dump())
  62. db.add(result)
  63. db.commit()
  64. db.refresh(result)
  65. if result:
  66. return FileModel.model_validate(result)
  67. else:
  68. return None
  69. except Exception as e:
  70. print(f"Error creating tool: {e}")
  71. return None
  72. def get_file_by_id(self, id: str) -> Optional[FileModel]:
  73. with get_db() as db:
  74. try:
  75. file = db.get(File, id)
  76. return FileModel.model_validate(file)
  77. except Exception:
  78. return None
  79. def get_files(self) -> list[FileModel]:
  80. with get_db() as db:
  81. return [FileModel.model_validate(file) for file in db.query(File).all()]
  82. def get_files_by_ids(self, ids: list[str]) -> list[FileModel]:
  83. with get_db() as db:
  84. return [
  85. FileModel.model_validate(file)
  86. for file in db.query(File).filter(File.id.in_(ids)).all()
  87. ]
  88. def get_files_by_user_id(self, user_id: str) -> list[FileModel]:
  89. with get_db() as db:
  90. return [
  91. FileModel.model_validate(file)
  92. for file in db.query(File).filter_by(user_id=user_id).all()
  93. ]
  94. def update_files_data_by_id(self, id: str, data: dict) -> Optional[FileModel]:
  95. with get_db() as db:
  96. try:
  97. file = db.query(File).filter_by(id=id).first()
  98. file.data = {**file.data, **data}
  99. db.commit()
  100. return FileModel.model_validate(file)
  101. except Exception:
  102. return None
  103. def update_files_metadata_by_id(self, id: str, meta: dict) -> Optional[FileModel]:
  104. with get_db() as db:
  105. try:
  106. file = db.query(File).filter_by(id=id).first()
  107. file.meta = {**file.meta, **meta}
  108. db.commit()
  109. return FileModel.model_validate(file)
  110. except Exception:
  111. return None
  112. def delete_file_by_id(self, id: str) -> bool:
  113. with get_db() as db:
  114. try:
  115. db.query(File).filter_by(id=id).delete()
  116. db.commit()
  117. return True
  118. except Exception:
  119. return False
  120. def delete_all_files(self) -> bool:
  121. with get_db() as db:
  122. try:
  123. db.query(File).delete()
  124. db.commit()
  125. return True
  126. except Exception:
  127. return False
  128. Files = FilesTable()