| """General helper utilities for authentication, policy loading, and file operations.""" |
|
|
| import os |
|
|
| import gradio as gr |
| from dotenv import load_dotenv |
|
|
|
|
| def get_hf_token(oauth_token: gr.OAuthToken | None) -> tuple[str | None, str]: |
| """ |
| Get Hugging Face token from OAuth or .env fallback. |
| |
| Args: |
| oauth_token: Gradio OAuth token from user login, or None |
| |
| Returns: |
| Tuple of (hf_token, status_message) |
| - hf_token: Token string if available, None otherwise |
| - status_message: Warning message if using local .env, empty string otherwise |
| """ |
| print(f"DEBUG: get_hf_token called with oauth_token type: {type(oauth_token)}") |
| |
| if oauth_token is None or (isinstance(oauth_token, str) and oauth_token == "Log in to Hugging Face"): |
| |
| print("DEBUG: oauth_token is None, loading from .env") |
| load_dotenv() |
| hf_token = os.getenv("HF_TOKEN_MLSOC") |
| if hf_token is None: |
| print("DEBUG: HF_TOKEN_MLSOC not found in .env") |
| return None, "" |
| else: |
| print(f"DEBUG: Loaded token from .env, length: {len(hf_token)}, first 4 chars: {hf_token[:4] if len(hf_token) >= 4 else hf_token}") |
| return hf_token, "\n⚠️ Using local .env file for token (not online)" |
| else: |
| |
| print(f"DEBUG: oauth_token is OAuthToken object") |
| token = oauth_token.token |
| print(f"DEBUG: Extracted token from OAuthToken, length: {len(token) if token else 0}, first 4 chars: {token[:4] if token and len(token) >= 4 else (token if token else 'None')}") |
| if not token or not token.strip(): |
| print("DEBUG: OAuthToken.token is empty, falling back to .env") |
| load_dotenv() |
| hf_token = os.getenv("HF_TOKEN_MLSOC") |
| if hf_token: |
| print(f"DEBUG: Loaded token from .env (empty OAuth case), length: {len(hf_token)}, first 4 chars: {hf_token[:4] if len(hf_token) >= 4 else hf_token}") |
| return hf_token, "\n⚠️ Using local .env file for token (not online)" |
| return None, "" |
| return token, "" |
|
|
|
|
| def load_preset_policy(preset_name: str, base_dir: str) -> tuple[str, str]: |
| """Load preset policy from markdown file.""" |
| preset_files = { |
| "Hate Speech Policy": "hate_speech.md", |
| "Violence Policy": "violence.md", |
| "Toxicity Policy": "toxicity.md", |
| } |
| if preset_name in preset_files: |
| policy_path = os.path.join(base_dir, "example_policies", preset_files[preset_name]) |
| try: |
| with open(policy_path, "r") as f: |
| policy_text = f.read() |
| return policy_text, policy_text |
| except FileNotFoundError: |
| return f"*Error: Policy file {preset_files[preset_name]} not found*", "" |
| return "", "" |
|
|
|
|
| def load_policy_from_file(file_path: str) -> tuple[str, str]: |
| """Load policy from uploaded file.""" |
| with open(file_path, "r") as f: |
| content = f.read() |
| return content, content |
|
|
|
|