env.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. import importlib.metadata
  2. import json
  3. import logging
  4. import os
  5. import pkgutil
  6. import sys
  7. import shutil
  8. from pathlib import Path
  9. import markdown
  10. from bs4 import BeautifulSoup
  11. from open_webui.constants import ERROR_MESSAGES
  12. ####################################
  13. # Load .env file
  14. ####################################
  15. OPEN_WEBUI_DIR = Path(__file__).parent # the path containing this file
  16. print(OPEN_WEBUI_DIR)
  17. BACKEND_DIR = OPEN_WEBUI_DIR.parent # the path containing this file
  18. BASE_DIR = BACKEND_DIR.parent # the path containing the backend/
  19. print(BACKEND_DIR)
  20. print(BASE_DIR)
  21. try:
  22. from dotenv import find_dotenv, load_dotenv
  23. load_dotenv(find_dotenv(str(BASE_DIR / ".env")))
  24. except ImportError:
  25. print("dotenv not installed, skipping...")
  26. DOCKER = os.environ.get("DOCKER", "False").lower() == "true"
  27. # device type embedding models - "cpu" (default), "cuda" (nvidia gpu required) or "mps" (apple silicon) - choosing this right can lead to better performance
  28. USE_CUDA = os.environ.get("USE_CUDA_DOCKER", "false")
  29. if USE_CUDA.lower() == "true":
  30. try:
  31. import torch
  32. assert torch.cuda.is_available(), "CUDA not available"
  33. DEVICE_TYPE = "cuda"
  34. except Exception as e:
  35. cuda_error = (
  36. "Error when testing CUDA but USE_CUDA_DOCKER is true. "
  37. f"Resetting USE_CUDA_DOCKER to false: {e}"
  38. )
  39. os.environ["USE_CUDA_DOCKER"] = "false"
  40. USE_CUDA = "false"
  41. DEVICE_TYPE = "cpu"
  42. else:
  43. DEVICE_TYPE = "cpu"
  44. ####################################
  45. # LOGGING
  46. ####################################
  47. log_levels = ["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"]
  48. GLOBAL_LOG_LEVEL = os.environ.get("GLOBAL_LOG_LEVEL", "").upper()
  49. if GLOBAL_LOG_LEVEL in log_levels:
  50. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL, force=True)
  51. else:
  52. GLOBAL_LOG_LEVEL = "INFO"
  53. log = logging.getLogger(__name__)
  54. log.info(f"GLOBAL_LOG_LEVEL: {GLOBAL_LOG_LEVEL}")
  55. if "cuda_error" in locals():
  56. log.exception(cuda_error)
  57. log_sources = [
  58. "AUDIO",
  59. "COMFYUI",
  60. "CONFIG",
  61. "DB",
  62. "IMAGES",
  63. "MAIN",
  64. "MODELS",
  65. "OLLAMA",
  66. "OPENAI",
  67. "RAG",
  68. "WEBHOOK",
  69. "SOCKET",
  70. ]
  71. SRC_LOG_LEVELS = {}
  72. for source in log_sources:
  73. log_env_var = source + "_LOG_LEVEL"
  74. SRC_LOG_LEVELS[source] = os.environ.get(log_env_var, "").upper()
  75. if SRC_LOG_LEVELS[source] not in log_levels:
  76. SRC_LOG_LEVELS[source] = GLOBAL_LOG_LEVEL
  77. log.info(f"{log_env_var}: {SRC_LOG_LEVELS[source]}")
  78. log.setLevel(SRC_LOG_LEVELS["CONFIG"])
  79. WEBUI_NAME = os.environ.get("WEBUI_NAME", "Open WebUI")
  80. if WEBUI_NAME != "Open WebUI":
  81. WEBUI_NAME += " (Open WebUI)"
  82. WEBUI_URL = os.environ.get("WEBUI_URL", "http://localhost:3000")
  83. WEBUI_FAVICON_URL = "https://openwebui.com/favicon.png"
  84. ####################################
  85. # ENV (dev,test,prod)
  86. ####################################
  87. ENV = os.environ.get("ENV", "dev")
  88. FROM_INIT_PY = os.environ.get("FROM_INIT_PY", "False").lower() == "true"
  89. if FROM_INIT_PY:
  90. PACKAGE_DATA = {"version": importlib.metadata.version("open-webui")}
  91. else:
  92. try:
  93. PACKAGE_DATA = json.loads((BASE_DIR / "package.json").read_text())
  94. except Exception:
  95. PACKAGE_DATA = {"version": "0.0.0"}
  96. VERSION = PACKAGE_DATA["version"]
  97. # Function to parse each section
  98. def parse_section(section):
  99. items = []
  100. for li in section.find_all("li"):
  101. # Extract raw HTML string
  102. raw_html = str(li)
  103. # Extract text without HTML tags
  104. text = li.get_text(separator=" ", strip=True)
  105. # Split into title and content
  106. parts = text.split(": ", 1)
  107. title = parts[0].strip() if len(parts) > 1 else ""
  108. content = parts[1].strip() if len(parts) > 1 else text
  109. items.append({"title": title, "content": content, "raw": raw_html})
  110. return items
  111. try:
  112. changelog_path = BASE_DIR / "CHANGELOG.md"
  113. with open(str(changelog_path.absolute()), "r", encoding="utf8") as file:
  114. changelog_content = file.read()
  115. except Exception:
  116. changelog_content = (pkgutil.get_data("open_webui", "CHANGELOG.md") or b"").decode()
  117. # Convert markdown content to HTML
  118. html_content = markdown.markdown(changelog_content)
  119. # Parse the HTML content
  120. soup = BeautifulSoup(html_content, "html.parser")
  121. # Initialize JSON structure
  122. changelog_json = {}
  123. # Iterate over each version
  124. for version in soup.find_all("h2"):
  125. version_number = version.get_text().strip().split(" - ")[0][1:-1] # Remove brackets
  126. date = version.get_text().strip().split(" - ")[1]
  127. version_data = {"date": date}
  128. # Find the next sibling that is a h3 tag (section title)
  129. current = version.find_next_sibling()
  130. while current and current.name != "h2":
  131. if current.name == "h3":
  132. section_title = current.get_text().lower() # e.g., "added", "fixed"
  133. section_items = parse_section(current.find_next_sibling("ul"))
  134. version_data[section_title] = section_items
  135. # Move to the next element
  136. current = current.find_next_sibling()
  137. changelog_json[version_number] = version_data
  138. CHANGELOG = changelog_json
  139. ####################################
  140. # SAFE_MODE
  141. ####################################
  142. SAFE_MODE = os.environ.get("SAFE_MODE", "false").lower() == "true"
  143. ####################################
  144. # WEBUI_BUILD_HASH
  145. ####################################
  146. WEBUI_BUILD_HASH = os.environ.get("WEBUI_BUILD_HASH", "dev-build")
  147. ####################################
  148. # DATA/FRONTEND BUILD DIR
  149. ####################################
  150. DATA_DIR = Path(os.getenv("DATA_DIR", BACKEND_DIR / "data")).resolve()
  151. if FROM_INIT_PY:
  152. NEW_DATA_DIR = Path(os.getenv("DATA_DIR", OPEN_WEBUI_DIR / "data")).resolve()
  153. NEW_DATA_DIR.mkdir(parents=True, exist_ok=True)
  154. # Check if the data directory exists in the package directory
  155. if DATA_DIR.exists() and DATA_DIR != NEW_DATA_DIR:
  156. log.info(f"Moving {DATA_DIR} to {NEW_DATA_DIR}")
  157. for item in DATA_DIR.iterdir():
  158. dest = NEW_DATA_DIR / item.name
  159. if item.is_dir():
  160. shutil.copytree(item, dest, dirs_exist_ok=True)
  161. else:
  162. shutil.copy2(item, dest)
  163. # And rename the old directory to _open_webui/data
  164. DATA_DIR.rename(DATA_DIR.parent / "_open_webui" / "data")
  165. DATA_DIR = Path(os.getenv("DATA_DIR", OPEN_WEBUI_DIR / "data"))
  166. FONTS_DIR = Path(os.getenv("FONTS_DIR", OPEN_WEBUI_DIR / "static" / "fonts"))
  167. FRONTEND_BUILD_DIR = Path(os.getenv("FRONTEND_BUILD_DIR", BASE_DIR / "build")).resolve()
  168. if FROM_INIT_PY:
  169. FRONTEND_BUILD_DIR = Path(
  170. os.getenv("FRONTEND_BUILD_DIR", OPEN_WEBUI_DIR / "frontend")
  171. ).resolve()
  172. ####################################
  173. # Database
  174. ####################################
  175. # Check if the file exists
  176. if os.path.exists(f"{DATA_DIR}/ollama.db"):
  177. # Rename the file
  178. os.rename(f"{DATA_DIR}/ollama.db", f"{DATA_DIR}/webui.db")
  179. log.info("Database migrated from Ollama-WebUI successfully.")
  180. else:
  181. pass
  182. DATABASE_URL = os.environ.get("DATABASE_URL", f"sqlite:///{DATA_DIR}/webui.db")
  183. # Replace the postgres:// with postgresql://
  184. if "postgres://" in DATABASE_URL:
  185. DATABASE_URL = DATABASE_URL.replace("postgres://", "postgresql://")
  186. RESET_CONFIG_ON_START = (
  187. os.environ.get("RESET_CONFIG_ON_START", "False").lower() == "true"
  188. )
  189. ####################################
  190. # WEBUI_AUTH (Required for security)
  191. ####################################
  192. WEBUI_AUTH = os.environ.get("WEBUI_AUTH", "True").lower() == "true"
  193. WEBUI_AUTH_TRUSTED_EMAIL_HEADER = os.environ.get(
  194. "WEBUI_AUTH_TRUSTED_EMAIL_HEADER", None
  195. )
  196. WEBUI_AUTH_TRUSTED_NAME_HEADER = os.environ.get("WEBUI_AUTH_TRUSTED_NAME_HEADER", None)
  197. ####################################
  198. # WEBUI_SECRET_KEY
  199. ####################################
  200. WEBUI_SECRET_KEY = os.environ.get(
  201. "WEBUI_SECRET_KEY",
  202. os.environ.get(
  203. "WEBUI_JWT_SECRET_KEY", "t0p-s3cr3t"
  204. ), # DEPRECATED: remove at next major version
  205. )
  206. WEBUI_SESSION_COOKIE_SAME_SITE = os.environ.get(
  207. "WEBUI_SESSION_COOKIE_SAME_SITE",
  208. os.environ.get("WEBUI_SESSION_COOKIE_SAME_SITE", "lax"),
  209. )
  210. WEBUI_SESSION_COOKIE_SECURE = os.environ.get(
  211. "WEBUI_SESSION_COOKIE_SECURE",
  212. os.environ.get("WEBUI_SESSION_COOKIE_SECURE", "false").lower() == "true",
  213. )
  214. if WEBUI_AUTH and WEBUI_SECRET_KEY == "":
  215. raise ValueError(ERROR_MESSAGES.ENV_VAR_NOT_FOUND)
  216. ENABLE_WEBSOCKET_SUPPORT = (
  217. os.environ.get("ENABLE_WEBSOCKET_SUPPORT", "True").lower() == "true"
  218. )
  219. WEBSOCKET_MANAGER = os.environ.get("WEBSOCKET_MANAGER", "")
  220. WEBSOCKET_REDIS_URL = os.environ.get("WEBSOCKET_REDIS_URL", "redis://localhost:6379/0")