Spaces:
Sleeping
Sleeping
File size: 4,043 Bytes
2dfc473 35db168 2dfc473 35db168 2dfc473 35db168 2dfc473 35db168 2dfc473 35db168 2dfc473 35db168 2dfc473 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | """Environment variable loader with HF Secrets support."""
import os
import logging
from typing import Optional
logger = logging.getLogger(__name__)
class EnvironmentLoader:
"""Loads environment variables with support for HF Secrets."""
@staticmethod
def get_secret(key: str, default: Optional[str] = None) -> str:
"""Get environment variable or secret.
In Hugging Face Spaces, secrets are injected as environment variables.
This function provides a consistent interface for accessing them.
Args:
key: Environment variable name
default: Default value if not found
Returns:
Environment variable value or default
Raises:
ValueError: If required variable is missing and no default provided
"""
value = os.getenv(key, default)
if value is None:
raise ValueError(
f"Required environment variable '{key}' is not set. "
f"Please add it to HF Secrets in your Space settings."
)
if not value:
logger.warning(f"Environment variable '{key}' is empty")
return value
@staticmethod
def validate_secrets() -> bool:
"""Validate that all required secrets are configured.
Returns:
True if all required secrets are present, False otherwise
"""
required_secrets = [
"HUGGINGFACE_TOKEN",
]
dashscope_secrets = [
"DASHSCOPE_API_KEY",
"DASHSCOPE_BASE_URL",
]
optional_secrets = [
"HUGGINGFACE_DATASET",
"MODEL_NAME",
]
all_valid = True
# Check required secrets
for secret in required_secrets:
value = os.getenv(secret)
if not value:
logger.error(f"Missing required secret: {secret}")
all_valid = False
else:
logger.info(f"✓ {secret} configured")
# Check DashScope secrets (without exposing values)
logger.info("\nDashScope Configuration:")
dashscope_valid = True
for secret in dashscope_secrets:
value = os.getenv(secret)
if value:
logger.info(f"✓ {secret} configured (***hidden***)")
else:
logger.warning(f"⚠ {secret} not configured")
dashscope_valid = False
if not dashscope_valid:
logger.warning(
"\n⚠ DashScope credentials not fully configured. "
"They will be set via HF API during Space deployment."
)
# Check optional secrets
for secret in optional_secrets:
value = os.getenv(secret)
if value:
logger.info(f"✓ {secret} configured")
else:
logger.info(f"ℹ {secret} not configured (using default)")
return all_valid
@staticmethod
def get_api_config() -> dict:
"""Get API configuration from environment.
Returns:
Dictionary with API configuration
"""
return {
"openrouter_api_key": os.getenv("DASHSCOPE_API_KEY", ""),
"openrouter_base_url": os.getenv(
"DASHSCOPE_BASE_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1"
),
"model_name": os.getenv("MODEL_NAME", "qwen3.7-plus"),
"huggingface_token": os.getenv("HUGGINGFACE_TOKEN", ""),
"huggingface_dataset": os.getenv(
"HUGGINGFACE_DATASET", "factorstudios/Pipeline"
),
}
# Validate secrets on import
def validate_on_startup():
"""Validate secrets when module is imported."""
if not EnvironmentLoader.validate_secrets():
logger.warning(
"Some secrets are not configured. "
"The application may not work correctly. "
"Please add missing secrets to HF Secrets in your Space settings."
)
|