File size: 16,267 Bytes
46ddbdc 9e2a39b 46ddbdc 9e2a39b 46ddbdc 4576b21 7c4bfcc 4576b21 7c4bfcc 4576b21 46ddbdc 9e2a39b 46ddbdc 9e2a39b 46ddbdc 4576b21 |
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 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 |
"""
Service adapters for Claude AI content generation
"""
import os
from typing import Optional
import anthropic
# Type definitions
class RepoProfile:
def __init__(
self,
url: str,
owner: str,
name: str,
description: str,
languages: dict,
primary_language: str,
stars: int,
forks: int,
structure: dict,
readme: str,
main_features: list[str],
technical_stack: list[str],
quickstart_path: Optional[str] = None,
commits: Optional[list] = None,
commits_with_diffs: Optional[list] = None,
breaking_changes: Optional[list] = None,
initial_readme: Optional[str] = None,
readme_diff: Optional[str] = None,
has_readme_changes: bool = False,
):
self.url = url
self.owner = owner
self.name = name
self.description = description
self.languages = languages
self.primary_language = primary_language
self.stars = stars
self.forks = forks
self.structure = structure
self.readme = readme
self.main_features = main_features
self.technical_stack = technical_stack
self.quickstart_path = quickstart_path
self.commits = commits or []
self.commits_with_diffs = commits_with_diffs or []
self.breaking_changes = breaking_changes or []
self.initial_readme = initial_readme or ""
self.readme_diff = readme_diff or ""
self.has_readme_changes = has_readme_changes
class ContentVariant:
def __init__(
self,
id: str,
format: str,
content: str,
score: Optional[float] = None,
evaluation_metrics: Optional[dict] = None,
):
self.id = id
self.format = format
self.content = content
self.score = score
self.evaluation_metrics = evaluation_metrics
# Claude Service
class ClaudeService:
def __init__(self, api_key: Optional[str] = None):
"""Initialize Claude service.
Priority for API key:
1. Environment variable ANTHROPIC_API_KEY (for Hugging Face Spaces secrets)
2. User-provided api_key parameter (for manual override)
"""
# Environment variable takes priority (for HF Spaces secrets)
self.api_key = os.environ.get("ANTHROPIC_API_KEY") or api_key
if not self.api_key:
raise ValueError("ANTHROPIC_API_KEY not configured. Please provide your own API key in Settings.")
self.client = anthropic.Anthropic(api_key=self.api_key)
def extract_repo_profile(self, repo_data: dict) -> dict:
prompt = f"""Analyze this GitHub repository and extract a structured profile:
Repository: {repo_data.get('full_name', '')}
Description: {repo_data.get('description', '')}
Languages: {repo_data.get('languages', {})}
README: {repo_data.get('readme', '')[:3000]}
Extract:
1. Main features (3-5 key capabilities)
2. Technical stack (frameworks, tools, dependencies)
3. Primary use cases
4. Key directories and their purposes
5. Quickstart path if available
Return as JSON with this structure:
{{
"mainFeatures": string[],
"technicalStack": string[],
"useCases": string[],
"keyDirectories": string[],
"quickstartPath": string | null
}}"""
try:
response = self.client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=2048,
messages=[{"role": "user", "content": prompt}],
)
import json
text = response.content[0].text
# Try to extract JSON from the response
try:
return json.loads(text)
except json.JSONDecodeError:
# Try to find JSON in the response
import re
json_match = re.search(r"\{[\s\S]*\}", text)
if json_match:
return json.loads(json_match.group())
return self._extract_profile_fallback(repo_data)
except Exception as e:
print(f"Claude API error: {e}")
return self._extract_profile_fallback(repo_data)
def _extract_profile_fallback(self, repo_data: dict) -> dict:
return {
"mainFeatures": [
repo_data.get("description", "No description available"),
"See README for details",
],
"technicalStack": list(repo_data.get("languages", {}).keys())[:5],
"useCases": ["General development"],
"keyDirectories": repo_data.get("structure", {}).get("keyDirectories", []),
"quickstartPath": None,
}
def generate_content_variants(
self, profile: RepoProfile, format: str, variant_count: int = 2
) -> list[ContentVariant]:
prompt = self._get_prompt_for_format(format, profile)
variants = []
try:
for i in range(variant_count):
response = self.client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=4096,
temperature=0.7 + (i * 0.1),
messages=[{"role": "user", "content": prompt}],
)
content = response.content[0].text
variants.append(
ContentVariant(
id=f"{format}-variant-{i + 1}",
format=format,
content=content,
)
)
except Exception as e:
print(f"Claude generation error: {e}")
variants.append(
ContentVariant(
id=f"{format}-variant-1",
format=format,
content=self._generate_fallback_content(format, profile),
)
)
return variants
def _generate_fallback_content(self, format: str, profile: RepoProfile) -> str:
repo_name = profile.name
description = profile.description
if format == "tutorial":
return f"""# Getting Started with {repo_name}
## Overview
{description}
## Prerequisites
- Git installed
- Basic knowledge of {profile.primary_language}
## Installation
```bash
git clone {profile.url}
cd {repo_name}
# Follow project-specific setup instructions
```
## Next Steps
Check the README for detailed documentation.
*Note: This is a fallback tutorial. For AI-generated content, please add valid ANTHROPIC_API_KEY.*"""
elif format == "blog":
features = "\n".join([f"- {f}" for f in profile.main_features])
return f"""# Introducing {repo_name}
{description}
## Key Features
{features}
## Tech Stack
Built with {', '.join(profile.technical_stack)}
## Get Started
Visit the repository: {profile.url}
*Note: This is a fallback blog post. For AI-generated content, please add valid ANTHROPIC_API_KEY.*"""
elif format == "talk":
return f"""# {repo_name}: Conference Talk Outline
## Title
"Introduction to {repo_name}"
## Abstract
{description}
## Slides (30-45 minutes)
1. Introduction & Background
2. Problem Statement
3. Solution Overview
4. Key Features
5. Live Demo
6. Q&A
*Note: This is a fallback talk outline. For AI-generated content, please add valid ANTHROPIC_API_KEY.*"""
elif format == "twitter":
return f"""π Check out {repo_name}!
{description}
Built with {profile.primary_language}
β {profile.stars} stars
Learn more: {profile.url}
#OpenSource #{profile.primary_language}
*Note: This is a fallback tweet. For AI-generated content, please add valid ANTHROPIC_API_KEY.*"""
elif format == "linkedin":
features = "\n".join([f"β’ {f}" for f in profile.main_features])
return f"""I'm excited to share {repo_name} with the community.
{description}
Key highlights:
{features}
Check it out: {profile.url}
*Note: This is a fallback LinkedIn post. For AI-generated content, please add valid ANTHROPIC_API_KEY.*"""
elif format == "hackathon":
return f"""# Hackathon Challenge: Build with {repo_name}
## Challenge Description
Create an innovative project using {repo_name}
## Requirements
- Use {profile.primary_language}
- Implement at least one key feature
- Document your approach
## Judging Criteria
- Innovation
- Technical implementation
- Code quality
- Presentation
*Note: This is a fallback challenge. For AI-generated content, please add valid ANTHROPIC_API_KEY.*"""
return f"Content for {format} format.\n\n*Note: Add ANTHROPIC_API_KEY for AI-generated content.*"
def _get_prompt_for_format(self, format: str, profile: RepoProfile) -> str:
commits_list = profile.commits[:5] if profile.commits else []
recent_commits = ""
if commits_list:
commits_text = "\n".join(
[
f"- {c.get('date', '')[:10]}: {c.get('message', '').split(chr(10))[0]}"
for c in commits_list
]
)
recent_commits = f"\nRecent Commits (most recent first):\n{commits_text}"
# Add code diffs context
code_diffs = ""
if profile.commits_with_diffs:
diff_summaries = []
for commit in profile.commits_with_diffs[:3]:
diff = commit.get("diff", "")
if diff:
# Truncate each diff to keep context manageable
diff_preview = diff[:2000] + "..." if len(diff) > 2000 else diff
diff_summaries.append(f"### {commit.get('message', 'No message')}\n```diff\n{diff_preview}\n```")
if diff_summaries:
code_diffs = f"\n\nCode Changes (diffs from recent commits):\n" + "\n\n".join(diff_summaries)
# Add breaking changes context
breaking_changes_ctx = ""
if profile.breaking_changes:
bc_items = []
for bc in profile.breaking_changes[:5]:
changes_desc = ", ".join([f"{c['type']} ({c['count']})" for c in bc.get("changes", [])])
bc_items.append(f"- [{bc.get('sha', '')}] {bc.get('message', '')}: {changes_desc}")
if bc_items:
breaking_changes_ctx = f"\n\nβ οΈ POTENTIAL BREAKING CHANGES DETECTED:\n" + "\n".join(bc_items)
breaking_changes_ctx += "\nIMPORTANT: If breaking changes exist, you MUST include migration guidance in the content."
# Add README changes context (highest priority)
readme_changes_ctx = ""
if profile.has_readme_changes and profile.readme_diff:
readme_changes_ctx = f"\n\nπ README CHANGES DETECTED (HIGHEST PRIORITY):\nThe README documentation has been updated during the analysis period. These changes likely reflect important API changes, new features, or usage updates that MUST be prominently featured:\n\n{profile.readme_diff[:3000]}"
# Add initial README context for project understanding
initial_readme_ctx = ""
if profile.initial_readme:
initial_readme_ctx = f"\n\nProject Background (from initial README):\n{profile.initial_readme[:2000]}"
base_context = f"""Repository: {profile.name}
Description: {profile.description}
Main Features: {', '.join(profile.main_features)}
Tech Stack: {', '.join(profile.technical_stack)}
Primary Language: {profile.primary_language}{recent_commits}{code_diffs}{breaking_changes_ctx}{readme_changes_ctx}{initial_readme_ctx}
Note: Focus content on changes within the selected analysis period when relevant."""
prompts = {
"tutorial": f"""{base_context}
Create a step-by-step tutorial showcasing the LATEST updates and new features from recent commits.
IMPORTANT:
- Start with a brief 2-3 sentence project introduction
- Focus 80% of content on recent updates, new features, and changes from the commit history
- Highlight what's NEW and DIFFERENT compared to older versions
- Include working code examples demonstrating recent features
- If no recent commits, focus on the most advanced/latest capabilities
Include:
- Brief project overview (2-3 sentences)
- What's new in recent updates (primary focus)
- Step-by-step guide to using new features
- Code examples showcasing latest additions
- Migration tips if APIs changed
- Next steps with new features
Make it executable and accurate. Use markdown format.""",
"blog": f"""{base_context}
Write a technical blog post announcing the LATEST updates and new features.
IMPORTANT:
- Focus on recent changes and what's NEW (based on recent commits)
- Brief context about the project (1 paragraph max)
- Deep dive into latest features and improvements (70-80% of content)
- Show before/after comparisons if APIs changed
- Highlight breaking changes or major improvements
Include:
- Hook: What's new and why it matters NOW
- Brief project context (1 paragraph)
- Deep dive: Latest features and updates (primary focus)
- Code examples showcasing new capabilities
- Migration guide if needed
- What's coming next
- Call to action
Target audience: Technical developers. Use markdown format.""",
"talk": f"""{base_context}
Create a 30-45 minute meetup/conference talk outline focused on LATEST updates and new features.
IMPORTANT:
- This is for a meetup/conference - focus on what's NEW and exciting
- Brief intro (2-3 slides max), then dive into recent updates
- 70-80% of talk should cover latest features, improvements, and changes
- Include live demos of new capabilities
- Show real code from recent commits
Include:
- Talk title emphasizing "What's New" or "Latest Updates"
- Abstract highlighting recent changes (150 words)
- Slide structure (15-20 slides):
* Quick intro (2-3 slides)
* Recent updates deep dive (10-12 slides)
* Live demos of new features (3-4 slides)
* Roadmap and what's next (1-2 slides)
- Speaker notes focusing on recent changes
- Demo points showcasing latest features
- Q&A prep about new capabilities
Format as markdown with clear sections.""",
"twitter": f"""{base_context}
Write an engaging Twitter/X thread (5-7 tweets) announcing the LATEST updates.
IMPORTANT:
- Focus on what's NEW (recent commits/features)
- First tweet: Brief intro + "Here's what's new π§΅"
- Next 3-5 tweets: Deep dive into specific new features
- Last tweet: Call to action
Make it:
- Start with "What's new in [project]" hook
- Highlight recent features/changes (use commit history)
- Technical but accessible
- Add relevant emojis (π β‘ π β¨)
- Include code snippets for new features
- End with link and CTA
- Each tweet under 280 chars
Format as numbered thread.""",
"linkedin": f"""{base_context}
Write a LinkedIn post announcing LATEST updates for a technical leadership audience.
IMPORTANT:
- Focus on recent updates and what's new
- Frame updates in terms of business value and impact
- Brief context, then dive into latest improvements
Include:
- Hook: Major update/new release announcement
- Brief project context (1-2 sentences)
- What's new: Recent features and improvements (primary focus)
- Business value of new updates
- Technical highlights of latest additions
- Team/community impact
- Call to action
Tone: Professional, insightful, forward-looking. 200-300 words.""",
"hackathon": f"""{base_context}
Design a hackathon challenge focused on exploring and using the LATEST features.
IMPORTANT:
- Challenge should require using recent updates/new features
- Encourage participants to push boundaries of new capabilities
- Provide recent code examples as starting points
Include:
- Challenge title emphasizing "Latest Features" or "New Capabilities"
- Brief project intro (2-3 sentences)
- Problem statement leveraging new features
- Required deliverables (must use recent updates)
- Judging criteria (4-5 points, bonus for creative use of new features)
- Starter resources with recent code examples
- Sample tasks exploring latest additions (3-5)
- Difficulty level
Make it engaging and achievable in 24-48 hours.""",
}
return prompts.get(
format, f"{base_context}\n\nCreate content for {format} format."
)
|