files.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. import logging
  2. import os
  3. import uuid
  4. from pathlib import Path
  5. from typing import Optional
  6. from urllib.parse import quote
  7. from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile, status
  8. from fastapi.responses import FileResponse, StreamingResponse
  9. from open_webui.constants import ERROR_MESSAGES
  10. from open_webui.env import SRC_LOG_LEVELS
  11. from open_webui.models.files import (
  12. FileForm,
  13. FileModel,
  14. FileModelResponse,
  15. Files,
  16. )
  17. from open_webui.routers.retrieval import ProcessFileForm, process_file
  18. from open_webui.routers.audio import transcribe
  19. from open_webui.storage.provider import Storage
  20. from open_webui.utils.auth import get_admin_user, get_verified_user
  21. from pydantic import BaseModel
  22. log = logging.getLogger(__name__)
  23. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  24. router = APIRouter()
  25. ############################
  26. # Upload File
  27. ############################
  28. @router.post("/", response_model=FileModelResponse)
  29. def upload_file(
  30. request: Request,
  31. file: UploadFile = File(...),
  32. user=Depends(get_verified_user),
  33. file_metadata: dict = {},
  34. ):
  35. log.info(f"file.content_type: {file.content_type}")
  36. try:
  37. unsanitized_filename = file.filename
  38. filename = os.path.basename(unsanitized_filename)
  39. # replace filename with uuid
  40. id = str(uuid.uuid4())
  41. name = filename
  42. filename = f"{id}_{filename}"
  43. contents, file_path = Storage.upload_file(file.file, filename)
  44. file_item = Files.insert_new_file(
  45. user.id,
  46. FileForm(
  47. **{
  48. "id": id,
  49. "filename": name,
  50. "path": file_path,
  51. "meta": {
  52. "name": name,
  53. "content_type": file.content_type,
  54. "size": len(contents),
  55. "data": file_metadata,
  56. },
  57. }
  58. ),
  59. )
  60. try:
  61. if file.content_type in [
  62. "audio/mpeg",
  63. "audio/wav",
  64. "audio/ogg",
  65. "audio/x-m4a",
  66. ]:
  67. file_path = Storage.get_file(file_path)
  68. result = transcribe(request, file_path)
  69. process_file(
  70. request,
  71. ProcessFileForm(file_id=id, content=result.get("text", "")),
  72. user=user,
  73. )
  74. else:
  75. process_file(request, ProcessFileForm(file_id=id), user=user)
  76. file_item = Files.get_file_by_id(id=id)
  77. except Exception as e:
  78. log.exception(e)
  79. log.error(f"Error processing file: {file_item.id}")
  80. file_item = FileModelResponse(
  81. **{
  82. **file_item.model_dump(),
  83. "error": str(e.detail) if hasattr(e, "detail") else str(e),
  84. }
  85. )
  86. if file_item:
  87. return file_item
  88. else:
  89. raise HTTPException(
  90. status_code=status.HTTP_400_BAD_REQUEST,
  91. detail=ERROR_MESSAGES.DEFAULT("Error uploading file"),
  92. )
  93. except Exception as e:
  94. log.exception(e)
  95. raise HTTPException(
  96. status_code=status.HTTP_400_BAD_REQUEST,
  97. detail=ERROR_MESSAGES.DEFAULT(e),
  98. )
  99. ############################
  100. # List Files
  101. ############################
  102. @router.get("/", response_model=list[FileModelResponse])
  103. async def list_files(user=Depends(get_verified_user)):
  104. if user.role == "admin":
  105. files = Files.get_files()
  106. else:
  107. files = Files.get_files_by_user_id(user.id)
  108. return files
  109. ############################
  110. # Delete All Files
  111. ############################
  112. @router.delete("/all")
  113. async def delete_all_files(user=Depends(get_admin_user)):
  114. result = Files.delete_all_files()
  115. if result:
  116. try:
  117. Storage.delete_all_files()
  118. except Exception as e:
  119. log.exception(e)
  120. log.error("Error deleting files")
  121. raise HTTPException(
  122. status_code=status.HTTP_400_BAD_REQUEST,
  123. detail=ERROR_MESSAGES.DEFAULT("Error deleting files"),
  124. )
  125. return {"message": "All files deleted successfully"}
  126. else:
  127. raise HTTPException(
  128. status_code=status.HTTP_400_BAD_REQUEST,
  129. detail=ERROR_MESSAGES.DEFAULT("Error deleting files"),
  130. )
  131. ############################
  132. # Get File By Id
  133. ############################
  134. @router.get("/{id}", response_model=Optional[FileModel])
  135. async def get_file_by_id(id: str, user=Depends(get_verified_user)):
  136. file = Files.get_file_by_id(id)
  137. if file and (file.user_id == user.id or user.role == "admin"):
  138. return file
  139. else:
  140. raise HTTPException(
  141. status_code=status.HTTP_404_NOT_FOUND,
  142. detail=ERROR_MESSAGES.NOT_FOUND,
  143. )
  144. ############################
  145. # Get File Data Content By Id
  146. ############################
  147. @router.get("/{id}/data/content")
  148. async def get_file_data_content_by_id(id: str, user=Depends(get_verified_user)):
  149. file = Files.get_file_by_id(id)
  150. if file and (file.user_id == user.id or user.role == "admin"):
  151. return {"content": file.data.get("content", "")}
  152. else:
  153. raise HTTPException(
  154. status_code=status.HTTP_404_NOT_FOUND,
  155. detail=ERROR_MESSAGES.NOT_FOUND,
  156. )
  157. ############################
  158. # Update File Data Content By Id
  159. ############################
  160. class ContentForm(BaseModel):
  161. content: str
  162. @router.post("/{id}/data/content/update")
  163. async def update_file_data_content_by_id(
  164. request: Request, id: str, form_data: ContentForm, user=Depends(get_verified_user)
  165. ):
  166. file = Files.get_file_by_id(id)
  167. if file and (file.user_id == user.id or user.role == "admin"):
  168. try:
  169. process_file(
  170. request,
  171. ProcessFileForm(file_id=id, content=form_data.content),
  172. user=user,
  173. )
  174. file = Files.get_file_by_id(id=id)
  175. except Exception as e:
  176. log.exception(e)
  177. log.error(f"Error processing file: {file.id}")
  178. return {"content": file.data.get("content", "")}
  179. else:
  180. raise HTTPException(
  181. status_code=status.HTTP_404_NOT_FOUND,
  182. detail=ERROR_MESSAGES.NOT_FOUND,
  183. )
  184. ############################
  185. # Get File Content By Id
  186. ############################
  187. @router.get("/{id}/content")
  188. async def get_file_content_by_id(id: str, user=Depends(get_verified_user)):
  189. file = Files.get_file_by_id(id)
  190. if file and (file.user_id == user.id or user.role == "admin"):
  191. try:
  192. file_path = Storage.get_file(file.path)
  193. file_path = Path(file_path)
  194. # Check if the file already exists in the cache
  195. if file_path.is_file():
  196. # Handle Unicode filenames
  197. filename = file.meta.get("name", file.filename)
  198. encoded_filename = quote(filename) # RFC5987 encoding
  199. content_type = file.meta.get("content_type")
  200. filename = file.meta.get("name", file.filename)
  201. encoded_filename = quote(filename)
  202. headers = {}
  203. if content_type == "application/pdf" or filename.lower().endswith(
  204. ".pdf"
  205. ):
  206. headers["Content-Disposition"] = (
  207. f"inline; filename*=UTF-8''{encoded_filename}"
  208. )
  209. content_type = "application/pdf"
  210. elif content_type != "text/plain":
  211. headers["Content-Disposition"] = (
  212. f"attachment; filename*=UTF-8''{encoded_filename}"
  213. )
  214. return FileResponse(file_path, headers=headers, media_type=content_type)
  215. else:
  216. raise HTTPException(
  217. status_code=status.HTTP_404_NOT_FOUND,
  218. detail=ERROR_MESSAGES.NOT_FOUND,
  219. )
  220. except Exception as e:
  221. log.exception(e)
  222. log.error("Error getting file content")
  223. raise HTTPException(
  224. status_code=status.HTTP_400_BAD_REQUEST,
  225. detail=ERROR_MESSAGES.DEFAULT("Error getting file content"),
  226. )
  227. else:
  228. raise HTTPException(
  229. status_code=status.HTTP_404_NOT_FOUND,
  230. detail=ERROR_MESSAGES.NOT_FOUND,
  231. )
  232. @router.get("/{id}/content/html")
  233. async def get_html_file_content_by_id(id: str, user=Depends(get_verified_user)):
  234. file = Files.get_file_by_id(id)
  235. if file and (file.user_id == user.id or user.role == "admin"):
  236. try:
  237. file_path = Storage.get_file(file.path)
  238. file_path = Path(file_path)
  239. # Check if the file already exists in the cache
  240. if file_path.is_file():
  241. log.info(f"file_path: {file_path}")
  242. return FileResponse(file_path)
  243. else:
  244. raise HTTPException(
  245. status_code=status.HTTP_404_NOT_FOUND,
  246. detail=ERROR_MESSAGES.NOT_FOUND,
  247. )
  248. except Exception as e:
  249. log.exception(e)
  250. log.error("Error getting file content")
  251. raise HTTPException(
  252. status_code=status.HTTP_400_BAD_REQUEST,
  253. detail=ERROR_MESSAGES.DEFAULT("Error getting file content"),
  254. )
  255. else:
  256. raise HTTPException(
  257. status_code=status.HTTP_404_NOT_FOUND,
  258. detail=ERROR_MESSAGES.NOT_FOUND,
  259. )
  260. @router.get("/{id}/content/{file_name}")
  261. async def get_file_content_by_id(id: str, user=Depends(get_verified_user)):
  262. file = Files.get_file_by_id(id)
  263. if file and (file.user_id == user.id or user.role == "admin"):
  264. file_path = file.path
  265. # Handle Unicode filenames
  266. filename = file.meta.get("name", file.filename)
  267. encoded_filename = quote(filename) # RFC5987 encoding
  268. headers = {
  269. "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
  270. }
  271. if file_path:
  272. file_path = Storage.get_file(file_path)
  273. file_path = Path(file_path)
  274. # Check if the file already exists in the cache
  275. if file_path.is_file():
  276. return FileResponse(file_path, headers=headers)
  277. else:
  278. raise HTTPException(
  279. status_code=status.HTTP_404_NOT_FOUND,
  280. detail=ERROR_MESSAGES.NOT_FOUND,
  281. )
  282. else:
  283. # File path doesn’t exist, return the content as .txt if possible
  284. file_content = file.content.get("content", "")
  285. file_name = file.filename
  286. # Create a generator that encodes the file content
  287. def generator():
  288. yield file_content.encode("utf-8")
  289. return StreamingResponse(
  290. generator(),
  291. media_type="text/plain",
  292. headers=headers,
  293. )
  294. else:
  295. raise HTTPException(
  296. status_code=status.HTTP_404_NOT_FOUND,
  297. detail=ERROR_MESSAGES.NOT_FOUND,
  298. )
  299. ############################
  300. # Delete File By Id
  301. ############################
  302. @router.delete("/{id}")
  303. async def delete_file_by_id(id: str, user=Depends(get_verified_user)):
  304. file = Files.get_file_by_id(id)
  305. if file and (file.user_id == user.id or user.role == "admin"):
  306. # We should add Chroma cleanup here
  307. result = Files.delete_file_by_id(id)
  308. if result:
  309. try:
  310. Storage.delete_file(file.path)
  311. except Exception as e:
  312. log.exception(e)
  313. log.error("Error deleting files")
  314. raise HTTPException(
  315. status_code=status.HTTP_400_BAD_REQUEST,
  316. detail=ERROR_MESSAGES.DEFAULT("Error deleting files"),
  317. )
  318. return {"message": "File deleted successfully"}
  319. else:
  320. raise HTTPException(
  321. status_code=status.HTTP_400_BAD_REQUEST,
  322. detail=ERROR_MESSAGES.DEFAULT("Error deleting file"),
  323. )
  324. else:
  325. raise HTTPException(
  326. status_code=status.HTTP_404_NOT_FOUND,
  327. detail=ERROR_MESSAGES.NOT_FOUND,
  328. )