|
| 1 | +""" |
| 2 | +AI description generator for GitCanvas GitHub stats. |
| 3 | +Generates short, theme-aware textual summaries with OpenAI/Gemini and a safe fallback. |
| 4 | +""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import re |
| 9 | +from typing import Any |
| 10 | + |
| 11 | +from config.settings import get_settings |
| 12 | +from utils.logger import setup_logger |
| 13 | + |
| 14 | +try: |
| 15 | + import google.generativeai as genai # type: ignore |
| 16 | + |
| 17 | + _HAS_GENAI = True |
| 18 | +except Exception: |
| 19 | + genai = None |
| 20 | + _HAS_GENAI = False |
| 21 | + |
| 22 | +try: |
| 23 | + from openai import OpenAI |
| 24 | +except Exception: |
| 25 | + OpenAI = None |
| 26 | + |
| 27 | + |
| 28 | +logger = setup_logger(__name__) |
| 29 | + |
| 30 | + |
| 31 | +SUPPORTED_TONES = {"professional", "funny", "creative"} |
| 32 | + |
| 33 | + |
| 34 | +_cfg = get_settings() |
| 35 | +OPENAI_API_KEY = _cfg.openai_api_key_value() |
| 36 | +GEMINI_API_KEY = _cfg.gemini_api_key_value() |
| 37 | + |
| 38 | +openai_client = None |
| 39 | +if OPENAI_API_KEY and OpenAI: |
| 40 | + try: |
| 41 | + openai_client = OpenAI(api_key=OPENAI_API_KEY) |
| 42 | + except Exception as exc: |
| 43 | + logger.warning(f"Failed to initialize OpenAI client: {exc}") |
| 44 | + |
| 45 | +if GEMINI_API_KEY and _HAS_GENAI: |
| 46 | + try: |
| 47 | + genai.configure(api_key=GEMINI_API_KEY) |
| 48 | + except Exception as exc: |
| 49 | + logger.warning(f"Failed to configure Gemini client: {exc}") |
| 50 | + |
| 51 | + |
| 52 | +def _normalize_tone(tone: str | None) -> str: |
| 53 | + if not tone: |
| 54 | + return "professional" |
| 55 | + normalized = tone.strip().lower() |
| 56 | + if normalized not in SUPPORTED_TONES: |
| 57 | + return "professional" |
| 58 | + return normalized |
| 59 | + |
| 60 | + |
| 61 | +def _normalize_top_languages(raw_languages: Any) -> list[str]: |
| 62 | + languages: list[str] = [] |
| 63 | + |
| 64 | + if not isinstance(raw_languages, list): |
| 65 | + return languages |
| 66 | + |
| 67 | + for entry in raw_languages: |
| 68 | + if isinstance(entry, dict): |
| 69 | + name = entry.get("name") |
| 70 | + if isinstance(name, str) and name.strip(): |
| 71 | + languages.append(name.strip()) |
| 72 | + elif isinstance(entry, (list, tuple)) and entry: |
| 73 | + name = str(entry[0]).strip() |
| 74 | + if name: |
| 75 | + languages.append(name) |
| 76 | + |
| 77 | + return languages[:5] |
| 78 | + |
| 79 | + |
| 80 | +def _active_contribution_days(contributions: Any) -> int: |
| 81 | + if not isinstance(contributions, list): |
| 82 | + return 0 |
| 83 | + |
| 84 | + active_days = 0 |
| 85 | + for item in contributions: |
| 86 | + if isinstance(item, dict) and int(item.get("count", 0) or 0) > 0: |
| 87 | + active_days += 1 |
| 88 | + return active_days |
| 89 | + |
| 90 | + |
| 91 | +def _clean_text(value: str) -> str: |
| 92 | + cleaned = value.strip().strip('"').strip("'") |
| 93 | + cleaned = re.sub(r"\s+", " ", cleaned).strip() |
| 94 | + return cleaned |
| 95 | + |
| 96 | + |
| 97 | +def create_description_prompt(profile_data: dict[str, Any], theme_name: str, tone: str = "professional") -> str: |
| 98 | + """Create a compact prompt describing profile stats with theme context.""" |
| 99 | + normalized_tone = _normalize_tone(tone) |
| 100 | + |
| 101 | + username = profile_data.get("username", "developer") |
| 102 | + commits = int(profile_data.get("total_commits", 0) or 0) |
| 103 | + repos = int(profile_data.get("public_repos", 0) or 0) |
| 104 | + followers = int(profile_data.get("followers", 0) or 0) |
| 105 | + stars = int(profile_data.get("total_stars", 0) or 0) |
| 106 | + |
| 107 | + languages = _normalize_top_languages(profile_data.get("top_languages", [])) |
| 108 | + languages_str = ", ".join(languages[:3]) if languages else "multiple languages" |
| 109 | + |
| 110 | + active_days = _active_contribution_days(profile_data.get("contributions", [])) |
| 111 | + |
| 112 | + tone_guidelines = { |
| 113 | + "professional": "Use a clear, polished and insightful tone.", |
| 114 | + "funny": "Use light and friendly humor without being rude.", |
| 115 | + "creative": "Use vivid and imaginative wording while staying readable.", |
| 116 | + } |
| 117 | + |
| 118 | + return f""" |
| 119 | +Write a short GitHub profile description in 3 to 4 sentences. |
| 120 | +
|
| 121 | +Username: {username} |
| 122 | +Theme selected in app: {theme_name} |
| 123 | +Total commits: {commits} |
| 124 | +Public repositories: {repos} |
| 125 | +Followers: {followers} |
| 126 | +Total stars: {stars} |
| 127 | +Top languages: {languages_str} |
| 128 | +Active contribution days (in loaded dataset): {active_days} |
| 129 | +Tone: {normalized_tone} |
| 130 | +
|
| 131 | +Rules: |
| 132 | +- Mention the selected theme naturally. |
| 133 | +- Include at least two concrete stats from above. |
| 134 | +- Keep it under 95 words. |
| 135 | +- Avoid bullet points and hashtags. |
| 136 | +- {tone_guidelines[normalized_tone]} |
| 137 | +Return only the description text. |
| 138 | +""".strip() |
| 139 | + |
| 140 | + |
| 141 | +def generate_description_with_openai(profile_data: dict[str, Any], theme_name: str, tone: str = "professional") -> str: |
| 142 | + """Generate description via OpenAI Chat Completions.""" |
| 143 | + if not openai_client: |
| 144 | + raise ValueError("OpenAI is not configured") |
| 145 | + |
| 146 | + prompt = create_description_prompt(profile_data, theme_name, tone) |
| 147 | + normalized_tone = _normalize_tone(tone) |
| 148 | + |
| 149 | + temperature = { |
| 150 | + "professional": 0.5, |
| 151 | + "funny": 0.8, |
| 152 | + "creative": 0.9, |
| 153 | + }[normalized_tone] |
| 154 | + |
| 155 | + response = openai_client.chat.completions.create( |
| 156 | + model="gpt-3.5-turbo", |
| 157 | + messages=[ |
| 158 | + { |
| 159 | + "role": "system", |
| 160 | + "content": "You summarize GitHub profiles accurately and engagingly.", |
| 161 | + }, |
| 162 | + { |
| 163 | + "role": "user", |
| 164 | + "content": prompt, |
| 165 | + }, |
| 166 | + ], |
| 167 | + max_tokens=180, |
| 168 | + temperature=temperature, |
| 169 | + ) |
| 170 | + |
| 171 | + content = response.choices[0].message.content or "" |
| 172 | + cleaned = _clean_text(content) |
| 173 | + if not cleaned: |
| 174 | + raise ValueError("OpenAI returned empty description") |
| 175 | + return cleaned |
| 176 | + |
| 177 | + |
| 178 | +def generate_description_with_gemini(profile_data: dict[str, Any], theme_name: str, tone: str = "professional") -> str: |
| 179 | + """Generate description via Gemini.""" |
| 180 | + if not GEMINI_API_KEY: |
| 181 | + raise ValueError("Gemini API key not configured") |
| 182 | + if not _HAS_GENAI: |
| 183 | + raise ImportError("google.generativeai is not installed") |
| 184 | + |
| 185 | + prompt = create_description_prompt(profile_data, theme_name, tone) |
| 186 | + normalized_tone = _normalize_tone(tone) |
| 187 | + |
| 188 | + temperature = { |
| 189 | + "professional": 0.5, |
| 190 | + "funny": 0.8, |
| 191 | + "creative": 0.9, |
| 192 | + }[normalized_tone] |
| 193 | + |
| 194 | + generation_config = genai.types.GenerationConfig( |
| 195 | + temperature=temperature, |
| 196 | + max_output_tokens=180, |
| 197 | + ) |
| 198 | + |
| 199 | + last_error: Exception | None = None |
| 200 | + for model_name in ("gemini-1.5-flash", "gemini-1.5-flash-latest", "gemini-pro"): |
| 201 | + try: |
| 202 | + model = genai.GenerativeModel(model_name) |
| 203 | + response = model.generate_content(prompt, generation_config=generation_config) |
| 204 | + content = getattr(response, "text", "") or "" |
| 205 | + cleaned = _clean_text(content) |
| 206 | + if cleaned: |
| 207 | + return cleaned |
| 208 | + except Exception as exc: |
| 209 | + last_error = exc |
| 210 | + |
| 211 | + raise ValueError(f"Gemini returned empty description or unsupported model. Last error: {last_error}") |
| 212 | + |
| 213 | + |
| 214 | +def get_fallback_description(profile_data: dict[str, Any], theme_name: str, tone: str = "professional") -> str: |
| 215 | + """Return a deterministic local fallback description when LLM calls fail.""" |
| 216 | + normalized_tone = _normalize_tone(tone) |
| 217 | + |
| 218 | + username = profile_data.get("username", "This developer") |
| 219 | + commits = int(profile_data.get("total_commits", 0) or 0) |
| 220 | + repos = int(profile_data.get("public_repos", 0) or 0) |
| 221 | + followers = int(profile_data.get("followers", 0) or 0) |
| 222 | + stars = int(profile_data.get("total_stars", 0) or 0) |
| 223 | + |
| 224 | + languages = _normalize_top_languages(profile_data.get("top_languages", [])) |
| 225 | + primary_lang = languages[0] if languages else "multiple languages" |
| 226 | + |
| 227 | + if normalized_tone == "funny": |
| 228 | + return ( |
| 229 | + f"{username} is running a {theme_name} coding universe where {commits} commits and " |
| 230 | + f"{repos} repos keep the plot moving. Their favorite tool seems to be {primary_lang}, " |
| 231 | + f"with {stars} stars and {followers} followers cheering from the sidelines." |
| 232 | + ) |
| 233 | + |
| 234 | + if normalized_tone == "creative": |
| 235 | + return ( |
| 236 | + f"In the {theme_name} palette, {username}'s GitHub story glows through {commits} commits " |
| 237 | + f"and {repos} public repositories. {primary_lang} leads the rhythm, while {stars} stars and " |
| 238 | + f"{followers} followers reflect the reach of their craft." |
| 239 | + ) |
| 240 | + |
| 241 | + return ( |
| 242 | + f"{username} shows consistent development activity with {commits} commits across {repos} public repositories. " |
| 243 | + f"Using {primary_lang} as a key language, the profile has gathered {stars} stars and {followers} followers. " |
| 244 | + f"The selected {theme_name} theme highlights this contribution pattern clearly." |
| 245 | + ) |
| 246 | + |
| 247 | + |
| 248 | +def generate_github_description( |
| 249 | + profile_data: dict[str, Any], |
| 250 | + theme_name: str, |
| 251 | + tone: str = "professional", |
| 252 | +) -> dict[str, Any]: |
| 253 | + """ |
| 254 | + Generate a theme-aware GitHub description with resilient provider fallback. |
| 255 | +
|
| 256 | + Returns metadata containing source provider and final description text. |
| 257 | + """ |
| 258 | + normalized_tone = _normalize_tone(tone) |
| 259 | + description_text: str | None = None |
| 260 | + source = "fallback" |
| 261 | + |
| 262 | + try: |
| 263 | + if openai_client: |
| 264 | + try: |
| 265 | + description_text = generate_description_with_openai(profile_data, theme_name, normalized_tone) |
| 266 | + source = "openai" |
| 267 | + except Exception as exc: |
| 268 | + logger.warning(f"OpenAI description generation failed: {exc}") |
| 269 | + |
| 270 | + if not description_text and GEMINI_API_KEY and _HAS_GENAI: |
| 271 | + try: |
| 272 | + description_text = generate_description_with_gemini(profile_data, theme_name, normalized_tone) |
| 273 | + source = "gemini" |
| 274 | + except Exception as exc: |
| 275 | + logger.warning(f"Gemini description generation failed: {exc}") |
| 276 | + |
| 277 | + if not description_text: |
| 278 | + description_text = get_fallback_description(profile_data, theme_name, normalized_tone) |
| 279 | + source = "fallback" |
| 280 | + |
| 281 | + return { |
| 282 | + "success": True, |
| 283 | + "description": description_text, |
| 284 | + "source": source, |
| 285 | + "tone": normalized_tone, |
| 286 | + "theme": theme_name, |
| 287 | + "username": profile_data.get("username", "developer"), |
| 288 | + } |
| 289 | + |
| 290 | + except Exception as exc: |
| 291 | + logger.error(f"Unexpected description generation error: {exc}") |
| 292 | + return { |
| 293 | + "success": False, |
| 294 | + "description": get_fallback_description(profile_data, theme_name, normalized_tone), |
| 295 | + "source": "fallback", |
| 296 | + "tone": normalized_tone, |
| 297 | + "theme": theme_name, |
| 298 | + "username": profile_data.get("username", "developer"), |
| 299 | + "error": str(exc), |
| 300 | + } |
0 commit comments