env.py 7.4 KB

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