Download src/utils/base_utils.py from Pteclub/Mock-app: direct link, hf CLI and curl.
- Browser
- Download file 5.9 kB
-
https://huggingface.co/spaces/Pteclub/Mock-app/resolve/main/src/utils/base_utils.py
- Command line
-
hf download hf://spaces/Pteclub/Mock-app/src/utils/base_utils.py
-
curl -L -o base_utils.py https://huggingface.co/spaces/Pteclub/Mock-app/resolve/main/src/utils/base_utils.py
5.9 kB
| """ | |
| src/utils/base_utils.py | |
| Shared utilities: Groq client, Gemini client, JSON cleaner, topic sampler. | |
| No UI concerns — pure back-end helpers. | |
| """ | |
| import os | |
| import json | |
| import logging | |
| import re | |
| import random | |
| from typing import Optional | |
| from groq import Groq | |
| import httpx | |
| from .questions import parse_groq_response # noqa: F401 (re-exported for callers) | |
| # ----------------------------------------------------------- | |
| # Logging | |
| # ----------------------------------------------------------- | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # ----------------------------------------------------------- | |
| # Custom Exception | |
| # ----------------------------------------------------------- | |
| class ModelError(Exception): | |
| """Raised when a model client fails to initialise or returns bad output.""" | |
| pass | |
| # ----------------------------------------------------------- | |
| # Groq Client | |
| # ----------------------------------------------------------- | |
| def get_groq_client() -> Groq: | |
| """Initialise and return a Groq client.""" | |
| api_key = os.getenv("GROQ_API_KEY") | |
| if not api_key: | |
| logger.error("GROQ_API_KEY is missing from environment variables.") | |
| raise ModelError("GROQ_API_KEY environment variable not set") | |
| try: | |
| # Use a plain httpx.Client to avoid proxy-parameter incompatibilities. | |
| http_client = httpx.Client() | |
| return Groq(api_key=api_key, http_client=http_client) | |
| except Exception as e: | |
| logger.error("Failed to initialise Groq client: %s", e) | |
| raise ModelError(f"Failed to initialise Groq client: {e}") from e | |
| # ----------------------------------------------------------- | |
| # Gemini Client | |
| # ----------------------------------------------------------- | |
| def get_gemini_client(): | |
| """ | |
| Initialise and return a Gemini 1.5 Flash generative model instance. | |
| Returns None (with a logged error) if the package is missing or the | |
| API key is not set — callers should handle the None case gracefully. | |
| """ | |
| try: | |
| import google.generativeai as genai | |
| except ImportError: | |
| logger.error( | |
| "google-generativeai is not installed. " | |
| "Run: pip install google-generativeai" | |
| ) | |
| return None | |
| api_key = os.getenv("GEMINI_API_KEY") | |
| if not api_key: | |
| logger.error("GEMINI_API_KEY not found in environment.") | |
| return None | |
| try: | |
| genai.configure(api_key=api_key) | |
| model = genai.GenerativeModel("gemini-1.5-flash") | |
| logger.info("Gemini 1.5 Flash client initialised.") | |
| return model | |
| except Exception as e: | |
| logger.error("Failed to initialise Gemini client: %s", e) | |
| return None | |
| # ----------------------------------------------------------- | |
| # JSON Cleaning Utility | |
| # ----------------------------------------------------------- | |
| def clean_json_content(content: str) -> str: | |
| """ | |
| Attempt to repair and normalise LLM-produced JSON. | |
| Returns a valid JSON string (output of json.dumps) or raises | |
| ModelError if the content cannot be salvaged. | |
| """ | |
| original = content | |
| try: | |
| content = content.strip() | |
| # Strip code fences | |
| content = re.sub(r"^```json", "", content, flags=re.IGNORECASE) | |
| content = re.sub(r"^```", "", content) | |
| content = re.sub(r"```$", "", content) | |
| content = content.strip() | |
| # Quick parse — succeeds for well-formed output | |
| try: | |
| return json.dumps(json.loads(content)) | |
| except json.JSONDecodeError: | |
| pass | |
| # Normalise curly / smart quotes | |
| content = ( | |
| content | |
| .replace("\u201c", '"').replace("\u201d", '"') | |
| .replace("\u2018", "'").replace("\u2019", "'") | |
| ) | |
| # Single → double quotes (blunt but usually effective for LLM output) | |
| content = re.sub(r"'", '"', content) | |
| # Strip trailing commas before ] or } | |
| content = re.sub(r",\s*([}\]])", r"\1", content) | |
| # Ensure outermost braces | |
| if not content.startswith("{"): | |
| content = "{" + content | |
| if not content.endswith("}"): | |
| content += "}" | |
| # Collapse excess whitespace | |
| content = re.sub(r"\s+", " ", content) | |
| return json.dumps(json.loads(content)) | |
| except Exception as e: | |
| logger.error( | |
| "JSON cleaning failed: %s\nOriginal:\n%s\nAfter cleaning:\n%s", | |
| e, original, content, | |
| ) | |
| raise ModelError(f"Failed to clean JSON content: {e}") from e | |
| # ----------------------------------------------------------- | |
| # Topic Sampler | |
| # ----------------------------------------------------------- | |
| _TOPICS = [ | |
| # Academic / general | |
| "environmental conservation", | |
| "digital technology", | |
| "global education", | |
| "public health", | |
| "cultural diversity", | |
| "urban development", | |
| "scientific research", | |
| "economic growth", | |
| "social media impact", | |
| "renewable energy", | |
| "artificial intelligence", | |
| "climate change", | |
| "online learning", | |
| "transportation systems", | |
| "workplace communication", | |
| "international trade", | |
| "mental wellbeing", | |
| "sustainable living", | |
| "innovation trends", | |
| "community development", | |
| # Additional variety | |
| "technology and innovation", | |
| "health and wellness", | |
| "education systems", | |
| "space exploration", | |
| "cultural heritage", | |
| "modern transportation", | |
| "digital communication", | |
| "scientific discoveries", | |
| "global economics", | |
| ] | |
| def get_random_topic() -> str: | |
| """Return a random academic topic string.""" | |
| return random.choice(_TOPICS) |