Spaces:
Paused
Paused
Download core/config.py from 3SCError404/miracle: direct link, hf CLI and curl.
- Browser
- Download file 7.67 kB
-
https://huggingface.co/spaces/3SCError404/miracle/resolve/main/core/config.py
- Command line
-
hf download hf://spaces/3SCError404/miracle/core/config.py
-
curl -L -o config.py https://huggingface.co/spaces/3SCError404/miracle/resolve/main/core/config.py
7.67 kB
| """ | |
| Application configuration loaded from environment variables. | |
| """ | |
| from pydantic_settings import BaseSettings | |
| from pydantic import field_validator | |
| from functools import lru_cache | |
| from typing import TYPE_CHECKING, List, Optional | |
| if TYPE_CHECKING: | |
| from arq.connections import RedisSettings | |
| class Settings(BaseSettings): | |
| """Application settings from environment variables.""" | |
| # App | |
| APP_NAME: str = "Nexus Master Gateway" | |
| APP_VERSION: str = "1.0.0" | |
| DEBUG: bool = False | |
| API_V1_STR: str = "/api/v1" | |
| ALLOWED_ORIGINS: List[str] = ["http://localhost:5173", "http://localhost:5174", "http://localhost:3000"] | |
| NEXUS_STREAM_BUFFER_SIZE: int = 25 | |
| # Super Admin Configuration | |
| SUPER_ADMIN_EMAIL: str = "admin@3sc.com" | |
| SUPER_ADMIN_NAME: str = "Nexus Super Admin" | |
| # Database | |
| DATABASE_URL: Optional[str] = None | |
| DB_USER: str = "postgres" | |
| DB_PASS: str = "" | |
| DB_HOST: str = "localhost" | |
| DB_PORT: int = 5432 | |
| DB_NAME: str = "customer_portal" | |
| def async_database_url(self) -> str: | |
| url = self.DATABASE_URL.strip() if self.DATABASE_URL else None | |
| if url: | |
| if "supabase.com" in url or "supabase.co" in url: | |
| if ":5432" in url: | |
| url = url.replace(":5432", ":6543") | |
| if url.startswith("postgresql://"): | |
| url = url.replace("postgresql://", "postgresql+psycopg://", 1) | |
| elif url.startswith("postgresql+asyncpg://"): | |
| url = url.replace("postgresql+asyncpg://", "postgresql+psycopg://", 1) | |
| return url | |
| return f"postgresql+psycopg://{self.DB_USER}:{self.DB_PASS}@{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}" | |
| # Redis Configuration | |
| ARQ_REDIS_URL: Optional[str] = None | |
| CACHE_REDIS_URL: Optional[str] = None | |
| LOCAL_REDIS_URL: str = "redis://localhost:6379" | |
| def clean_arq_redis_url(self) -> str: | |
| url = self.ARQ_REDIS_URL or self.LOCAL_REDIS_URL | |
| return url.strip().replace("\n", "").replace("\r", "") | |
| def clean_cache_redis_url(self) -> str: | |
| url = self.CACHE_REDIS_URL or self.LOCAL_REDIS_URL | |
| return url.strip().replace("\n", "").replace("\r", "") | |
| def database_host(self) -> str: | |
| if self.DATABASE_URL: | |
| try: | |
| from urllib.parse import urlparse | |
| parsed = urlparse(self.DATABASE_URL) | |
| return parsed.hostname or "unspecified" | |
| except Exception: | |
| return "error-parsing" | |
| return f"{self.DB_HOST} (WARNING: FALLBACK)" | |
| # JWT Auth | |
| SECRET_KEY: str = "nexus-insecure-default-secret-key-change-it" | |
| ALGORITHM: str = "HS256" | |
| ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 | |
| REFRESH_TOKEN_EXPIRE_DAYS: int = 7 | |
| # AI Settings (Hybrid Strategy: Groq/Anthropic + Ollama) | |
| AI_PROVIDER: str = "groq" | |
| AI_PRIMARY_PROVIDER: str = "groq" | |
| AI_SECONDARY_PROVIDER: str = "ollama" | |
| # AI Models | |
| AI_MODEL: str = "llama-3.3-70b-versatile" | |
| AI_FAST_MODEL: str = "llama-3.1-8b-instant" | |
| AI_BACKUP_PROVIDER_MODEL: str = "llama3.1:8b" | |
| OLLAMA_BASE_URL: str = "http://localhost:11434" | |
| # AI Providers (Task-Specific Routing) | |
| AI_IMAGE_PROVIDER: str = "local" | |
| AI_TEXT_PROVIDER: str = "anthropic" | |
| AI_IMAGE_EMBEDDING_DIM: int = 512 | |
| # Embeddings (Unified to Ollama for a clean environment) | |
| AI_TEXT_EMBEDDING_PROVIDER: str = "ollama" | |
| AI_TEXT_EMBEDDING_MODEL: str = "nomic-embed-text" | |
| AI_TEXT_EMBEDDING_DIM: int = 768 | |
| AI_FORCE_DIMENSION_COMPATIBILITY: bool = True | |
| # Cloud API Keys | |
| ANTHROPIC_API_KEY: Optional[str] = None | |
| GOOGLE_API_KEY: Optional[str] = None | |
| GROQ_API_KEY: Optional[str] = None | |
| # LangGraph Settings | |
| LANGCHAIN_TRACING_V2: bool = False | |
| LANGCHAIN_API_KEY: Optional[str] = None | |
| LANGCHAIN_PROJECT: str = "customer-portal" | |
| # Storage & Logging | |
| STORAGE_BACKEND: str = "local" | |
| UPLOAD_DIR: str = "uploads" | |
| LOG_DIR: str = "logs" | |
| def is_hf_space(self) -> bool: | |
| import os | |
| return os.environ.get("SPACE_ID") is not None or os.environ.get("HF_HUB_OFFLINE") is not None | |
| def effective_upload_dir(self) -> str: | |
| if self.is_hf_space and not self.UPLOAD_DIR.startswith("/data"): | |
| return f"/data/{self.UPLOAD_DIR}" | |
| return self.UPLOAD_DIR | |
| def effective_log_dir(self) -> str: | |
| if self.is_hf_space and not self.LOG_DIR.startswith("/data"): | |
| return f"/data/{self.LOG_DIR}" | |
| return self.LOG_DIR | |
| # S3 Configuration | |
| S3_ACCESS_KEY: Optional[str] = None | |
| S3_SECRET_KEY: Optional[str] = None | |
| S3_BUCKET: Optional[str] = None | |
| S3_REGION: str = "us-east-1" | |
| S3_ENDPOINT_URL: Optional[str] = None | |
| # Notifications | |
| NOTIFICATION_WEBHOOK_URL: Optional[str] = None | |
| RESEND_API_KEY: Optional[str] = None | |
| RESEND_FROM_EMAIL: str = "onboarding@resend.dev" | |
| FRONTEND_URL: str = "http://localhost:3000" | |
| APP_LOGO_URL: str = "https://raw.githubusercontent.com/3sc-ai/nexus-assets/main/logo-dark.png" | |
| def effective_frontend_url(self) -> str: | |
| import os | |
| frontend_url = os.environ.get("FRONTEND_URL") | |
| if frontend_url: | |
| return frontend_url.rstrip('/') | |
| if self.is_hf_space: | |
| space_id = os.environ.get("SPACE_ID") | |
| if space_id: | |
| parts = space_id.split('/') | |
| if len(parts) == 2: | |
| user, name = parts | |
| return f"https://{user}-{name.replace('_', '-')}.hf.space" | |
| return self.FRONTEND_URL.rstrip('/') | |
| def sanitize_ollama_url(cls, v: str) -> str: | |
| if v and v.endswith("/"): | |
| return v.rstrip("/") | |
| return v | |
| class Config: | |
| case_sensitive = True | |
| env_file = ".env" | |
| extra = "ignore" | |
| populate_by_name = True | |
| def get_settings() -> Settings: | |
| s = Settings() | |
| if s.SECRET_KEY.startswith("nexus-insecure-default-secret-key"): | |
| # Raise whenever DEBUG is off — this catches any non-development deployment | |
| # regardless of whether NEXUS_ENV is set correctly. | |
| if not s.DEBUG: | |
| raise RuntimeError( | |
| "FATAL: Insecure SECRET_KEY detected with DEBUG=False. " | |
| "Set a strong SECRET_KEY before deploying." | |
| ) | |
| import warnings | |
| warnings.warn("SECRET_KEY is insecure. Set a strong key before deploying.", stacklevel=2) | |
| return s | |
| def get_redis_settings() -> "RedisSettings": | |
| from arq.connections import RedisSettings | |
| settings = get_settings() | |
| url = settings.clean_arq_redis_url | |
| # arq only accepts redis:// or rediss:// — fall back to local Redis for anything else | |
| # (e.g. Upstash REST URLs like https:// will cause "invalid DSN scheme" at startup) | |
| if not (url.startswith("redis://") or url.startswith("rediss://")): | |
| import warnings | |
| warnings.warn( | |
| f"ARQ_REDIS_URL has unsupported scheme, falling back to LOCAL_REDIS_URL. Got: {url[:40]}", | |
| stacklevel=2, | |
| ) | |
| url = settings.LOCAL_REDIS_URL | |
| use_ssl = url.startswith("rediss://") | |
| rs = RedisSettings.from_dsn(url) | |
| rs.conn_timeout = 60 | |
| rs.conn_retries = 20 | |
| rs.retry_on_timeout = True | |
| import redis.exceptions | |
| rs.retry_on_error = [redis.exceptions.ConnectionError, redis.exceptions.TimeoutError, ConnectionResetError, TimeoutError] | |
| if use_ssl: | |
| rs.ssl = True | |
| rs.ssl_cert_reqs = "none" | |
| return rs | |