env.py 7.9 KB

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