Spaces:
Runtime error
Runtime error
Download utils.py from farkmuslims/anycoder-1135769a: direct link, hf CLI and curl.
- Browser
- Download file 4.46 kB
-
https://huggingface.co/spaces/farkmuslims/anycoder-1135769a/resolve/main/utils.py
- Command line
-
hf download hf://spaces/farkmuslims/anycoder-1135769a/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/farkmuslims/anycoder-1135769a/resolve/main/utils.py
4.46 kB
| """ | |
| Utility functions for the AI 3D Generator application. | |
| """ | |
| import re | |
| import time | |
| import hashlib | |
| import base64 | |
| from typing import Tuple, Optional, Dict, Any | |
| import streamlit as st | |
| def validate_api_key(service_id: str, api_key: str) -> Tuple[bool, str]: | |
| """ | |
| Validate an API key format for a specific service. | |
| In production, this would make actual API calls to verify. | |
| Returns: | |
| Tuple of (is_valid: bool, message: str) | |
| """ | |
| if not api_key or len(api_key) < 10: | |
| return False, "API key too short" | |
| # Basic format validation based on service | |
| validators = { | |
| "meshy": lambda k: len(k) >= 32 and k.startswith("ms-"), | |
| "sloyd": lambda k: len(k) >= 24, | |
| "tripo3d": lambda k: len(k) >= 32, | |
| "rodin": lambda k: len(k) >= 40, | |
| "csm": lambda k: len(k) >= 32 | |
| } | |
| validator = validators.get(service_id, lambda k: len(k) >= 20) | |
| if not validator(api_key): | |
| return False, f"Invalid format for {service_id} API key" | |
| # Mock validation - in production, make actual API test call | |
| # This simulates network delay | |
| time.sleep(0.5) | |
| return True, "API key validated successfully" | |
| def format_file_size(size_mb: float) -> str: | |
| """Format file size for display.""" | |
| if size_mb < 1: | |
| return f"{size_mb * 1024:.1f} KB" | |
| elif size_mb < 1024: | |
| return f"{size_mb:.2f} MB" | |
| else: | |
| return f"{size_mb / 1024:.2f} GB" | |
| def create_download_link(data: bytes, filename: str, text: str = "Download") -> str: | |
| """Create a download link for binary data.""" | |
| b64 = base64.b64encode(data).decode() | |
| return f'<a href="data:application/octet-stream;base64,{b64}" download="{filename}">{text}</a>' | |
| def estimate_generation_time( | |
| keyword_count: int, | |
| variations: int = 1, | |
| polycount: str = "10K" | |
| ) -> str: | |
| """Estimate generation time based on parameters.""" | |
| base_time = 30 # seconds | |
| # Keyword complexity factor | |
| keyword_factor = min(keyword_count * 2, 30) | |
| # Variations multiplier | |
| var_multiplier = variations * 0.8 | |
| # Quality factor | |
| quality_factors = {"1K": 0.5, "5K": 0.8, "10K": 1.0, "25K": 1.5, "50K": 2.0, "100K": 3.0} | |
| quality_factor = quality_factors.get(polycount, 1.0) | |
| total_seconds = (base_time + keyword_factor) * var_multiplier * quality_factor | |
| if total_seconds < 60: | |
| return f"{int(total_seconds)} seconds" | |
| elif total_seconds < 3600: | |
| return f"{int(total_seconds / 60)} minutes" | |
| else: | |
| return f"{total_seconds / 3600:.1f} hours" | |
| def sanitize_prompt(prompt: str) -> str: | |
| """Clean and sanitize user prompt input.""" | |
| # Remove excessive whitespace | |
| cleaned = " ".join(prompt.split()) | |
| # Remove potentially harmful characters | |
| cleaned = re.sub(r'[<>{}[\]]', '', cleaned) | |
| # Truncate if too long | |
| return cleaned[:1000] | |
| def generate_model_hash(prompt: str, settings: Dict[str, Any]) -> str: | |
| """Generate a unique hash for a generation request.""" | |
| hash_input = f"{prompt}:{sorted(settings.items())}:{time.time()}" | |
| return hashlib.md5(hash_input.encode()).hexdigest()[:12] | |
| def mock_api_call( | |
| service: str, | |
| endpoint: str, | |
| payload: Dict[str, Any], | |
| api_key: str | |
| ) -> Dict[str, Any]: | |
| """ | |
| Mock API call for demonstration. | |
| In production, this would make actual HTTP requests. | |
| """ | |
| # Simulate network delay | |
| time.sleep(0.5) | |
| return { | |
| "status": "success", | |
| "job_id": f"job_{int(time.time())}_{hash(api_key) % 10000}", | |
| "estimated_time": 30, | |
| "result_url": f"https://api.example.com/results/{int(time.time())}" | |
| } | |
| def get_service_status(api_keys: Dict[str, str]) -> Dict[str, bool]: | |
| """Check which services have configured API keys.""" | |
| return { | |
| service_id: service_id in api_keys | |
| for service_id in ["meshy", "sloyd", "tripo3d", "rodin", "csm"] | |
| } | |
| def format_keywords(keywords: list) -> str: | |
| """Format keyword list for display.""" | |
| if not keywords: | |
| return "No keywords" | |
| return ", ".join(f'"{kw}"' for kw in keywords) | |
| def parse_variation_settings(settings_str: str) -> Dict[str, Any]: | |
| """Parse variation settings from string input.""" | |
| settings = {} | |
| pairs = settings_str.split(",") | |
| for pair in pairs: | |
| if "=" in pair: | |
| key, value = pair.split("=", 1) | |
| settings[key.strip()] = value.strip() | |
| return settings |