sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
davila7/claude-code-templates:cli-tool/components/skills/business-marketing/app-store-optimization/aso_scorer.py
""" ASO scoring module for App Store Optimization. Calculates comprehensive ASO health score across multiple dimensions. """ from typing import Dict, List, Any, Optional class ASOScorer: """Calculates overall ASO health score and provides recommendations.""" # Score weights for different components (total = 100) WEIGHTS = { 'metadata_quality': 25, 'ratings_reviews': 25, 'keyword_performance': 25, 'conversion_metrics': 25 } # Benchmarks for scoring BENCHMARKS = { 'title_keyword_usage': {'min': 1, 'target': 2}, 'description_length': {'min': 500, 'target': 2000}, 'keyword_density': {'min': 2, 'optimal': 5, 'max': 8}, 'average_rating': {'min': 3.5, 'target': 4.5}, 'ratings_count': {'min': 100, 'target': 5000}, 'keywords_top_10': {'min': 2, 'target': 10}, 'keywords_top_50': {'min': 5, 'target': 20}, 'conversion_rate': {'min': 0.02, 'target': 0.10} } def __init__(self): """Initialize ASO scorer.""" self.score_breakdown = {} def calculate_overall_score( self, metadata: Dict[str, Any], ratings: Dict[str, Any], keyword_performance: Dict[str, Any], conversion: Dict[str, Any] ) -> Dict[str, Any]: """ Calculate comprehensive ASO score (0-100). Args: metadata: Title, description quality metrics ratings: Rating average and count keyword_performance: Keyword ranking data conversion: Impression-to-install metrics Returns: Overall score with detailed breakdown """ # Calculate component scores metadata_score = self.score_metadata_quality(metadata) ratings_score = self.score_ratings_reviews(ratings) keyword_score = self.score_keyword_performance(keyword_performance) conversion_score = self.score_conversion_metrics(conversion) # Calculate weighted overall score overall_score = ( metadata_score * (self.WEIGHTS['metadata_quality'] / 100) + ratings_score * (self.WEIGHTS['ratings_reviews'] / 100) + keyword_score * (self.WEIGHTS['keyword_performance'] / 100) + conversion_score * (self.WEIGHTS['conversion_metrics'] / 100) ) # Store breakdown self.score_breakdown = { 'metadata_quality': { 'score': metadata_score, 'weight': self.WEIGHTS['metadata_quality'], 'weighted_contribution': round(metadata_score * (self.WEIGHTS['metadata_quality'] / 100), 1) }, 'ratings_reviews': { 'score': ratings_score, 'weight': self.WEIGHTS['ratings_reviews'], 'weighted_contribution': round(ratings_score * (self.WEIGHTS['ratings_reviews'] / 100), 1) }, 'keyword_performance': { 'score': keyword_score, 'weight': self.WEIGHTS['keyword_performance'], 'weighted_contribution': round(keyword_score * (self.WEIGHTS['keyword_performance'] / 100), 1) }, 'conversion_metrics': { 'score': conversion_score, 'weight': self.WEIGHTS['conversion_metrics'], 'weighted_contribution': round(conversion_score * (self.WEIGHTS['conversion_metrics'] / 100), 1) } } # Generate recommendations recommendations = self.generate_recommendations( metadata_score, ratings_score, keyword_score, conversion_score ) # Assess overall health health_status = self._assess_health_status(overall_score) return { 'overall_score': round(overall_score, 1), 'health_status': health_status, 'score_breakdown': self.score_breakdown, 'recommendations': recommendations, 'priority_actions': self._prioritize_actions(recommendations), 'strengths': self._identify_strengths(self.score_breakdown), 'weaknesses': self._identify_weaknesses(self.score_breakdown) } def score_metadata_quality(self, metadata: Dict[str, Any]) -> float: """ Score metadata quality (0-100). Evaluates: - Title optimization - Description quality - Keyword usage """ scores = [] # Title score (0-35 points) title_keywords = metadata.get('title_keyword_count', 0) title_length = metadata.get('title_length', 0) title_score = 0 if title_keywords >= self.BENCHMARKS['title_keyword_usage']['target']: title_score = 35 elif title_keywords >= self.BENCHMARKS['title_keyword_usage']['min']: title_score = 25 else: title_score = 10 # Adjust for title length usage if title_length > 25: # Using most of available space title_score += 0 else: title_score -= 5 scores.append(min(title_score, 35)) # Description score (0-35 points) desc_length = metadata.get('description_length', 0) desc_quality = metadata.get('description_quality', 0.0) # 0-1 scale desc_score = 0 if desc_length >= self.BENCHMARKS['description_length']['target']: desc_score = 25 elif desc_length >= self.BENCHMARKS['description_length']['min']: desc_score = 15 else: desc_score = 5 # Add quality bonus desc_score += desc_quality * 10 scores.append(min(desc_score, 35)) # Keyword density score (0-30 points) keyword_density = metadata.get('keyword_density', 0.0) if self.BENCHMARKS['keyword_density']['min'] <= keyword_density <= self.BENCHMARKS['keyword_density']['optimal']: density_score = 30 elif keyword_density < self.BENCHMARKS['keyword_density']['min']: # Too low - proportional scoring density_score = (keyword_density / self.BENCHMARKS['keyword_density']['min']) * 20 else: # Too high (keyword stuffing) - penalty excess = keyword_density - self.BENCHMARKS['keyword_density']['optimal'] density_score = max(30 - (excess * 5), 0) scores.append(density_score) return round(sum(scores), 1) def score_ratings_reviews(self, ratings: Dict[str, Any]) -> float: """ Score ratings and reviews (0-100). Evaluates: - Average rating - Total ratings count - Review velocity """ average_rating = ratings.get('average_rating', 0.0) total_ratings = ratings.get('total_ratings', 0) recent_ratings = ratings.get('recent_ratings_30d', 0) # Rating quality score (0-50 points) if average_rating >= self.BENCHMARKS['average_rating']['target']: rating_quality_score = 50 elif average_rating >= self.BENCHMARKS['average_rating']['min']: # Proportional scoring between min and target proportion = (average_rating - self.BENCHMARKS['average_rating']['min']) / \ (self.BENCHMARKS['average_rating']['target'] - self.BENCHMARKS['average_rating']['min']) rating_quality_score = 30 + (proportion * 20) elif average_rating >= 3.0: rating_quality_score = 20 else: rating_quality_score = 10 # Rating volume score (0-30 points) if total_ratings >= self.BENCHMARKS['ratings_count']['target']: rating_volume_score = 30 elif total_ratings >= self.BENCHMARKS['ratings_count']['min']: # Proportional scoring proportion = (total_ratings - self.BENCHMARKS['ratings_count']['min']) / \ (self.BENCHMARKS['ratings_count']['target'] - self.BENCHMARKS['ratings_count']['min']) rating_volume_score = 15 + (proportion * 15) else: # Very low volume rating_volume_score = (total_ratings / self.BENCHMARKS['ratings_count']['min']) * 15 # Rating velocity score (0-20 points) if recent_ratings > 100: velocity_score = 20 elif recent_ratings > 50: velocity_score = 15 elif recent_ratings > 10: velocity_score = 10 else: velocity_score = 5 total_score = rating_quality_score + rating_volume_score + velocity_score return round(min(total_score, 100), 1) def score_keyword_performance(self, keyword_performance: Dict[str, Any]) -> float: """ Score keyword ranking performance (0-100). Evaluates: - Top 10 rankings - Top 50 rankings - Ranking trends """ top_10_count = keyword_performance.get('top_10', 0) top_50_count = keyword_performance.get('top_50', 0) top_100_count = keyword_performance.get('top_100', 0) improving_keywords = keyword_performance.get('improving_keywords', 0) # Top 10 score (0-50 points) - most valuable rankings if top_10_count >= self.BENCHMARKS['keywords_top_10']['target']: top_10_score = 50 elif top_10_count >= self.BENCHMARKS['keywords_top_10']['min']: proportion = (top_10_count - self.BENCHMARKS['keywords_top_10']['min']) / \ (self.BENCHMARKS['keywords_top_10']['target'] - self.BENCHMARKS['keywords_top_10']['min']) top_10_score = 25 + (proportion * 25) else: top_10_score = (top_10_count / self.BENCHMARKS['keywords_top_10']['min']) * 25 # Top 50 score (0-30 points) if top_50_count >= self.BENCHMARKS['keywords_top_50']['target']: top_50_score = 30 elif top_50_count >= self.BENCHMARKS['keywords_top_50']['min']: proportion = (top_50_count - self.BENCHMARKS['keywords_top_50']['min']) / \ (self.BENCHMARKS['keywords_top_50']['target'] - self.BENCHMARKS['keywords_top_50']['min']) top_50_score = 15 + (proportion * 15) else: top_50_score = (top_50_count / self.BENCHMARKS['keywords_top_50']['min']) * 15 # Coverage score (0-10 points) - based on top 100 coverage_score = min((top_100_count / 30) * 10, 10) # Trend score (0-10 points) - are rankings improving? if improving_keywords > 5: trend_score = 10 elif improving_keywords > 0: trend_score = 5 else: trend_score = 0 total_score = top_10_score + top_50_score + coverage_score + trend_score return round(min(total_score, 100), 1) def score_conversion_metrics(self, conversion: Dict[str, Any]) -> float: """ Score conversion performance (0-100). Evaluates: - Impression-to-install conversion rate - Download velocity """ conversion_rate = conversion.get('impression_to_install', 0.0) downloads_30d = conversion.get('downloads_last_30_days', 0) downloads_trend = conversion.get('downloads_trend', 'stable') # 'up', 'stable', 'down' # Conversion rate score (0-70 points) if conversion_rate >= self.BENCHMARKS['conversion_rate']['target']: conversion_score = 70 elif conversion_rate >= self.BENCHMARKS['conversion_rate']['min']: proportion = (conversion_rate - self.BENCHMARKS['conversion_rate']['min']) / \ (self.BENCHMARKS['conversion_rate']['target'] - self.BENCHMARKS['conversion_rate']['min']) conversion_score = 35 + (proportion * 35) else: conversion_score = (conversion_rate / self.BENCHMARKS['conversion_rate']['min']) * 35 # Download velocity score (0-20 points) if downloads_30d > 10000: velocity_score = 20 elif downloads_30d > 1000: velocity_score = 15 elif downloads_30d > 100: velocity_score = 10 else: velocity_score = 5 # Trend bonus (0-10 points) if downloads_trend == 'up': trend_score = 10 elif downloads_trend == 'stable': trend_score = 5 else: trend_score = 0 total_score = conversion_score + velocity_score + trend_score return round(min(total_score, 100), 1) def generate_recommendations( self, metadata_score: float, ratings_score: float, keyword_score: float, conversion_score: float ) -> List[Dict[str, Any]]: """Generate prioritized recommendations based on scores.""" recommendations = [] # Metadata recommendations if metadata_score < 60: recommendations.append({ 'category': 'metadata_quality', 'priority': 'high', 'action': 'Optimize app title and description', 'details': 'Add more keywords to title, expand description to 1500-2000 characters, improve keyword density to 3-5%', 'expected_impact': 'Improve discoverability and ranking potential' }) elif metadata_score < 80: recommendations.append({ 'category': 'metadata_quality', 'priority': 'medium', 'action': 'Refine metadata for better keyword targeting', 'details': 'Test variations of title/subtitle, optimize keyword field for Apple', 'expected_impact': 'Incremental ranking improvements' }) # Ratings recommendations if ratings_score < 60: recommendations.append({ 'category': 'ratings_reviews', 'priority': 'high', 'action': 'Improve rating quality and volume', 'details': 'Address top user complaints, implement in-app rating prompts, respond to negative reviews', 'expected_impact': 'Better conversion rates and trust signals' }) elif ratings_score < 80: recommendations.append({ 'category': 'ratings_reviews', 'priority': 'medium', 'action': 'Increase rating velocity', 'details': 'Optimize timing of rating requests, encourage satisfied users to rate', 'expected_impact': 'Sustained rating quality' }) # Keyword performance recommendations if keyword_score < 60: recommendations.append({ 'category': 'keyword_performance', 'priority': 'high', 'action': 'Improve keyword rankings', 'details': 'Target long-tail keywords with lower competition, update metadata with high-potential keywords, build backlinks', 'expected_impact': 'Significant improvement in organic visibility' }) elif keyword_score < 80: recommendations.append({ 'category': 'keyword_performance', 'priority': 'medium', 'action': 'Expand keyword coverage', 'details': 'Target additional related keywords, test seasonal keywords, localize for new markets', 'expected_impact': 'Broader reach and more discovery opportunities' }) # Conversion recommendations if conversion_score < 60: recommendations.append({ 'category': 'conversion_metrics', 'priority': 'high', 'action': 'Optimize store listing for conversions', 'details': 'Improve screenshots and icon, strengthen value proposition in description, add video preview', 'expected_impact': 'Higher impression-to-install conversion' }) elif conversion_score < 80: recommendations.append({ 'category': 'conversion_metrics', 'priority': 'medium', 'action': 'Test visual asset variations', 'details': 'A/B test different icon designs and screenshot sequences', 'expected_impact': 'Incremental conversion improvements' }) return recommendations def _assess_health_status(self, overall_score: float) -> str: """Assess overall ASO health status.""" if overall_score >= 80: return "Excellent - Top-tier ASO performance" elif overall_score >= 65: return "Good - Competitive ASO with room for improvement" elif overall_score >= 50: return "Fair - Needs strategic improvements" else: return "Poor - Requires immediate ASO overhaul" def _prioritize_actions( self, recommendations: List[Dict[str, Any]] ) -> List[Dict[str, Any]]: """Prioritize actions by impact and urgency.""" # Sort by priority (high first) and expected impact priority_order = {'high': 0, 'medium': 1, 'low': 2} sorted_recommendations = sorted( recommendations, key=lambda x: priority_order[x['priority']] ) return sorted_recommendations[:3] # Top 3 priority actions def _identify_strengths(self, score_breakdown: Dict[str, Any]) -> List[str]: """Identify areas of strength (scores >= 75).""" strengths = [] for category, data in score_breakdown.items(): if data['score'] >= 75: strengths.append( f"{category.replace('_', ' ').title()}: {data['score']}/100" ) return strengths if strengths else ["Focus on building strengths across all areas"] def _identify_weaknesses(self, score_breakdown: Dict[str, Any]) -> List[str]: """Identify areas needing improvement (scores < 60).""" weaknesses = [] for category, data in score_breakdown.items(): if data['score'] < 60: weaknesses.append( f"{category.replace('_', ' ').title()}: {data['score']}/100 - needs improvement" ) return weaknesses if weaknesses else ["All areas performing adequately"] def calculate_aso_score( metadata: Dict[str, Any], ratings: Dict[str, Any], keyword_performance: Dict[str, Any], conversion: Dict[str, Any] ) -> Dict[str, Any]: """ Convenience function to calculate ASO score. Args: metadata: Metadata quality metrics ratings: Ratings data keyword_performance: Keyword ranking data conversion: Conversion metrics Returns: Complete ASO score report """ scorer = ASOScorer() return scorer.calculate_overall_score( metadata, ratings, keyword_performance, conversion )
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/business-marketing/app-store-optimization/aso_scorer.py", "license": "MIT License", "lines": 413, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/business-marketing/app-store-optimization/competitor_analyzer.py
""" Competitor analysis module for App Store Optimization. Analyzes top competitors' ASO strategies and identifies opportunities. """ from typing import Dict, List, Any, Optional from collections import Counter import re class CompetitorAnalyzer: """Analyzes competitor apps to identify ASO opportunities.""" def __init__(self, category: str, platform: str = 'apple'): """ Initialize competitor analyzer. Args: category: App category (e.g., "Productivity", "Games") platform: 'apple' or 'google' """ self.category = category self.platform = platform self.competitors = [] def analyze_competitor( self, app_data: Dict[str, Any] ) -> Dict[str, Any]: """ Analyze a single competitor's ASO strategy. Args: app_data: Dictionary with app_name, title, description, rating, ratings_count, keywords Returns: Comprehensive competitor analysis """ app_name = app_data.get('app_name', '') title = app_data.get('title', '') description = app_data.get('description', '') rating = app_data.get('rating', 0.0) ratings_count = app_data.get('ratings_count', 0) keywords = app_data.get('keywords', []) analysis = { 'app_name': app_name, 'title_analysis': self._analyze_title(title), 'description_analysis': self._analyze_description(description), 'keyword_strategy': self._extract_keyword_strategy(title, description, keywords), 'rating_metrics': { 'rating': rating, 'ratings_count': ratings_count, 'rating_quality': self._assess_rating_quality(rating, ratings_count) }, 'competitive_strength': self._calculate_competitive_strength( rating, ratings_count, len(description) ), 'key_differentiators': self._identify_differentiators(description) } self.competitors.append(analysis) return analysis def compare_competitors( self, competitors_data: List[Dict[str, Any]] ) -> Dict[str, Any]: """ Compare multiple competitors and identify patterns. Args: competitors_data: List of competitor data dictionaries Returns: Comparative analysis with insights """ # Analyze each competitor analyses = [] for comp_data in competitors_data: analysis = self.analyze_competitor(comp_data) analyses.append(analysis) # Extract common keywords across competitors all_keywords = [] for analysis in analyses: all_keywords.extend(analysis['keyword_strategy']['primary_keywords']) common_keywords = self._find_common_keywords(all_keywords) # Identify keyword gaps (used by some but not all) keyword_gaps = self._identify_keyword_gaps(analyses) # Rank competitors by strength ranked_competitors = sorted( analyses, key=lambda x: x['competitive_strength'], reverse=True ) # Analyze rating distribution rating_analysis = self._analyze_rating_distribution(analyses) # Identify best practices best_practices = self._identify_best_practices(ranked_competitors) return { 'category': self.category, 'platform': self.platform, 'competitors_analyzed': len(analyses), 'ranked_competitors': ranked_competitors, 'common_keywords': common_keywords, 'keyword_gaps': keyword_gaps, 'rating_analysis': rating_analysis, 'best_practices': best_practices, 'opportunities': self._identify_opportunities( analyses, common_keywords, keyword_gaps ) } def identify_gaps( self, your_app_data: Dict[str, Any], competitors_data: List[Dict[str, Any]] ) -> Dict[str, Any]: """ Identify gaps between your app and competitors. Args: your_app_data: Your app's data competitors_data: List of competitor data Returns: Gap analysis with actionable recommendations """ # Analyze your app your_analysis = self.analyze_competitor(your_app_data) # Analyze competitors competitor_comparison = self.compare_competitors(competitors_data) # Identify keyword gaps your_keywords = set(your_analysis['keyword_strategy']['primary_keywords']) competitor_keywords = set(competitor_comparison['common_keywords']) missing_keywords = competitor_keywords - your_keywords # Identify rating gap avg_competitor_rating = competitor_comparison['rating_analysis']['average_rating'] rating_gap = avg_competitor_rating - your_analysis['rating_metrics']['rating'] # Identify description length gap avg_competitor_desc_length = sum( len(comp['description_analysis']['text']) for comp in competitor_comparison['ranked_competitors'] ) / len(competitor_comparison['ranked_competitors']) your_desc_length = len(your_analysis['description_analysis']['text']) desc_length_gap = avg_competitor_desc_length - your_desc_length return { 'your_app': your_analysis, 'keyword_gaps': { 'missing_keywords': list(missing_keywords)[:10], 'recommendations': self._generate_keyword_recommendations(missing_keywords) }, 'rating_gap': { 'your_rating': your_analysis['rating_metrics']['rating'], 'average_competitor_rating': avg_competitor_rating, 'gap': round(rating_gap, 2), 'action_items': self._generate_rating_improvement_actions(rating_gap) }, 'content_gap': { 'your_description_length': your_desc_length, 'average_competitor_length': int(avg_competitor_desc_length), 'gap': int(desc_length_gap), 'recommendations': self._generate_content_recommendations(desc_length_gap) }, 'competitive_positioning': self._assess_competitive_position( your_analysis, competitor_comparison ) } def _analyze_title(self, title: str) -> Dict[str, Any]: """Analyze title structure and keyword usage.""" parts = re.split(r'[-:|]', title) return { 'title': title, 'length': len(title), 'has_brand': len(parts) > 0, 'has_keywords': len(parts) > 1, 'components': [part.strip() for part in parts], 'word_count': len(title.split()), 'strategy': 'brand_plus_keywords' if len(parts) > 1 else 'brand_only' } def _analyze_description(self, description: str) -> Dict[str, Any]: """Analyze description structure and content.""" lines = description.split('\n') word_count = len(description.split()) # Check for structural elements has_bullet_points = '•' in description or '*' in description has_sections = any(line.isupper() for line in lines if len(line) > 0) has_call_to_action = any( cta in description.lower() for cta in ['download', 'try', 'get', 'start', 'join'] ) # Extract features mentioned features = self._extract_features(description) return { 'text': description, 'length': len(description), 'word_count': word_count, 'structure': { 'has_bullet_points': has_bullet_points, 'has_sections': has_sections, 'has_call_to_action': has_call_to_action }, 'features_mentioned': features, 'readability': 'good' if 50 <= word_count <= 300 else 'needs_improvement' } def _extract_keyword_strategy( self, title: str, description: str, explicit_keywords: List[str] ) -> Dict[str, Any]: """Extract keyword strategy from metadata.""" # Extract keywords from title title_keywords = [word.lower() for word in title.split() if len(word) > 3] # Extract frequently used words from description desc_words = re.findall(r'\b\w{4,}\b', description.lower()) word_freq = Counter(desc_words) frequent_words = [word for word, count in word_freq.most_common(15) if count > 2] # Combine with explicit keywords all_keywords = list(set(title_keywords + frequent_words + explicit_keywords)) return { 'primary_keywords': title_keywords, 'description_keywords': frequent_words[:10], 'explicit_keywords': explicit_keywords, 'total_unique_keywords': len(all_keywords), 'keyword_focus': self._assess_keyword_focus(title_keywords, frequent_words) } def _assess_rating_quality(self, rating: float, ratings_count: int) -> str: """Assess the quality of ratings.""" if ratings_count < 100: return 'insufficient_data' elif rating >= 4.5 and ratings_count > 1000: return 'excellent' elif rating >= 4.0 and ratings_count > 500: return 'good' elif rating >= 3.5: return 'average' else: return 'poor' def _calculate_competitive_strength( self, rating: float, ratings_count: int, description_length: int ) -> float: """ Calculate overall competitive strength (0-100). Factors: - Rating quality (40%) - Rating volume (30%) - Metadata quality (30%) """ # Rating quality score (0-40) rating_score = (rating / 5.0) * 40 # Rating volume score (0-30) volume_score = min((ratings_count / 10000) * 30, 30) # Metadata quality score (0-30) metadata_score = min((description_length / 2000) * 30, 30) total_score = rating_score + volume_score + metadata_score return round(total_score, 1) def _identify_differentiators(self, description: str) -> List[str]: """Identify key differentiators from description.""" differentiator_keywords = [ 'unique', 'only', 'first', 'best', 'leading', 'exclusive', 'revolutionary', 'innovative', 'patent', 'award' ] differentiators = [] sentences = description.split('.') for sentence in sentences: sentence_lower = sentence.lower() if any(keyword in sentence_lower for keyword in differentiator_keywords): differentiators.append(sentence.strip()) return differentiators[:5] def _find_common_keywords(self, all_keywords: List[str]) -> List[str]: """Find keywords used by multiple competitors.""" keyword_counts = Counter(all_keywords) # Return keywords used by at least 2 competitors common = [kw for kw, count in keyword_counts.items() if count >= 2] return sorted(common, key=lambda x: keyword_counts[x], reverse=True)[:20] def _identify_keyword_gaps(self, analyses: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Identify keywords used by some competitors but not others.""" all_keywords_by_app = {} for analysis in analyses: app_name = analysis['app_name'] keywords = analysis['keyword_strategy']['primary_keywords'] all_keywords_by_app[app_name] = set(keywords) # Find keywords used by some but not all all_keywords_set = set() for keywords in all_keywords_by_app.values(): all_keywords_set.update(keywords) gaps = [] for keyword in all_keywords_set: using_apps = [ app for app, keywords in all_keywords_by_app.items() if keyword in keywords ] if 1 < len(using_apps) < len(analyses): gaps.append({ 'keyword': keyword, 'used_by': using_apps, 'usage_percentage': round(len(using_apps) / len(analyses) * 100, 1) }) return sorted(gaps, key=lambda x: x['usage_percentage'], reverse=True)[:15] def _analyze_rating_distribution(self, analyses: List[Dict[str, Any]]) -> Dict[str, Any]: """Analyze rating distribution across competitors.""" ratings = [a['rating_metrics']['rating'] for a in analyses] ratings_counts = [a['rating_metrics']['ratings_count'] for a in analyses] return { 'average_rating': round(sum(ratings) / len(ratings), 2), 'highest_rating': max(ratings), 'lowest_rating': min(ratings), 'average_ratings_count': int(sum(ratings_counts) / len(ratings_counts)), 'total_ratings_in_category': sum(ratings_counts) } def _identify_best_practices(self, ranked_competitors: List[Dict[str, Any]]) -> List[str]: """Identify best practices from top competitors.""" if not ranked_competitors: return [] top_competitor = ranked_competitors[0] practices = [] # Title strategy title_analysis = top_competitor['title_analysis'] if title_analysis['has_keywords']: practices.append( f"Title Strategy: Include primary keyword in title (e.g., '{title_analysis['title']}')" ) # Description structure desc_analysis = top_competitor['description_analysis'] if desc_analysis['structure']['has_bullet_points']: practices.append("Description: Use bullet points to highlight key features") if desc_analysis['structure']['has_sections']: practices.append("Description: Organize content with clear section headers") # Rating strategy rating_quality = top_competitor['rating_metrics']['rating_quality'] if rating_quality in ['excellent', 'good']: practices.append( f"Ratings: Maintain high rating quality ({top_competitor['rating_metrics']['rating']}★) " f"with significant volume ({top_competitor['rating_metrics']['ratings_count']} ratings)" ) return practices[:5] def _identify_opportunities( self, analyses: List[Dict[str, Any]], common_keywords: List[str], keyword_gaps: List[Dict[str, Any]] ) -> List[str]: """Identify ASO opportunities based on competitive analysis.""" opportunities = [] # Keyword opportunities from gaps if keyword_gaps: underutilized_keywords = [ gap['keyword'] for gap in keyword_gaps if gap['usage_percentage'] < 50 ] if underutilized_keywords: opportunities.append( f"Target underutilized keywords: {', '.join(underutilized_keywords[:5])}" ) # Rating opportunity avg_rating = sum(a['rating_metrics']['rating'] for a in analyses) / len(analyses) if avg_rating < 4.5: opportunities.append( f"Category average rating is {avg_rating:.1f} - opportunity to differentiate with higher ratings" ) # Content depth opportunity avg_desc_length = sum( a['description_analysis']['length'] for a in analyses ) / len(analyses) if avg_desc_length < 1500: opportunities.append( "Competitors have relatively short descriptions - opportunity to provide more comprehensive information" ) return opportunities[:5] def _extract_features(self, description: str) -> List[str]: """Extract feature mentions from description.""" # Look for bullet points or numbered lists lines = description.split('\n') features = [] for line in lines: line = line.strip() # Check if line starts with bullet or number if line and (line[0] in ['•', '*', '-', '✓'] or line[0].isdigit()): # Clean the line cleaned = re.sub(r'^[•*\-✓\d.)\s]+', '', line) if cleaned: features.append(cleaned) return features[:10] def _assess_keyword_focus( self, title_keywords: List[str], description_keywords: List[str] ) -> str: """Assess keyword focus strategy.""" overlap = set(title_keywords) & set(description_keywords) if len(overlap) >= 3: return 'consistent_focus' elif len(overlap) >= 1: return 'moderate_focus' else: return 'broad_focus' def _generate_keyword_recommendations(self, missing_keywords: set) -> List[str]: """Generate recommendations for missing keywords.""" if not missing_keywords: return ["Your keyword coverage is comprehensive"] recommendations = [] missing_list = list(missing_keywords)[:5] recommendations.append( f"Consider adding these competitor keywords: {', '.join(missing_list)}" ) recommendations.append( "Test keyword variations in subtitle/promotional text first" ) recommendations.append( "Monitor competitor keyword changes monthly" ) return recommendations def _generate_rating_improvement_actions(self, rating_gap: float) -> List[str]: """Generate actions to improve ratings.""" actions = [] if rating_gap > 0.5: actions.append("CRITICAL: Significant rating gap - prioritize user satisfaction improvements") actions.append("Analyze negative reviews to identify top issues") actions.append("Implement in-app rating prompts after positive experiences") actions.append("Respond to all negative reviews professionally") elif rating_gap > 0.2: actions.append("Focus on incremental improvements to close rating gap") actions.append("Optimize timing of rating requests") else: actions.append("Ratings are competitive - maintain quality and continue improvements") return actions def _generate_content_recommendations(self, desc_length_gap: int) -> List[str]: """Generate content recommendations based on length gap.""" recommendations = [] if desc_length_gap > 500: recommendations.append( "Expand description to match competitor detail level" ) recommendations.append( "Add use case examples and success stories" ) recommendations.append( "Include more feature explanations and benefits" ) elif desc_length_gap < -500: recommendations.append( "Consider condensing description for better readability" ) recommendations.append( "Focus on most important features first" ) else: recommendations.append( "Description length is competitive" ) return recommendations def _assess_competitive_position( self, your_analysis: Dict[str, Any], competitor_comparison: Dict[str, Any] ) -> str: """Assess your competitive position.""" your_strength = your_analysis['competitive_strength'] competitors = competitor_comparison['ranked_competitors'] if not competitors: return "No comparison data available" # Find where you'd rank better_than_count = sum( 1 for comp in competitors if your_strength > comp['competitive_strength'] ) position_percentage = (better_than_count / len(competitors)) * 100 if position_percentage >= 75: return "Strong Position: Top quartile in competitive strength" elif position_percentage >= 50: return "Competitive Position: Above average, opportunities for improvement" elif position_percentage >= 25: return "Challenging Position: Below average, requires strategic improvements" else: return "Weak Position: Bottom quartile, major ASO overhaul needed" def analyze_competitor_set( category: str, competitors_data: List[Dict[str, Any]], platform: str = 'apple' ) -> Dict[str, Any]: """ Convenience function to analyze a set of competitors. Args: category: App category competitors_data: List of competitor data platform: 'apple' or 'google' Returns: Complete competitive analysis """ analyzer = CompetitorAnalyzer(category, platform) return analyzer.compare_competitors(competitors_data)
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/business-marketing/app-store-optimization/competitor_analyzer.py", "license": "MIT License", "lines": 484, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/business-marketing/app-store-optimization/keyword_analyzer.py
""" Keyword analysis module for App Store Optimization. Analyzes keyword search volume, competition, and relevance for app discovery. """ from typing import Dict, List, Any, Optional, Tuple import re from collections import Counter class KeywordAnalyzer: """Analyzes keywords for ASO effectiveness.""" # Competition level thresholds (based on number of competing apps) COMPETITION_THRESHOLDS = { 'low': 1000, 'medium': 5000, 'high': 10000 } # Search volume categories (monthly searches estimate) VOLUME_CATEGORIES = { 'very_low': 1000, 'low': 5000, 'medium': 20000, 'high': 100000, 'very_high': 500000 } def __init__(self): """Initialize keyword analyzer.""" self.analyzed_keywords = {} def analyze_keyword( self, keyword: str, search_volume: int = 0, competing_apps: int = 0, relevance_score: float = 0.0 ) -> Dict[str, Any]: """ Analyze a single keyword for ASO potential. Args: keyword: The keyword to analyze search_volume: Estimated monthly search volume competing_apps: Number of apps competing for this keyword relevance_score: Relevance to your app (0.0-1.0) Returns: Dictionary with keyword analysis """ competition_level = self._calculate_competition_level(competing_apps) volume_category = self._categorize_search_volume(search_volume) difficulty_score = self._calculate_keyword_difficulty( search_volume, competing_apps ) # Calculate potential score (0-100) potential_score = self._calculate_potential_score( search_volume, competing_apps, relevance_score ) analysis = { 'keyword': keyword, 'search_volume': search_volume, 'volume_category': volume_category, 'competing_apps': competing_apps, 'competition_level': competition_level, 'relevance_score': relevance_score, 'difficulty_score': difficulty_score, 'potential_score': potential_score, 'recommendation': self._generate_recommendation( potential_score, difficulty_score, relevance_score ), 'keyword_length': len(keyword.split()), 'is_long_tail': len(keyword.split()) >= 3 } self.analyzed_keywords[keyword] = analysis return analysis def compare_keywords(self, keywords_data: List[Dict[str, Any]]) -> Dict[str, Any]: """ Compare multiple keywords and rank by potential. Args: keywords_data: List of dicts with keyword, search_volume, competing_apps, relevance_score Returns: Comparison report with ranked keywords """ analyses = [] for kw_data in keywords_data: analysis = self.analyze_keyword( keyword=kw_data['keyword'], search_volume=kw_data.get('search_volume', 0), competing_apps=kw_data.get('competing_apps', 0), relevance_score=kw_data.get('relevance_score', 0.0) ) analyses.append(analysis) # Sort by potential score (descending) ranked_keywords = sorted( analyses, key=lambda x: x['potential_score'], reverse=True ) # Categorize keywords primary_keywords = [ kw for kw in ranked_keywords if kw['potential_score'] >= 70 and kw['relevance_score'] >= 0.8 ] secondary_keywords = [ kw for kw in ranked_keywords if 50 <= kw['potential_score'] < 70 and kw['relevance_score'] >= 0.6 ] long_tail_keywords = [ kw for kw in ranked_keywords if kw['is_long_tail'] and kw['relevance_score'] >= 0.7 ] return { 'total_keywords_analyzed': len(analyses), 'ranked_keywords': ranked_keywords, 'primary_keywords': primary_keywords[:5], # Top 5 'secondary_keywords': secondary_keywords[:10], # Top 10 'long_tail_keywords': long_tail_keywords[:10], # Top 10 'summary': self._generate_comparison_summary( primary_keywords, secondary_keywords, long_tail_keywords ) } def find_long_tail_opportunities( self, base_keyword: str, modifiers: List[str] ) -> List[Dict[str, Any]]: """ Generate long-tail keyword variations. Args: base_keyword: Core keyword (e.g., "task manager") modifiers: List of modifiers (e.g., ["free", "simple", "team"]) Returns: List of long-tail keyword suggestions """ long_tail_keywords = [] # Generate combinations for modifier in modifiers: # Modifier + base variation1 = f"{modifier} {base_keyword}" long_tail_keywords.append({ 'keyword': variation1, 'pattern': 'modifier_base', 'estimated_competition': 'low', 'rationale': f"Less competitive variation of '{base_keyword}'" }) # Base + modifier variation2 = f"{base_keyword} {modifier}" long_tail_keywords.append({ 'keyword': variation2, 'pattern': 'base_modifier', 'estimated_competition': 'low', 'rationale': f"Specific use-case variation of '{base_keyword}'" }) # Add question-based long-tail question_words = ['how', 'what', 'best', 'top'] for q_word in question_words: question_keyword = f"{q_word} {base_keyword}" long_tail_keywords.append({ 'keyword': question_keyword, 'pattern': 'question_based', 'estimated_competition': 'very_low', 'rationale': f"Informational search query" }) return long_tail_keywords def extract_keywords_from_text( self, text: str, min_word_length: int = 3 ) -> List[Tuple[str, int]]: """ Extract potential keywords from text (descriptions, reviews). Args: text: Text to analyze min_word_length: Minimum word length to consider Returns: List of (keyword, frequency) tuples """ # Clean and normalize text text = text.lower() text = re.sub(r'[^\w\s]', ' ', text) # Extract words words = text.split() # Filter by length words = [w for w in words if len(w) >= min_word_length] # Remove common stop words stop_words = { 'the', 'and', 'for', 'with', 'this', 'that', 'from', 'have', 'but', 'not', 'you', 'all', 'can', 'are', 'was', 'were', 'been' } words = [w for w in words if w not in stop_words] # Count frequency word_counts = Counter(words) # Extract 2-word phrases phrases = [] for i in range(len(words) - 1): phrase = f"{words[i]} {words[i+1]}" phrases.append(phrase) phrase_counts = Counter(phrases) # Combine and sort all_keywords = list(word_counts.items()) + list(phrase_counts.items()) all_keywords.sort(key=lambda x: x[1], reverse=True) return all_keywords[:50] # Top 50 def calculate_keyword_density( self, text: str, target_keywords: List[str] ) -> Dict[str, float]: """ Calculate keyword density in text. Args: text: Text to analyze (title, description) target_keywords: Keywords to check density for Returns: Dictionary of keyword: density (percentage) """ text_lower = text.lower() total_words = len(text_lower.split()) densities = {} for keyword in target_keywords: keyword_lower = keyword.lower() occurrences = text_lower.count(keyword_lower) density = (occurrences / total_words) * 100 if total_words > 0 else 0 densities[keyword] = round(density, 2) return densities def _calculate_competition_level(self, competing_apps: int) -> str: """Determine competition level based on number of competing apps.""" if competing_apps < self.COMPETITION_THRESHOLDS['low']: return 'low' elif competing_apps < self.COMPETITION_THRESHOLDS['medium']: return 'medium' elif competing_apps < self.COMPETITION_THRESHOLDS['high']: return 'high' else: return 'very_high' def _categorize_search_volume(self, search_volume: int) -> str: """Categorize search volume.""" if search_volume < self.VOLUME_CATEGORIES['very_low']: return 'very_low' elif search_volume < self.VOLUME_CATEGORIES['low']: return 'low' elif search_volume < self.VOLUME_CATEGORIES['medium']: return 'medium' elif search_volume < self.VOLUME_CATEGORIES['high']: return 'high' else: return 'very_high' def _calculate_keyword_difficulty( self, search_volume: int, competing_apps: int ) -> float: """ Calculate keyword difficulty score (0-100). Higher score = harder to rank. """ if competing_apps == 0: return 0.0 # Competition factor (0-1) competition_factor = min(competing_apps / 50000, 1.0) # Volume factor (0-1) - higher volume = more difficulty volume_factor = min(search_volume / 1000000, 1.0) # Difficulty score (weighted average) difficulty = (competition_factor * 0.7 + volume_factor * 0.3) * 100 return round(difficulty, 1) def _calculate_potential_score( self, search_volume: int, competing_apps: int, relevance_score: float ) -> float: """ Calculate overall keyword potential (0-100). Higher score = better opportunity. """ # Volume score (0-40 points) volume_score = min((search_volume / 100000) * 40, 40) # Competition score (0-30 points) - inverse relationship if competing_apps > 0: competition_score = max(30 - (competing_apps / 500), 0) else: competition_score = 30 # Relevance score (0-30 points) relevance_points = relevance_score * 30 total_score = volume_score + competition_score + relevance_points return round(min(total_score, 100), 1) def _generate_recommendation( self, potential_score: float, difficulty_score: float, relevance_score: float ) -> str: """Generate actionable recommendation for keyword.""" if relevance_score < 0.5: return "Low relevance - avoid targeting" if potential_score >= 70: return "High priority - target immediately" elif potential_score >= 50: if difficulty_score < 50: return "Good opportunity - include in metadata" else: return "Competitive - use in description, not title" elif potential_score >= 30: return "Secondary keyword - use for long-tail variations" else: return "Low potential - deprioritize" def _generate_comparison_summary( self, primary_keywords: List[Dict[str, Any]], secondary_keywords: List[Dict[str, Any]], long_tail_keywords: List[Dict[str, Any]] ) -> str: """Generate summary of keyword comparison.""" summary_parts = [] summary_parts.append( f"Identified {len(primary_keywords)} high-priority primary keywords." ) if primary_keywords: top_keyword = primary_keywords[0]['keyword'] summary_parts.append( f"Top recommendation: '{top_keyword}' (potential score: {primary_keywords[0]['potential_score']})." ) summary_parts.append( f"Found {len(secondary_keywords)} secondary keywords for description and metadata." ) summary_parts.append( f"Discovered {len(long_tail_keywords)} long-tail opportunities with lower competition." ) return " ".join(summary_parts) def analyze_keyword_set(keywords_data: List[Dict[str, Any]]) -> Dict[str, Any]: """ Convenience function to analyze a set of keywords. Args: keywords_data: List of keyword data dictionaries Returns: Complete analysis report """ analyzer = KeywordAnalyzer() return analyzer.compare_keywords(keywords_data)
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/business-marketing/app-store-optimization/keyword_analyzer.py", "license": "MIT License", "lines": 339, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/business-marketing/app-store-optimization/launch_checklist.py
""" Launch checklist module for App Store Optimization. Generates comprehensive pre-launch and update checklists. """ from typing import Dict, List, Any, Optional from datetime import datetime, timedelta class LaunchChecklistGenerator: """Generates comprehensive checklists for app launches and updates.""" def __init__(self, platform: str = 'both'): """ Initialize checklist generator. Args: platform: 'apple', 'google', or 'both' """ if platform not in ['apple', 'google', 'both']: raise ValueError("Platform must be 'apple', 'google', or 'both'") self.platform = platform def generate_prelaunch_checklist( self, app_info: Dict[str, Any], launch_date: Optional[str] = None ) -> Dict[str, Any]: """ Generate comprehensive pre-launch checklist. Args: app_info: App information (name, category, target_audience) launch_date: Target launch date (YYYY-MM-DD) Returns: Complete pre-launch checklist """ checklist = { 'app_info': app_info, 'launch_date': launch_date, 'checklists': {} } # Generate platform-specific checklists if self.platform in ['apple', 'both']: checklist['checklists']['apple'] = self._generate_apple_checklist(app_info) if self.platform in ['google', 'both']: checklist['checklists']['google'] = self._generate_google_checklist(app_info) # Add universal checklist items checklist['checklists']['universal'] = self._generate_universal_checklist(app_info) # Generate timeline if launch_date: checklist['timeline'] = self._generate_launch_timeline(launch_date) # Calculate completion status checklist['summary'] = self._calculate_checklist_summary(checklist['checklists']) return checklist def validate_app_store_compliance( self, app_data: Dict[str, Any], platform: str = 'apple' ) -> Dict[str, Any]: """ Validate compliance with app store guidelines. Args: app_data: App data including metadata, privacy policy, etc. platform: 'apple' or 'google' Returns: Compliance validation report """ validation_results = { 'platform': platform, 'is_compliant': True, 'errors': [], 'warnings': [], 'recommendations': [] } if platform == 'apple': self._validate_apple_compliance(app_data, validation_results) elif platform == 'google': self._validate_google_compliance(app_data, validation_results) # Determine overall compliance validation_results['is_compliant'] = len(validation_results['errors']) == 0 return validation_results def create_update_plan( self, current_version: str, planned_features: List[str], update_frequency: str = 'monthly' ) -> Dict[str, Any]: """ Create update cadence and feature rollout plan. Args: current_version: Current app version planned_features: List of planned features update_frequency: 'weekly', 'biweekly', 'monthly', 'quarterly' Returns: Update plan with cadence and feature schedule """ # Calculate next versions next_versions = self._calculate_next_versions( current_version, update_frequency, len(planned_features) ) # Distribute features across versions feature_schedule = self._distribute_features( planned_features, next_versions ) # Generate "What's New" templates whats_new_templates = [ self._generate_whats_new_template(version_data) for version_data in feature_schedule ] return { 'current_version': current_version, 'update_frequency': update_frequency, 'planned_updates': len(feature_schedule), 'feature_schedule': feature_schedule, 'whats_new_templates': whats_new_templates, 'recommendations': self._generate_update_recommendations(update_frequency) } def optimize_launch_timing( self, app_category: str, target_audience: str, current_date: Optional[str] = None ) -> Dict[str, Any]: """ Recommend optimal launch timing. Args: app_category: App category target_audience: Target audience description current_date: Current date (YYYY-MM-DD), defaults to today Returns: Launch timing recommendations """ if not current_date: current_date = datetime.now().strftime('%Y-%m-%d') # Analyze launch timing factors day_of_week_rec = self._recommend_day_of_week(app_category) seasonal_rec = self._recommend_seasonal_timing(app_category, current_date) competitive_rec = self._analyze_competitive_timing(app_category) # Calculate optimal dates optimal_dates = self._calculate_optimal_dates( current_date, day_of_week_rec, seasonal_rec ) return { 'current_date': current_date, 'optimal_launch_dates': optimal_dates, 'day_of_week_recommendation': day_of_week_rec, 'seasonal_considerations': seasonal_rec, 'competitive_timing': competitive_rec, 'final_recommendation': self._generate_timing_recommendation( optimal_dates, seasonal_rec ) } def plan_seasonal_campaigns( self, app_category: str, current_month: int = None ) -> Dict[str, Any]: """ Identify seasonal opportunities for ASO campaigns. Args: app_category: App category current_month: Current month (1-12), defaults to current Returns: Seasonal campaign opportunities """ if not current_month: current_month = datetime.now().month # Identify relevant seasonal events seasonal_opportunities = self._identify_seasonal_opportunities( app_category, current_month ) # Generate campaign ideas campaigns = [ self._generate_seasonal_campaign(opportunity) for opportunity in seasonal_opportunities ] return { 'current_month': current_month, 'category': app_category, 'seasonal_opportunities': seasonal_opportunities, 'campaign_ideas': campaigns, 'implementation_timeline': self._create_seasonal_timeline(campaigns) } def _generate_apple_checklist(self, app_info: Dict[str, Any]) -> List[Dict[str, Any]]: """Generate Apple App Store specific checklist.""" return [ { 'category': 'App Store Connect Setup', 'items': [ {'task': 'App Store Connect account created', 'status': 'pending'}, {'task': 'App bundle ID registered', 'status': 'pending'}, {'task': 'App Privacy declarations completed', 'status': 'pending'}, {'task': 'Age rating questionnaire completed', 'status': 'pending'} ] }, { 'category': 'Metadata (Apple)', 'items': [ {'task': 'App title (30 chars max)', 'status': 'pending'}, {'task': 'Subtitle (30 chars max)', 'status': 'pending'}, {'task': 'Promotional text (170 chars max)', 'status': 'pending'}, {'task': 'Description (4000 chars max)', 'status': 'pending'}, {'task': 'Keywords (100 chars, comma-separated)', 'status': 'pending'}, {'task': 'Category selection (primary + secondary)', 'status': 'pending'} ] }, { 'category': 'Visual Assets (Apple)', 'items': [ {'task': 'App icon (1024x1024px)', 'status': 'pending'}, {'task': 'Screenshots (iPhone 6.7" required)', 'status': 'pending'}, {'task': 'Screenshots (iPhone 5.5" required)', 'status': 'pending'}, {'task': 'Screenshots (iPad Pro 12.9" if iPad app)', 'status': 'pending'}, {'task': 'App preview video (optional but recommended)', 'status': 'pending'} ] }, { 'category': 'Technical Requirements (Apple)', 'items': [ {'task': 'Build uploaded to App Store Connect', 'status': 'pending'}, {'task': 'TestFlight testing completed', 'status': 'pending'}, {'task': 'App tested on required iOS versions', 'status': 'pending'}, {'task': 'Crash-free rate > 99%', 'status': 'pending'}, {'task': 'All links in app/metadata working', 'status': 'pending'} ] }, { 'category': 'Legal & Privacy (Apple)', 'items': [ {'task': 'Privacy Policy URL provided', 'status': 'pending'}, {'task': 'Terms of Service URL (if applicable)', 'status': 'pending'}, {'task': 'Data collection declarations accurate', 'status': 'pending'}, {'task': 'Third-party SDKs disclosed', 'status': 'pending'} ] } ] def _generate_google_checklist(self, app_info: Dict[str, Any]) -> List[Dict[str, Any]]: """Generate Google Play Store specific checklist.""" return [ { 'category': 'Play Console Setup', 'items': [ {'task': 'Google Play Console account created', 'status': 'pending'}, {'task': 'Developer profile completed', 'status': 'pending'}, {'task': 'Payment merchant account linked (if paid app)', 'status': 'pending'}, {'task': 'Content rating questionnaire completed', 'status': 'pending'} ] }, { 'category': 'Metadata (Google)', 'items': [ {'task': 'App title (50 chars max)', 'status': 'pending'}, {'task': 'Short description (80 chars max)', 'status': 'pending'}, {'task': 'Full description (4000 chars max)', 'status': 'pending'}, {'task': 'Category selection', 'status': 'pending'}, {'task': 'Tags (up to 5)', 'status': 'pending'} ] }, { 'category': 'Visual Assets (Google)', 'items': [ {'task': 'App icon (512x512px)', 'status': 'pending'}, {'task': 'Feature graphic (1024x500px)', 'status': 'pending'}, {'task': 'Screenshots (2-8 required, phone)', 'status': 'pending'}, {'task': 'Screenshots (tablet, if applicable)', 'status': 'pending'}, {'task': 'Promo video (YouTube link, optional)', 'status': 'pending'} ] }, { 'category': 'Technical Requirements (Google)', 'items': [ {'task': 'APK/AAB uploaded to Play Console', 'status': 'pending'}, {'task': 'Internal testing completed', 'status': 'pending'}, {'task': 'App tested on required Android versions', 'status': 'pending'}, {'task': 'Target API level meets requirements', 'status': 'pending'}, {'task': 'All permissions justified', 'status': 'pending'} ] }, { 'category': 'Legal & Privacy (Google)', 'items': [ {'task': 'Privacy Policy URL provided', 'status': 'pending'}, {'task': 'Data safety section completed', 'status': 'pending'}, {'task': 'Ads disclosure (if applicable)', 'status': 'pending'}, {'task': 'In-app purchase disclosure (if applicable)', 'status': 'pending'} ] } ] def _generate_universal_checklist(self, app_info: Dict[str, Any]) -> List[Dict[str, Any]]: """Generate universal (both platforms) checklist.""" return [ { 'category': 'Pre-Launch Marketing', 'items': [ {'task': 'Landing page created', 'status': 'pending'}, {'task': 'Social media accounts setup', 'status': 'pending'}, {'task': 'Press kit prepared', 'status': 'pending'}, {'task': 'Beta tester feedback collected', 'status': 'pending'}, {'task': 'Launch announcement drafted', 'status': 'pending'} ] }, { 'category': 'ASO Preparation', 'items': [ {'task': 'Keyword research completed', 'status': 'pending'}, {'task': 'Competitor analysis done', 'status': 'pending'}, {'task': 'A/B test plan created for post-launch', 'status': 'pending'}, {'task': 'Analytics tracking configured', 'status': 'pending'} ] }, { 'category': 'Quality Assurance', 'items': [ {'task': 'All core features tested', 'status': 'pending'}, {'task': 'User flows validated', 'status': 'pending'}, {'task': 'Performance testing completed', 'status': 'pending'}, {'task': 'Accessibility features tested', 'status': 'pending'}, {'task': 'Security audit completed', 'status': 'pending'} ] }, { 'category': 'Support Infrastructure', 'items': [ {'task': 'Support email/system setup', 'status': 'pending'}, {'task': 'FAQ page created', 'status': 'pending'}, {'task': 'Documentation for users prepared', 'status': 'pending'}, {'task': 'Team trained on handling reviews', 'status': 'pending'} ] } ] def _generate_launch_timeline(self, launch_date: str) -> List[Dict[str, Any]]: """Generate timeline with milestones leading to launch.""" launch_dt = datetime.strptime(launch_date, '%Y-%m-%d') milestones = [ { 'date': (launch_dt - timedelta(days=90)).strftime('%Y-%m-%d'), 'milestone': '90 days before: Complete keyword research and competitor analysis' }, { 'date': (launch_dt - timedelta(days=60)).strftime('%Y-%m-%d'), 'milestone': '60 days before: Finalize metadata and visual assets' }, { 'date': (launch_dt - timedelta(days=45)).strftime('%Y-%m-%d'), 'milestone': '45 days before: Begin beta testing program' }, { 'date': (launch_dt - timedelta(days=30)).strftime('%Y-%m-%d'), 'milestone': '30 days before: Submit app for review (Apple typically takes 1-2 days, Google instant)' }, { 'date': (launch_dt - timedelta(days=14)).strftime('%Y-%m-%d'), 'milestone': '14 days before: Prepare launch marketing materials' }, { 'date': (launch_dt - timedelta(days=7)).strftime('%Y-%m-%d'), 'milestone': '7 days before: Set up analytics and monitoring' }, { 'date': launch_dt.strftime('%Y-%m-%d'), 'milestone': 'Launch Day: Release app and execute marketing plan' }, { 'date': (launch_dt + timedelta(days=7)).strftime('%Y-%m-%d'), 'milestone': '7 days after: Monitor metrics, respond to reviews, address critical issues' }, { 'date': (launch_dt + timedelta(days=30)).strftime('%Y-%m-%d'), 'milestone': '30 days after: Analyze launch metrics, plan first update' } ] return milestones def _calculate_checklist_summary(self, checklists: Dict[str, List[Dict[str, Any]]]) -> Dict[str, Any]: """Calculate completion summary.""" total_items = 0 completed_items = 0 for platform, categories in checklists.items(): for category in categories: for item in category['items']: total_items += 1 if item['status'] == 'completed': completed_items += 1 completion_percentage = (completed_items / total_items * 100) if total_items > 0 else 0 return { 'total_items': total_items, 'completed_items': completed_items, 'pending_items': total_items - completed_items, 'completion_percentage': round(completion_percentage, 1), 'is_ready_to_launch': completion_percentage == 100 } def _validate_apple_compliance( self, app_data: Dict[str, Any], validation_results: Dict[str, Any] ) -> None: """Validate Apple App Store compliance.""" # Check for required fields if not app_data.get('privacy_policy_url'): validation_results['errors'].append("Privacy Policy URL is required") if not app_data.get('app_icon'): validation_results['errors'].append("App icon (1024x1024px) is required") # Check metadata character limits title = app_data.get('title', '') if len(title) > 30: validation_results['errors'].append(f"Title exceeds 30 characters ({len(title)})") # Warnings for best practices subtitle = app_data.get('subtitle', '') if not subtitle: validation_results['warnings'].append("Subtitle is empty - consider adding for better discoverability") keywords = app_data.get('keywords', '') if len(keywords) < 80: validation_results['warnings'].append( f"Keywords field underutilized ({len(keywords)}/100 chars) - add more keywords" ) def _validate_google_compliance( self, app_data: Dict[str, Any], validation_results: Dict[str, Any] ) -> None: """Validate Google Play Store compliance.""" # Check for required fields if not app_data.get('privacy_policy_url'): validation_results['errors'].append("Privacy Policy URL is required") if not app_data.get('feature_graphic'): validation_results['errors'].append("Feature graphic (1024x500px) is required") # Check metadata character limits title = app_data.get('title', '') if len(title) > 50: validation_results['errors'].append(f"Title exceeds 50 characters ({len(title)})") short_desc = app_data.get('short_description', '') if len(short_desc) > 80: validation_results['errors'].append(f"Short description exceeds 80 characters ({len(short_desc)})") # Warnings if not short_desc: validation_results['warnings'].append("Short description is empty") def _calculate_next_versions( self, current_version: str, update_frequency: str, feature_count: int ) -> List[str]: """Calculate next version numbers.""" # Parse current version (assume semantic versioning) parts = current_version.split('.') major, minor, patch = int(parts[0]), int(parts[1]), int(parts[2] if len(parts) > 2 else 0) versions = [] for i in range(feature_count): if update_frequency == 'weekly': patch += 1 elif update_frequency == 'biweekly': patch += 1 elif update_frequency == 'monthly': minor += 1 patch = 0 else: # quarterly minor += 1 patch = 0 versions.append(f"{major}.{minor}.{patch}") return versions def _distribute_features( self, features: List[str], versions: List[str] ) -> List[Dict[str, Any]]: """Distribute features across versions.""" features_per_version = max(1, len(features) // len(versions)) schedule = [] for i, version in enumerate(versions): start_idx = i * features_per_version end_idx = start_idx + features_per_version if i < len(versions) - 1 else len(features) schedule.append({ 'version': version, 'features': features[start_idx:end_idx], 'release_priority': 'high' if i == 0 else ('medium' if i < len(versions) // 2 else 'low') }) return schedule def _generate_whats_new_template(self, version_data: Dict[str, Any]) -> Dict[str, str]: """Generate What's New template for version.""" features_list = '\n'.join([f"• {feature}" for feature in version_data['features']]) template = f"""Version {version_data['version']} {features_list} We're constantly improving your experience. Thanks for using [App Name]! Have feedback? Contact us at support@[company].com""" return { 'version': version_data['version'], 'template': template } def _generate_update_recommendations(self, update_frequency: str) -> List[str]: """Generate recommendations for update strategy.""" recommendations = [] if update_frequency == 'weekly': recommendations.append("Weekly updates show active development but ensure quality doesn't suffer") elif update_frequency == 'monthly': recommendations.append("Monthly updates are optimal for most apps - balance features and stability") recommendations.extend([ "Include bug fixes in every update", "Update 'What's New' section with each release", "Respond to reviews mentioning fixed issues" ]) return recommendations def _recommend_day_of_week(self, app_category: str) -> Dict[str, Any]: """Recommend best day of week to launch.""" # General recommendations based on category if app_category.lower() in ['games', 'entertainment']: return { 'recommended_day': 'Thursday', 'rationale': 'People download entertainment apps before weekend' } elif app_category.lower() in ['productivity', 'business']: return { 'recommended_day': 'Tuesday', 'rationale': 'Business users most active mid-week' } else: return { 'recommended_day': 'Wednesday', 'rationale': 'Mid-week provides good balance and review potential' } def _recommend_seasonal_timing(self, app_category: str, current_date: str) -> Dict[str, Any]: """Recommend seasonal timing considerations.""" current_dt = datetime.strptime(current_date, '%Y-%m-%d') month = current_dt.month # Avoid certain periods avoid_periods = [] if month == 12: avoid_periods.append("Late December - low user engagement during holidays") if month in [7, 8]: avoid_periods.append("Summer months - some categories see lower engagement") # Recommend periods good_periods = [] if month in [1, 9]: good_periods.append("New Year/Back-to-school - high user engagement") if month in [10, 11]: good_periods.append("Pre-holiday season - good for shopping/gift apps") return { 'current_month': month, 'avoid_periods': avoid_periods, 'good_periods': good_periods } def _analyze_competitive_timing(self, app_category: str) -> Dict[str, str]: """Analyze competitive timing considerations.""" return { 'recommendation': 'Research competitor launch schedules in your category', 'strategy': 'Avoid launching same week as major competitor updates' } def _calculate_optimal_dates( self, current_date: str, day_rec: Dict[str, Any], seasonal_rec: Dict[str, Any] ) -> List[str]: """Calculate optimal launch dates.""" current_dt = datetime.strptime(current_date, '%Y-%m-%d') # Find next occurrence of recommended day target_day = day_rec['recommended_day'] days_map = {'Monday': 0, 'Tuesday': 1, 'Wednesday': 2, 'Thursday': 3, 'Friday': 4} target_day_num = days_map.get(target_day, 2) days_ahead = (target_day_num - current_dt.weekday()) % 7 if days_ahead == 0: days_ahead = 7 next_target_date = current_dt + timedelta(days=days_ahead) optimal_dates = [ next_target_date.strftime('%Y-%m-%d'), (next_target_date + timedelta(days=7)).strftime('%Y-%m-%d'), (next_target_date + timedelta(days=14)).strftime('%Y-%m-%d') ] return optimal_dates def _generate_timing_recommendation( self, optimal_dates: List[str], seasonal_rec: Dict[str, Any] ) -> str: """Generate final timing recommendation.""" if seasonal_rec['avoid_periods']: return f"Consider launching in {optimal_dates[1]} to avoid {seasonal_rec['avoid_periods'][0]}" elif seasonal_rec['good_periods']: return f"Launch on {optimal_dates[0]} to capitalize on {seasonal_rec['good_periods'][0]}" else: return f"Recommended launch date: {optimal_dates[0]}" def _identify_seasonal_opportunities( self, app_category: str, current_month: int ) -> List[Dict[str, Any]]: """Identify seasonal opportunities for category.""" opportunities = [] # Universal opportunities if current_month == 1: opportunities.append({ 'event': 'New Year Resolutions', 'dates': 'January 1-31', 'relevance': 'high' if app_category.lower() in ['health', 'fitness', 'productivity'] else 'medium' }) if current_month in [11, 12]: opportunities.append({ 'event': 'Holiday Shopping Season', 'dates': 'November-December', 'relevance': 'high' if app_category.lower() in ['shopping', 'gifts'] else 'low' }) # Category-specific if app_category.lower() == 'education' and current_month in [8, 9]: opportunities.append({ 'event': 'Back to School', 'dates': 'August-September', 'relevance': 'high' }) return opportunities def _generate_seasonal_campaign(self, opportunity: Dict[str, Any]) -> Dict[str, Any]: """Generate campaign idea for seasonal opportunity.""" return { 'event': opportunity['event'], 'campaign_idea': f"Create themed visuals and messaging for {opportunity['event']}", 'metadata_updates': 'Update app description and screenshots with seasonal themes', 'promotion_strategy': 'Consider limited-time features or discounts' } def _create_seasonal_timeline(self, campaigns: List[Dict[str, Any]]) -> List[str]: """Create implementation timeline for campaigns.""" return [ f"30 days before: Plan {campaign['event']} campaign strategy" for campaign in campaigns ] def generate_launch_checklist( platform: str, app_info: Dict[str, Any], launch_date: Optional[str] = None ) -> Dict[str, Any]: """ Convenience function to generate launch checklist. Args: platform: Platform ('apple', 'google', or 'both') app_info: App information launch_date: Target launch date Returns: Complete launch checklist """ generator = LaunchChecklistGenerator(platform) return generator.generate_prelaunch_checklist(app_info, launch_date)
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/business-marketing/app-store-optimization/launch_checklist.py", "license": "MIT License", "lines": 638, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/business-marketing/app-store-optimization/localization_helper.py
""" Localization helper module for App Store Optimization. Manages multi-language ASO optimization strategies. """ from typing import Dict, List, Any, Optional, Tuple class LocalizationHelper: """Helps manage multi-language ASO optimization.""" # Priority markets by language (based on app store revenue and user base) PRIORITY_MARKETS = { 'tier_1': [ {'language': 'en-US', 'market': 'United States', 'revenue_share': 0.25}, {'language': 'zh-CN', 'market': 'China', 'revenue_share': 0.20}, {'language': 'ja-JP', 'market': 'Japan', 'revenue_share': 0.10}, {'language': 'de-DE', 'market': 'Germany', 'revenue_share': 0.08}, {'language': 'en-GB', 'market': 'United Kingdom', 'revenue_share': 0.06} ], 'tier_2': [ {'language': 'fr-FR', 'market': 'France', 'revenue_share': 0.05}, {'language': 'ko-KR', 'market': 'South Korea', 'revenue_share': 0.05}, {'language': 'es-ES', 'market': 'Spain', 'revenue_share': 0.03}, {'language': 'it-IT', 'market': 'Italy', 'revenue_share': 0.03}, {'language': 'pt-BR', 'market': 'Brazil', 'revenue_share': 0.03} ], 'tier_3': [ {'language': 'ru-RU', 'market': 'Russia', 'revenue_share': 0.02}, {'language': 'es-MX', 'market': 'Mexico', 'revenue_share': 0.02}, {'language': 'nl-NL', 'market': 'Netherlands', 'revenue_share': 0.02}, {'language': 'sv-SE', 'market': 'Sweden', 'revenue_share': 0.01}, {'language': 'pl-PL', 'market': 'Poland', 'revenue_share': 0.01} ] } # Character limit multipliers by language (some languages need more/less space) CHAR_MULTIPLIERS = { 'en': 1.0, 'zh': 0.6, # Chinese characters are more compact 'ja': 0.7, # Japanese uses kanji 'ko': 0.8, # Korean is relatively compact 'de': 1.3, # German words are typically longer 'fr': 1.2, # French tends to be longer 'es': 1.1, # Spanish slightly longer 'pt': 1.1, # Portuguese similar to Spanish 'ru': 1.1, # Russian similar length 'ar': 1.0, # Arabic varies 'it': 1.1 # Italian similar to Spanish } def __init__(self, app_category: str = 'general'): """ Initialize localization helper. Args: app_category: App category to prioritize relevant markets """ self.app_category = app_category self.localization_plans = [] def identify_target_markets( self, current_market: str = 'en-US', budget_level: str = 'medium', target_market_count: int = 5 ) -> Dict[str, Any]: """ Recommend priority markets for localization. Args: current_market: Current/primary market budget_level: 'low', 'medium', or 'high' target_market_count: Number of markets to target Returns: Prioritized market recommendations """ # Determine tier priorities based on budget if budget_level == 'low': priority_tiers = ['tier_1'] max_markets = min(target_market_count, 3) elif budget_level == 'medium': priority_tiers = ['tier_1', 'tier_2'] max_markets = min(target_market_count, 8) else: # high budget priority_tiers = ['tier_1', 'tier_2', 'tier_3'] max_markets = target_market_count # Collect markets from priority tiers recommended_markets = [] for tier in priority_tiers: for market in self.PRIORITY_MARKETS[tier]: if market['language'] != current_market: recommended_markets.append({ **market, 'tier': tier, 'estimated_translation_cost': self._estimate_translation_cost( market['language'] ) }) # Sort by revenue share and limit recommended_markets.sort(key=lambda x: x['revenue_share'], reverse=True) recommended_markets = recommended_markets[:max_markets] # Calculate potential ROI total_potential_revenue_share = sum(m['revenue_share'] for m in recommended_markets) return { 'recommended_markets': recommended_markets, 'total_markets': len(recommended_markets), 'estimated_total_revenue_lift': f"{total_potential_revenue_share*100:.1f}%", 'estimated_cost': self._estimate_total_localization_cost(recommended_markets), 'implementation_priority': self._prioritize_implementation(recommended_markets) } def translate_metadata( self, source_metadata: Dict[str, str], source_language: str, target_language: str, platform: str = 'apple' ) -> Dict[str, Any]: """ Generate localized metadata with character limit considerations. Args: source_metadata: Original metadata (title, description, etc.) source_language: Source language code (e.g., 'en') target_language: Target language code (e.g., 'es') platform: 'apple' or 'google' Returns: Localized metadata with character limit validation """ # Get character multiplier target_lang_code = target_language.split('-')[0] char_multiplier = self.CHAR_MULTIPLIERS.get(target_lang_code, 1.0) # Platform-specific limits if platform == 'apple': limits = {'title': 30, 'subtitle': 30, 'description': 4000, 'keywords': 100} else: limits = {'title': 50, 'short_description': 80, 'description': 4000} localized_metadata = {} warnings = [] for field, text in source_metadata.items(): if field not in limits: continue # Estimate target length estimated_length = int(len(text) * char_multiplier) limit = limits[field] localized_metadata[field] = { 'original_text': text, 'original_length': len(text), 'estimated_target_length': estimated_length, 'character_limit': limit, 'fits_within_limit': estimated_length <= limit, 'translation_notes': self._get_translation_notes( field, target_language, estimated_length, limit ) } if estimated_length > limit: warnings.append( f"{field}: Estimated length ({estimated_length}) may exceed limit ({limit}) - " f"condensing may be required" ) return { 'source_language': source_language, 'target_language': target_language, 'platform': platform, 'localized_fields': localized_metadata, 'character_multiplier': char_multiplier, 'warnings': warnings, 'recommendations': self._generate_translation_recommendations( target_language, warnings ) } def adapt_keywords( self, source_keywords: List[str], source_language: str, target_language: str, target_market: str ) -> Dict[str, Any]: """ Adapt keywords for target market (not just direct translation). Args: source_keywords: Original keywords source_language: Source language code target_language: Target language code target_market: Target market (e.g., 'France', 'Japan') Returns: Adapted keyword recommendations """ # Cultural adaptation considerations cultural_notes = self._get_cultural_keyword_considerations(target_market) # Search behavior differences search_patterns = self._get_search_patterns(target_market) adapted_keywords = [] for keyword in source_keywords: adapted_keywords.append({ 'source_keyword': keyword, 'adaptation_strategy': self._determine_adaptation_strategy( keyword, target_market ), 'cultural_considerations': cultural_notes.get(keyword, []), 'priority': 'high' if keyword in source_keywords[:3] else 'medium' }) return { 'source_language': source_language, 'target_language': target_language, 'target_market': target_market, 'adapted_keywords': adapted_keywords, 'search_behavior_notes': search_patterns, 'recommendations': [ 'Use native speakers for keyword research', 'Test keywords with local users before finalizing', 'Consider local competitors\' keyword strategies', 'Monitor search trends in target market' ] } def validate_translations( self, translated_metadata: Dict[str, str], target_language: str, platform: str = 'apple' ) -> Dict[str, Any]: """ Validate translated metadata for character limits and quality. Args: translated_metadata: Translated text fields target_language: Target language code platform: 'apple' or 'google' Returns: Validation report """ # Platform limits if platform == 'apple': limits = {'title': 30, 'subtitle': 30, 'description': 4000, 'keywords': 100} else: limits = {'title': 50, 'short_description': 80, 'description': 4000} validation_results = { 'is_valid': True, 'field_validations': {}, 'errors': [], 'warnings': [] } for field, text in translated_metadata.items(): if field not in limits: continue actual_length = len(text) limit = limits[field] is_within_limit = actual_length <= limit validation_results['field_validations'][field] = { 'text': text, 'length': actual_length, 'limit': limit, 'is_valid': is_within_limit, 'usage_percentage': round((actual_length / limit) * 100, 1) } if not is_within_limit: validation_results['is_valid'] = False validation_results['errors'].append( f"{field} exceeds limit: {actual_length}/{limit} characters" ) # Quality checks quality_issues = self._check_translation_quality( translated_metadata, target_language ) validation_results['quality_checks'] = quality_issues if quality_issues: validation_results['warnings'].extend( [f"Quality issue: {issue}" for issue in quality_issues] ) return validation_results def calculate_localization_roi( self, target_markets: List[str], current_monthly_downloads: int, localization_cost: float, expected_lift_percentage: float = 0.15 ) -> Dict[str, Any]: """ Estimate ROI of localization investment. Args: target_markets: List of market codes current_monthly_downloads: Current monthly downloads localization_cost: Total cost to localize expected_lift_percentage: Expected download increase (default 15%) Returns: ROI analysis """ # Estimate market-specific lift market_data = [] total_expected_lift = 0 for market_code in target_markets: # Find market in priority lists market_info = None for tier_name, markets in self.PRIORITY_MARKETS.items(): for m in markets: if m['language'] == market_code: market_info = m break if not market_info: continue # Estimate downloads from this market market_downloads = int(current_monthly_downloads * market_info['revenue_share']) expected_increase = int(market_downloads * expected_lift_percentage) total_expected_lift += expected_increase market_data.append({ 'market': market_info['market'], 'current_monthly_downloads': market_downloads, 'expected_increase': expected_increase, 'revenue_potential': market_info['revenue_share'] }) # Calculate payback period (assuming $2 revenue per download) revenue_per_download = 2.0 monthly_additional_revenue = total_expected_lift * revenue_per_download payback_months = (localization_cost / monthly_additional_revenue) if monthly_additional_revenue > 0 else float('inf') return { 'markets_analyzed': len(market_data), 'market_breakdown': market_data, 'total_expected_monthly_lift': total_expected_lift, 'expected_monthly_revenue_increase': f"${monthly_additional_revenue:,.2f}", 'localization_cost': f"${localization_cost:,.2f}", 'payback_period_months': round(payback_months, 1) if payback_months != float('inf') else 'N/A', 'annual_roi': f"{((monthly_additional_revenue * 12 - localization_cost) / localization_cost * 100):.1f}%" if payback_months != float('inf') else 'Negative', 'recommendation': self._generate_roi_recommendation(payback_months) } def _estimate_translation_cost(self, language: str) -> Dict[str, float]: """Estimate translation cost for a language.""" # Base cost per word (professional translation) base_cost_per_word = 0.12 # Language-specific multipliers multipliers = { 'zh-CN': 1.5, # Chinese requires specialist 'ja-JP': 1.5, # Japanese requires specialist 'ko-KR': 1.3, 'ar-SA': 1.4, # Arabic (right-to-left) 'default': 1.0 } multiplier = multipliers.get(language, multipliers['default']) # Typical word counts for app store metadata typical_word_counts = { 'title': 5, 'subtitle': 5, 'description': 300, 'keywords': 20, 'screenshots': 50 # Caption text } total_words = sum(typical_word_counts.values()) estimated_cost = total_words * base_cost_per_word * multiplier return { 'cost_per_word': base_cost_per_word * multiplier, 'total_words': total_words, 'estimated_cost': round(estimated_cost, 2) } def _estimate_total_localization_cost(self, markets: List[Dict[str, Any]]) -> str: """Estimate total cost for multiple markets.""" total = sum(m['estimated_translation_cost']['estimated_cost'] for m in markets) return f"${total:,.2f}" def _prioritize_implementation(self, markets: List[Dict[str, Any]]) -> List[Dict[str, str]]: """Create phased implementation plan.""" phases = [] # Phase 1: Top revenue markets phase_1 = [m for m in markets[:3]] if phase_1: phases.append({ 'phase': 'Phase 1 (First 30 days)', 'markets': ', '.join([m['market'] for m in phase_1]), 'rationale': 'Highest revenue potential markets' }) # Phase 2: Remaining tier 1 and top tier 2 phase_2 = [m for m in markets[3:6]] if phase_2: phases.append({ 'phase': 'Phase 2 (Days 31-60)', 'markets': ', '.join([m['market'] for m in phase_2]), 'rationale': 'Strong revenue markets with good ROI' }) # Phase 3: Remaining markets phase_3 = [m for m in markets[6:]] if phase_3: phases.append({ 'phase': 'Phase 3 (Days 61-90)', 'markets': ', '.join([m['market'] for m in phase_3]), 'rationale': 'Complete global coverage' }) return phases def _get_translation_notes( self, field: str, target_language: str, estimated_length: int, limit: int ) -> List[str]: """Get translation-specific notes for field.""" notes = [] if estimated_length > limit: notes.append(f"Condensing required - aim for {limit - 10} characters to allow buffer") if field == 'title' and target_language.startswith('zh'): notes.append("Chinese characters convey more meaning - may need fewer characters") if field == 'keywords' and target_language.startswith('de'): notes.append("German compound words may be longer - prioritize shorter keywords") return notes def _generate_translation_recommendations( self, target_language: str, warnings: List[str] ) -> List[str]: """Generate translation recommendations.""" recommendations = [ "Use professional native speakers for translation", "Test translations with local users before finalizing" ] if warnings: recommendations.append("Work with translator to condense text while preserving meaning") if target_language.startswith('zh') or target_language.startswith('ja'): recommendations.append("Consider cultural context and local idioms") return recommendations def _get_cultural_keyword_considerations(self, target_market: str) -> Dict[str, List[str]]: """Get cultural considerations for keywords by market.""" # Simplified example - real implementation would be more comprehensive considerations = { 'China': ['Avoid politically sensitive terms', 'Consider local alternatives to blocked services'], 'Japan': ['Honorific language important', 'Technical terms often use katakana'], 'Germany': ['Privacy and security terms resonate', 'Efficiency and quality valued'], 'France': ['French language protection laws', 'Prefer French terms over English'], 'default': ['Research local search behavior', 'Test with native speakers'] } return considerations.get(target_market, considerations['default']) def _get_search_patterns(self, target_market: str) -> List[str]: """Get search pattern notes for market.""" patterns = { 'China': ['Use both simplified characters and romanization', 'Brand names often romanized'], 'Japan': ['Mix of kanji, hiragana, and katakana', 'English words common in tech'], 'Germany': ['Compound words common', 'Specific technical terminology'], 'default': ['Research local search trends', 'Monitor competitor keywords'] } return patterns.get(target_market, patterns['default']) def _determine_adaptation_strategy(self, keyword: str, target_market: str) -> str: """Determine how to adapt keyword for market.""" # Simplified logic if target_market in ['China', 'Japan', 'Korea']: return 'full_localization' # Complete translation needed elif target_market in ['Germany', 'France', 'Spain']: return 'adapt_and_translate' # Some adaptation needed else: return 'direct_translation' # Direct translation usually sufficient def _check_translation_quality( self, translated_metadata: Dict[str, str], target_language: str ) -> List[str]: """Basic quality checks for translations.""" issues = [] # Check for untranslated placeholders for field, text in translated_metadata.items(): if '[' in text or '{' in text or 'TODO' in text.upper(): issues.append(f"{field} contains placeholder text") # Check for excessive punctuation for field, text in translated_metadata.items(): if text.count('!') > 3: issues.append(f"{field} has excessive exclamation marks") return issues def _generate_roi_recommendation(self, payback_months: float) -> str: """Generate ROI recommendation.""" if payback_months <= 3: return "Excellent ROI - proceed immediately" elif payback_months <= 6: return "Good ROI - recommended investment" elif payback_months <= 12: return "Moderate ROI - consider if strategic market" else: return "Low ROI - reconsider or focus on higher-priority markets first" def plan_localization_strategy( current_market: str, budget_level: str, monthly_downloads: int ) -> Dict[str, Any]: """ Convenience function to plan localization strategy. Args: current_market: Current market code budget_level: Budget level monthly_downloads: Current monthly downloads Returns: Complete localization plan """ helper = LocalizationHelper() target_markets = helper.identify_target_markets( current_market=current_market, budget_level=budget_level ) # Extract market codes market_codes = [m['language'] for m in target_markets['recommended_markets']] # Calculate ROI estimated_cost = float(target_markets['estimated_cost'].replace('$', '').replace(',', '')) roi_analysis = helper.calculate_localization_roi( market_codes, monthly_downloads, estimated_cost ) return { 'target_markets': target_markets, 'roi_analysis': roi_analysis }
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/business-marketing/app-store-optimization/localization_helper.py", "license": "MIT License", "lines": 497, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/business-marketing/app-store-optimization/metadata_optimizer.py
""" Metadata optimization module for App Store Optimization. Optimizes titles, descriptions, and keyword fields with platform-specific character limit validation. """ from typing import Dict, List, Any, Optional, Tuple import re class MetadataOptimizer: """Optimizes app store metadata for maximum discoverability and conversion.""" # Platform-specific character limits CHAR_LIMITS = { 'apple': { 'title': 30, 'subtitle': 30, 'promotional_text': 170, 'description': 4000, 'keywords': 100, 'whats_new': 4000 }, 'google': { 'title': 50, 'short_description': 80, 'full_description': 4000 } } def __init__(self, platform: str = 'apple'): """ Initialize metadata optimizer. Args: platform: 'apple' or 'google' """ if platform not in ['apple', 'google']: raise ValueError("Platform must be 'apple' or 'google'") self.platform = platform self.limits = self.CHAR_LIMITS[platform] def optimize_title( self, app_name: str, target_keywords: List[str], include_brand: bool = True ) -> Dict[str, Any]: """ Optimize app title with keyword integration. Args: app_name: Your app's brand name target_keywords: List of keywords to potentially include include_brand: Whether to include brand name Returns: Optimized title options with analysis """ max_length = self.limits['title'] title_options = [] # Option 1: Brand name only if include_brand: option1 = app_name[:max_length] title_options.append({ 'title': option1, 'length': len(option1), 'remaining_chars': max_length - len(option1), 'keywords_included': [], 'strategy': 'brand_only', 'pros': ['Maximum brand recognition', 'Clean and simple'], 'cons': ['No keyword targeting', 'Lower discoverability'] }) # Option 2: Brand + Primary Keyword if target_keywords: primary_keyword = target_keywords[0] option2 = self._build_title_with_keywords( app_name, [primary_keyword], max_length ) if option2: title_options.append({ 'title': option2, 'length': len(option2), 'remaining_chars': max_length - len(option2), 'keywords_included': [primary_keyword], 'strategy': 'brand_plus_primary', 'pros': ['Targets main keyword', 'Maintains brand identity'], 'cons': ['Limited keyword coverage'] }) # Option 3: Brand + Multiple Keywords (if space allows) if len(target_keywords) > 1: option3 = self._build_title_with_keywords( app_name, target_keywords[:2], max_length ) if option3: title_options.append({ 'title': option3, 'length': len(option3), 'remaining_chars': max_length - len(option3), 'keywords_included': target_keywords[:2], 'strategy': 'brand_plus_multiple', 'pros': ['Multiple keyword targets', 'Better discoverability'], 'cons': ['May feel cluttered', 'Less brand focus'] }) # Option 4: Keyword-first approach (for new apps) if target_keywords and not include_brand: option4 = " ".join(target_keywords[:2])[:max_length] title_options.append({ 'title': option4, 'length': len(option4), 'remaining_chars': max_length - len(option4), 'keywords_included': target_keywords[:2], 'strategy': 'keyword_first', 'pros': ['Maximum SEO benefit', 'Clear functionality'], 'cons': ['No brand recognition', 'Generic appearance'] }) return { 'platform': self.platform, 'max_length': max_length, 'options': title_options, 'recommendation': self._recommend_title_option(title_options) } def optimize_description( self, app_info: Dict[str, Any], target_keywords: List[str], description_type: str = 'full' ) -> Dict[str, Any]: """ Optimize app description with keyword integration and conversion focus. Args: app_info: Dict with 'name', 'key_features', 'unique_value', 'target_audience' target_keywords: List of keywords to integrate naturally description_type: 'full', 'short' (Google), 'subtitle' (Apple) Returns: Optimized description with analysis """ if description_type == 'short' and self.platform == 'google': return self._optimize_short_description(app_info, target_keywords) elif description_type == 'subtitle' and self.platform == 'apple': return self._optimize_subtitle(app_info, target_keywords) else: return self._optimize_full_description(app_info, target_keywords) def optimize_keyword_field( self, target_keywords: List[str], app_title: str = "", app_description: str = "" ) -> Dict[str, Any]: """ Optimize Apple's 100-character keyword field. Rules: - No spaces between commas - No plural forms if singular exists - No duplicates - Keywords in title/subtitle are already indexed Args: target_keywords: List of target keywords app_title: Current app title (to avoid duplication) app_description: Current description (to check coverage) Returns: Optimized keyword field (comma-separated, no spaces) """ if self.platform != 'apple': return {'error': 'Keyword field optimization only applies to Apple App Store'} max_length = self.limits['keywords'] # Extract words already in title (these don't need to be in keyword field) title_words = set(app_title.lower().split()) if app_title else set() # Process keywords processed_keywords = [] for keyword in target_keywords: keyword_lower = keyword.lower().strip() # Skip if already in title if keyword_lower in title_words: continue # Remove duplicates and process words = keyword_lower.split() for word in words: if word not in processed_keywords and word not in title_words: processed_keywords.append(word) # Remove plurals if singular exists deduplicated = self._remove_plural_duplicates(processed_keywords) # Build keyword field within 100 character limit keyword_field = self._build_keyword_field(deduplicated, max_length) # Calculate keyword density in description density = self._calculate_coverage(target_keywords, app_description) return { 'keyword_field': keyword_field, 'length': len(keyword_field), 'remaining_chars': max_length - len(keyword_field), 'keywords_included': keyword_field.split(','), 'keywords_count': len(keyword_field.split(',')), 'keywords_excluded': [kw for kw in target_keywords if kw.lower() not in keyword_field], 'description_coverage': density, 'optimization_tips': [ 'Keywords in title are auto-indexed - no need to repeat', 'Use singular forms only (Apple indexes plurals automatically)', 'No spaces between commas to maximize character usage', 'Update keyword field with each app update to test variations' ] } def validate_character_limits( self, metadata: Dict[str, str] ) -> Dict[str, Any]: """ Validate all metadata fields against platform character limits. Args: metadata: Dictionary of field_name: value Returns: Validation report with errors and warnings """ validation_results = { 'is_valid': True, 'errors': [], 'warnings': [], 'field_status': {} } for field_name, value in metadata.items(): if field_name not in self.limits: validation_results['warnings'].append( f"Unknown field '{field_name}' for {self.platform} platform" ) continue max_length = self.limits[field_name] actual_length = len(value) remaining = max_length - actual_length field_status = { 'value': value, 'length': actual_length, 'limit': max_length, 'remaining': remaining, 'is_valid': actual_length <= max_length, 'usage_percentage': round((actual_length / max_length) * 100, 1) } validation_results['field_status'][field_name] = field_status if actual_length > max_length: validation_results['is_valid'] = False validation_results['errors'].append( f"'{field_name}' exceeds limit: {actual_length}/{max_length} chars" ) elif remaining > max_length * 0.2: # More than 20% unused validation_results['warnings'].append( f"'{field_name}' under-utilizes space: {remaining} chars remaining" ) return validation_results def calculate_keyword_density( self, text: str, target_keywords: List[str] ) -> Dict[str, Any]: """ Calculate keyword density in text. Args: text: Text to analyze target_keywords: Keywords to check Returns: Density analysis """ text_lower = text.lower() total_words = len(text_lower.split()) keyword_densities = {} for keyword in target_keywords: keyword_lower = keyword.lower() count = text_lower.count(keyword_lower) density = (count / total_words * 100) if total_words > 0 else 0 keyword_densities[keyword] = { 'occurrences': count, 'density_percentage': round(density, 2), 'status': self._assess_density(density) } # Overall assessment total_keyword_occurrences = sum(kw['occurrences'] for kw in keyword_densities.values()) overall_density = (total_keyword_occurrences / total_words * 100) if total_words > 0 else 0 return { 'total_words': total_words, 'keyword_densities': keyword_densities, 'overall_keyword_density': round(overall_density, 2), 'assessment': self._assess_overall_density(overall_density), 'recommendations': self._generate_density_recommendations(keyword_densities) } def _build_title_with_keywords( self, app_name: str, keywords: List[str], max_length: int ) -> Optional[str]: """Build title combining app name and keywords within limit.""" separators = [' - ', ': ', ' | '] for sep in separators: for kw in keywords: title = f"{app_name}{sep}{kw}" if len(title) <= max_length: return title return None def _optimize_short_description( self, app_info: Dict[str, Any], target_keywords: List[str] ) -> Dict[str, Any]: """Optimize Google Play short description (80 chars).""" max_length = self.limits['short_description'] # Focus on unique value proposition with primary keyword unique_value = app_info.get('unique_value', '') primary_keyword = target_keywords[0] if target_keywords else '' # Template: [Primary Keyword] - [Unique Value] short_desc = f"{primary_keyword.title()} - {unique_value}"[:max_length] return { 'short_description': short_desc, 'length': len(short_desc), 'remaining_chars': max_length - len(short_desc), 'keywords_included': [primary_keyword] if primary_keyword in short_desc.lower() else [], 'strategy': 'keyword_value_proposition' } def _optimize_subtitle( self, app_info: Dict[str, Any], target_keywords: List[str] ) -> Dict[str, Any]: """Optimize Apple App Store subtitle (30 chars).""" max_length = self.limits['subtitle'] # Very concise - primary keyword or key feature primary_keyword = target_keywords[0] if target_keywords else '' key_feature = app_info.get('key_features', [''])[0] if app_info.get('key_features') else '' options = [ primary_keyword[:max_length], key_feature[:max_length], f"{primary_keyword} App"[:max_length] ] return { 'subtitle_options': [opt for opt in options if opt], 'max_length': max_length, 'recommendation': options[0] if options else '' } def _optimize_full_description( self, app_info: Dict[str, Any], target_keywords: List[str] ) -> Dict[str, Any]: """Optimize full app description (4000 chars for both platforms).""" max_length = self.limits.get('description', self.limits.get('full_description', 4000)) # Structure: Hook → Features → Benefits → Social Proof → CTA sections = [] # Hook (with primary keyword) primary_keyword = target_keywords[0] if target_keywords else '' unique_value = app_info.get('unique_value', '') hook = f"{unique_value} {primary_keyword.title()} that helps you achieve more.\n\n" sections.append(hook) # Features (with keywords naturally integrated) features = app_info.get('key_features', []) if features: sections.append("KEY FEATURES:\n") for i, feature in enumerate(features[:5], 1): # Integrate keywords naturally feature_text = f"• {feature}" if i <= len(target_keywords): keyword = target_keywords[i-1] if keyword.lower() not in feature.lower(): feature_text = f"• {feature} with {keyword}" sections.append(f"{feature_text}\n") sections.append("\n") # Benefits target_audience = app_info.get('target_audience', 'users') sections.append(f"PERFECT FOR:\n{target_audience}\n\n") # Social proof placeholder sections.append("WHY USERS LOVE US:\n") sections.append("Join thousands of satisfied users who have transformed their workflow.\n\n") # CTA sections.append("Download now and start experiencing the difference!") # Combine and validate length full_description = "".join(sections) if len(full_description) > max_length: full_description = full_description[:max_length-3] + "..." # Calculate keyword density density = self.calculate_keyword_density(full_description, target_keywords) return { 'full_description': full_description, 'length': len(full_description), 'remaining_chars': max_length - len(full_description), 'keyword_analysis': density, 'structure': { 'has_hook': True, 'has_features': len(features) > 0, 'has_benefits': True, 'has_cta': True } } def _remove_plural_duplicates(self, keywords: List[str]) -> List[str]: """Remove plural forms if singular exists.""" deduplicated = [] singular_set = set() for keyword in keywords: if keyword.endswith('s') and len(keyword) > 1: singular = keyword[:-1] if singular not in singular_set: deduplicated.append(singular) singular_set.add(singular) else: if keyword not in singular_set: deduplicated.append(keyword) singular_set.add(keyword) return deduplicated def _build_keyword_field(self, keywords: List[str], max_length: int) -> str: """Build comma-separated keyword field within character limit.""" keyword_field = "" for keyword in keywords: test_field = f"{keyword_field},{keyword}" if keyword_field else keyword if len(test_field) <= max_length: keyword_field = test_field else: break return keyword_field def _calculate_coverage(self, keywords: List[str], text: str) -> Dict[str, int]: """Calculate how many keywords are covered in text.""" text_lower = text.lower() coverage = {} for keyword in keywords: coverage[keyword] = text_lower.count(keyword.lower()) return coverage def _assess_density(self, density: float) -> str: """Assess individual keyword density.""" if density < 0.5: return "too_low" elif density <= 2.5: return "optimal" else: return "too_high" def _assess_overall_density(self, density: float) -> str: """Assess overall keyword density.""" if density < 2: return "Under-optimized: Consider adding more keyword variations" elif density <= 5: return "Optimal: Good keyword integration without stuffing" elif density <= 8: return "High: Approaching keyword stuffing - reduce keyword usage" else: return "Too High: Keyword stuffing detected - rewrite for natural flow" def _generate_density_recommendations( self, keyword_densities: Dict[str, Dict[str, Any]] ) -> List[str]: """Generate recommendations based on keyword density analysis.""" recommendations = [] for keyword, data in keyword_densities.items(): if data['status'] == 'too_low': recommendations.append( f"Increase usage of '{keyword}' - currently only {data['occurrences']} times" ) elif data['status'] == 'too_high': recommendations.append( f"Reduce usage of '{keyword}' - appears {data['occurrences']} times (keyword stuffing risk)" ) if not recommendations: recommendations.append("Keyword density is well-balanced") return recommendations def _recommend_title_option(self, options: List[Dict[str, Any]]) -> str: """Recommend best title option based on strategy.""" if not options: return "No valid options available" # Prefer brand_plus_primary for established apps for option in options: if option['strategy'] == 'brand_plus_primary': return f"Recommended: '{option['title']}' (Balance of brand and SEO)" # Fallback to first option return f"Recommended: '{options[0]['title']}' ({options[0]['strategy']})" def optimize_app_metadata( platform: str, app_info: Dict[str, Any], target_keywords: List[str] ) -> Dict[str, Any]: """ Convenience function to optimize all metadata fields. Args: platform: 'apple' or 'google' app_info: App information dictionary target_keywords: Target keywords list Returns: Complete metadata optimization package """ optimizer = MetadataOptimizer(platform) return { 'platform': platform, 'title': optimizer.optimize_title( app_info['name'], target_keywords ), 'description': optimizer.optimize_description( app_info, target_keywords, 'full' ), 'keyword_field': optimizer.optimize_keyword_field( target_keywords ) if platform == 'apple' else None }
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/business-marketing/app-store-optimization/metadata_optimizer.py", "license": "MIT License", "lines": 489, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/business-marketing/app-store-optimization/review_analyzer.py
""" Review analysis module for App Store Optimization. Analyzes user reviews for sentiment, issues, and feature requests. """ from typing import Dict, List, Any, Optional, Tuple from collections import Counter import re class ReviewAnalyzer: """Analyzes user reviews for actionable insights.""" # Sentiment keywords POSITIVE_KEYWORDS = [ 'great', 'awesome', 'excellent', 'amazing', 'love', 'best', 'perfect', 'fantastic', 'wonderful', 'brilliant', 'outstanding', 'superb' ] NEGATIVE_KEYWORDS = [ 'bad', 'terrible', 'awful', 'horrible', 'hate', 'worst', 'useless', 'broken', 'crash', 'bug', 'slow', 'disappointing', 'frustrating' ] # Issue indicators ISSUE_KEYWORDS = [ 'crash', 'bug', 'error', 'broken', 'not working', 'doesnt work', 'freezes', 'slow', 'laggy', 'glitch', 'problem', 'issue', 'fail' ] # Feature request indicators FEATURE_REQUEST_KEYWORDS = [ 'wish', 'would be nice', 'should add', 'need', 'want', 'hope', 'please add', 'missing', 'lacks', 'feature request' ] def __init__(self, app_name: str): """ Initialize review analyzer. Args: app_name: Name of the app """ self.app_name = app_name self.reviews = [] self.analysis_cache = {} def analyze_sentiment( self, reviews: List[Dict[str, Any]] ) -> Dict[str, Any]: """ Analyze sentiment across reviews. Args: reviews: List of review dicts with 'text', 'rating', 'date' Returns: Sentiment analysis summary """ self.reviews = reviews sentiment_counts = { 'positive': 0, 'neutral': 0, 'negative': 0 } detailed_sentiments = [] for review in reviews: text = review.get('text', '').lower() rating = review.get('rating', 3) # Calculate sentiment score sentiment_score = self._calculate_sentiment_score(text, rating) sentiment_category = self._categorize_sentiment(sentiment_score) sentiment_counts[sentiment_category] += 1 detailed_sentiments.append({ 'review_id': review.get('id', ''), 'rating': rating, 'sentiment_score': sentiment_score, 'sentiment': sentiment_category, 'text_preview': text[:100] + '...' if len(text) > 100 else text }) # Calculate percentages total = len(reviews) sentiment_distribution = { 'positive': round((sentiment_counts['positive'] / total) * 100, 1) if total > 0 else 0, 'neutral': round((sentiment_counts['neutral'] / total) * 100, 1) if total > 0 else 0, 'negative': round((sentiment_counts['negative'] / total) * 100, 1) if total > 0 else 0 } # Calculate average rating avg_rating = sum(r.get('rating', 0) for r in reviews) / total if total > 0 else 0 return { 'total_reviews_analyzed': total, 'average_rating': round(avg_rating, 2), 'sentiment_distribution': sentiment_distribution, 'sentiment_counts': sentiment_counts, 'sentiment_trend': self._assess_sentiment_trend(sentiment_distribution), 'detailed_sentiments': detailed_sentiments[:50] # Limit output } def extract_common_themes( self, reviews: List[Dict[str, Any]], min_mentions: int = 3 ) -> Dict[str, Any]: """ Extract frequently mentioned themes and topics. Args: reviews: List of review dicts min_mentions: Minimum mentions to be considered common Returns: Common themes analysis """ # Extract all words from reviews all_words = [] all_phrases = [] for review in reviews: text = review.get('text', '').lower() # Clean text text = re.sub(r'[^\w\s]', ' ', text) words = text.split() # Filter out common words stop_words = { 'the', 'and', 'for', 'with', 'this', 'that', 'from', 'have', 'app', 'apps', 'very', 'really', 'just', 'but', 'not', 'you' } words = [w for w in words if w not in stop_words and len(w) > 3] all_words.extend(words) # Extract 2-3 word phrases for i in range(len(words) - 1): phrase = f"{words[i]} {words[i+1]}" all_phrases.append(phrase) # Count frequency word_freq = Counter(all_words) phrase_freq = Counter(all_phrases) # Filter by min_mentions common_words = [ {'word': word, 'mentions': count} for word, count in word_freq.most_common(30) if count >= min_mentions ] common_phrases = [ {'phrase': phrase, 'mentions': count} for phrase, count in phrase_freq.most_common(20) if count >= min_mentions ] # Categorize themes themes = self._categorize_themes(common_words, common_phrases) return { 'common_words': common_words, 'common_phrases': common_phrases, 'identified_themes': themes, 'insights': self._generate_theme_insights(themes) } def identify_issues( self, reviews: List[Dict[str, Any]], rating_threshold: int = 3 ) -> Dict[str, Any]: """ Identify bugs, crashes, and other issues from reviews. Args: reviews: List of review dicts rating_threshold: Only analyze reviews at or below this rating Returns: Issue identification report """ issues = [] for review in reviews: rating = review.get('rating', 5) if rating > rating_threshold: continue text = review.get('text', '').lower() # Check for issue keywords mentioned_issues = [] for keyword in self.ISSUE_KEYWORDS: if keyword in text: mentioned_issues.append(keyword) if mentioned_issues: issues.append({ 'review_id': review.get('id', ''), 'rating': rating, 'date': review.get('date', ''), 'issue_keywords': mentioned_issues, 'text': text[:200] + '...' if len(text) > 200 else text }) # Group by issue type issue_frequency = Counter() for issue in issues: for keyword in issue['issue_keywords']: issue_frequency[keyword] += 1 # Categorize issues categorized_issues = self._categorize_issues(issues) # Calculate issue severity severity_scores = self._calculate_issue_severity( categorized_issues, len(reviews) ) return { 'total_issues_found': len(issues), 'issue_frequency': dict(issue_frequency.most_common(15)), 'categorized_issues': categorized_issues, 'severity_scores': severity_scores, 'top_issues': self._rank_issues_by_severity(severity_scores), 'recommendations': self._generate_issue_recommendations( categorized_issues, severity_scores ) } def find_feature_requests( self, reviews: List[Dict[str, Any]] ) -> Dict[str, Any]: """ Extract feature requests and desired improvements. Args: reviews: List of review dicts Returns: Feature request analysis """ feature_requests = [] for review in reviews: text = review.get('text', '').lower() rating = review.get('rating', 3) # Check for feature request indicators is_feature_request = any( keyword in text for keyword in self.FEATURE_REQUEST_KEYWORDS ) if is_feature_request: # Extract the specific request request_text = self._extract_feature_request_text(text) feature_requests.append({ 'review_id': review.get('id', ''), 'rating': rating, 'date': review.get('date', ''), 'request_text': request_text, 'full_review': text[:200] + '...' if len(text) > 200 else text }) # Cluster similar requests clustered_requests = self._cluster_feature_requests(feature_requests) # Prioritize based on frequency and rating context prioritized_requests = self._prioritize_feature_requests(clustered_requests) return { 'total_feature_requests': len(feature_requests), 'clustered_requests': clustered_requests, 'prioritized_requests': prioritized_requests, 'implementation_recommendations': self._generate_feature_recommendations( prioritized_requests ) } def track_sentiment_trends( self, reviews_by_period: Dict[str, List[Dict[str, Any]]] ) -> Dict[str, Any]: """ Track sentiment changes over time. Args: reviews_by_period: Dict of period_name: reviews Returns: Trend analysis """ trends = [] for period, reviews in reviews_by_period.items(): sentiment = self.analyze_sentiment(reviews) trends.append({ 'period': period, 'total_reviews': len(reviews), 'average_rating': sentiment['average_rating'], 'positive_percentage': sentiment['sentiment_distribution']['positive'], 'negative_percentage': sentiment['sentiment_distribution']['negative'] }) # Calculate trend direction if len(trends) >= 2: first_period = trends[0] last_period = trends[-1] rating_change = last_period['average_rating'] - first_period['average_rating'] sentiment_change = last_period['positive_percentage'] - first_period['positive_percentage'] trend_direction = self._determine_trend_direction( rating_change, sentiment_change ) else: trend_direction = 'insufficient_data' return { 'periods_analyzed': len(trends), 'trend_data': trends, 'trend_direction': trend_direction, 'insights': self._generate_trend_insights(trends, trend_direction) } def generate_response_templates( self, issue_category: str ) -> List[Dict[str, str]]: """ Generate response templates for common review scenarios. Args: issue_category: Category of issue ('crash', 'feature_request', 'positive', etc.) Returns: Response templates """ templates = { 'crash': [ { 'scenario': 'App crash reported', 'template': "Thank you for bringing this to our attention. We're sorry you experienced a crash. " "Our team is investigating this issue. Could you please share more details about when " "this occurred (device model, iOS/Android version) by contacting support@[company].com? " "We're committed to fixing this quickly." }, { 'scenario': 'Crash already fixed', 'template': "Thank you for your feedback. We've identified and fixed this crash issue in version [X.X]. " "Please update to the latest version. If the problem persists, please reach out to " "support@[company].com and we'll help you directly." } ], 'bug': [ { 'scenario': 'Bug reported', 'template': "Thanks for reporting this bug. We take these issues seriously. Our team is looking into it " "and we'll have a fix in an upcoming update. We appreciate your patience and will notify you " "when it's resolved." } ], 'feature_request': [ { 'scenario': 'Feature request received', 'template': "Thank you for this suggestion! We're always looking to improve [app_name]. We've added your " "request to our roadmap and will consider it for a future update. Follow us @[social] for " "updates on new features." }, { 'scenario': 'Feature already planned', 'template': "Great news! This feature is already on our roadmap and we're working on it. Stay tuned for " "updates in the coming months. Thanks for your feedback!" } ], 'positive': [ { 'scenario': 'Positive review', 'template': "Thank you so much for your kind words! We're thrilled that you're enjoying [app_name]. " "Reviews like yours motivate our team to keep improving. If you ever have suggestions, " "we'd love to hear them!" } ], 'negative_general': [ { 'scenario': 'General complaint', 'template': "We're sorry to hear you're not satisfied with your experience. We'd like to make this right. " "Please contact us at support@[company].com so we can understand the issue better and help " "you directly. Thank you for giving us a chance to improve." } ] } return templates.get(issue_category, templates['negative_general']) def _calculate_sentiment_score(self, text: str, rating: int) -> float: """Calculate sentiment score (-1 to 1).""" # Start with rating-based score rating_score = (rating - 3) / 2 # Convert 1-5 to -1 to 1 # Adjust based on text sentiment positive_count = sum(1 for keyword in self.POSITIVE_KEYWORDS if keyword in text) negative_count = sum(1 for keyword in self.NEGATIVE_KEYWORDS if keyword in text) text_score = (positive_count - negative_count) / 10 # Normalize # Weighted average (60% rating, 40% text) final_score = (rating_score * 0.6) + (text_score * 0.4) return max(min(final_score, 1.0), -1.0) def _categorize_sentiment(self, score: float) -> str: """Categorize sentiment score.""" if score > 0.3: return 'positive' elif score < -0.3: return 'negative' else: return 'neutral' def _assess_sentiment_trend(self, distribution: Dict[str, float]) -> str: """Assess overall sentiment trend.""" positive = distribution['positive'] negative = distribution['negative'] if positive > 70: return 'very_positive' elif positive > 50: return 'positive' elif negative > 30: return 'concerning' elif negative > 50: return 'critical' else: return 'mixed' def _categorize_themes( self, common_words: List[Dict[str, Any]], common_phrases: List[Dict[str, Any]] ) -> Dict[str, List[str]]: """Categorize themes from words and phrases.""" themes = { 'features': [], 'performance': [], 'usability': [], 'support': [], 'pricing': [] } # Keywords for each category feature_keywords = {'feature', 'functionality', 'option', 'tool'} performance_keywords = {'fast', 'slow', 'crash', 'lag', 'speed', 'performance'} usability_keywords = {'easy', 'difficult', 'intuitive', 'confusing', 'interface', 'design'} support_keywords = {'support', 'help', 'customer', 'service', 'response'} pricing_keywords = {'price', 'cost', 'expensive', 'cheap', 'subscription', 'free'} for word_data in common_words: word = word_data['word'] if any(kw in word for kw in feature_keywords): themes['features'].append(word) elif any(kw in word for kw in performance_keywords): themes['performance'].append(word) elif any(kw in word for kw in usability_keywords): themes['usability'].append(word) elif any(kw in word for kw in support_keywords): themes['support'].append(word) elif any(kw in word for kw in pricing_keywords): themes['pricing'].append(word) return {k: v for k, v in themes.items() if v} # Remove empty categories def _generate_theme_insights(self, themes: Dict[str, List[str]]) -> List[str]: """Generate insights from themes.""" insights = [] for category, keywords in themes.items(): if keywords: insights.append( f"{category.title()}: Users frequently mention {', '.join(keywords[:3])}" ) return insights[:5] def _categorize_issues(self, issues: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]: """Categorize issues by type.""" categories = { 'crashes': [], 'bugs': [], 'performance': [], 'compatibility': [] } for issue in issues: keywords = issue['issue_keywords'] if 'crash' in keywords or 'freezes' in keywords: categories['crashes'].append(issue) elif 'bug' in keywords or 'error' in keywords or 'broken' in keywords: categories['bugs'].append(issue) elif 'slow' in keywords or 'laggy' in keywords: categories['performance'].append(issue) else: categories['compatibility'].append(issue) return {k: v for k, v in categories.items() if v} def _calculate_issue_severity( self, categorized_issues: Dict[str, List[Dict[str, Any]]], total_reviews: int ) -> Dict[str, Dict[str, Any]]: """Calculate severity scores for each issue category.""" severity_scores = {} for category, issues in categorized_issues.items(): count = len(issues) percentage = (count / total_reviews) * 100 if total_reviews > 0 else 0 # Calculate average rating of affected reviews avg_rating = sum(i['rating'] for i in issues) / count if count > 0 else 0 # Severity score (0-100) severity = min((percentage * 10) + ((5 - avg_rating) * 10), 100) severity_scores[category] = { 'count': count, 'percentage': round(percentage, 2), 'average_rating': round(avg_rating, 2), 'severity_score': round(severity, 1), 'priority': 'critical' if severity > 70 else ('high' if severity > 40 else 'medium') } return severity_scores def _rank_issues_by_severity( self, severity_scores: Dict[str, Dict[str, Any]] ) -> List[Dict[str, Any]]: """Rank issues by severity score.""" ranked = sorted( [{'category': cat, **data} for cat, data in severity_scores.items()], key=lambda x: x['severity_score'], reverse=True ) return ranked def _generate_issue_recommendations( self, categorized_issues: Dict[str, List[Dict[str, Any]]], severity_scores: Dict[str, Dict[str, Any]] ) -> List[str]: """Generate recommendations for addressing issues.""" recommendations = [] for category, score_data in severity_scores.items(): if score_data['priority'] == 'critical': recommendations.append( f"URGENT: Address {category} issues immediately - affecting {score_data['percentage']}% of reviews" ) elif score_data['priority'] == 'high': recommendations.append( f"HIGH PRIORITY: Focus on {category} issues in next update" ) return recommendations def _extract_feature_request_text(self, text: str) -> str: """Extract the specific feature request from review text.""" # Simple extraction - find sentence with feature request keywords sentences = text.split('.') for sentence in sentences: if any(keyword in sentence for keyword in self.FEATURE_REQUEST_KEYWORDS): return sentence.strip() return text[:100] # Fallback def _cluster_feature_requests( self, feature_requests: List[Dict[str, Any]] ) -> List[Dict[str, Any]]: """Cluster similar feature requests.""" # Simplified clustering - group by common keywords clusters = {} for request in feature_requests: text = request['request_text'].lower() # Extract key words words = [w for w in text.split() if len(w) > 4] # Try to find matching cluster matched = False for cluster_key in clusters: if any(word in cluster_key for word in words[:3]): clusters[cluster_key].append(request) matched = True break if not matched and words: cluster_key = ' '.join(words[:2]) clusters[cluster_key] = [request] return [ {'feature_theme': theme, 'request_count': len(requests), 'examples': requests[:3]} for theme, requests in clusters.items() ] def _prioritize_feature_requests( self, clustered_requests: List[Dict[str, Any]] ) -> List[Dict[str, Any]]: """Prioritize feature requests by frequency.""" return sorted( clustered_requests, key=lambda x: x['request_count'], reverse=True )[:10] def _generate_feature_recommendations( self, prioritized_requests: List[Dict[str, Any]] ) -> List[str]: """Generate recommendations for feature requests.""" recommendations = [] if prioritized_requests: top_request = prioritized_requests[0] recommendations.append( f"Most requested feature: {top_request['feature_theme']} " f"({top_request['request_count']} mentions) - consider for next major release" ) if len(prioritized_requests) > 1: recommendations.append( f"Also consider: {prioritized_requests[1]['feature_theme']}" ) return recommendations def _determine_trend_direction( self, rating_change: float, sentiment_change: float ) -> str: """Determine overall trend direction.""" if rating_change > 0.2 and sentiment_change > 5: return 'improving' elif rating_change < -0.2 and sentiment_change < -5: return 'declining' else: return 'stable' def _generate_trend_insights( self, trends: List[Dict[str, Any]], trend_direction: str ) -> List[str]: """Generate insights from trend analysis.""" insights = [] if trend_direction == 'improving': insights.append("Positive trend: User satisfaction is increasing over time") elif trend_direction == 'declining': insights.append("WARNING: User satisfaction is declining - immediate action needed") else: insights.append("Sentiment is stable - maintain current quality") # Review velocity insight if len(trends) >= 2: recent_reviews = trends[-1]['total_reviews'] previous_reviews = trends[-2]['total_reviews'] if recent_reviews > previous_reviews * 1.5: insights.append("Review volume increasing - growing user base or recent controversy") return insights def analyze_reviews( app_name: str, reviews: List[Dict[str, Any]] ) -> Dict[str, Any]: """ Convenience function to perform comprehensive review analysis. Args: app_name: App name reviews: List of review dictionaries Returns: Complete review analysis """ analyzer = ReviewAnalyzer(app_name) return { 'sentiment_analysis': analyzer.analyze_sentiment(reviews), 'common_themes': analyzer.extract_common_themes(reviews), 'issues_identified': analyzer.identify_issues(reviews), 'feature_requests': analyzer.find_feature_requests(reviews) }
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/business-marketing/app-store-optimization/review_analyzer.py", "license": "MIT License", "lines": 596, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/business-marketing/seo-fundamentals/scripts/seo_checker.py
#!/usr/bin/env python3 """ SEO Checker - Search Engine Optimization Audit Checks HTML/JSX/TSX pages for SEO best practices. PURPOSE: - Verify meta tags, titles, descriptions - Check Open Graph tags for social sharing - Validate heading hierarchy - Check image accessibility (alt attributes) WHAT IT CHECKS: - HTML files (actual web pages) - JSX/TSX files (React page components) - Only files that are likely PUBLIC pages Usage: python seo_checker.py <project_path> """ import sys import json import re from pathlib import Path from datetime import datetime # Fix Windows console encoding try: sys.stdout.reconfigure(encoding='utf-8', errors='replace') except: pass # Directories to skip SKIP_DIRS = { 'node_modules', '.next', 'dist', 'build', '.git', '.github', '__pycache__', '.vscode', '.idea', 'coverage', 'test', 'tests', '__tests__', 'spec', 'docs', 'documentation', 'examples' } # Files to skip (not pages) SKIP_PATTERNS = [ 'config', 'setup', 'util', 'helper', 'hook', 'context', 'store', 'service', 'api', 'lib', 'constant', 'type', 'interface', 'mock', '.test.', '.spec.', '_test.', '_spec.' ] def is_page_file(file_path: Path) -> bool: """Check if this file is likely a public-facing page.""" name = file_path.name.lower() stem = file_path.stem.lower() # Skip utility/config files if any(skip in name for skip in SKIP_PATTERNS): return False # Check path - pages in specific directories are likely pages parts = [p.lower() for p in file_path.parts] page_dirs = ['pages', 'app', 'routes', 'views', 'screens'] if any(d in parts for d in page_dirs): return True # Filename indicators for pages page_names = ['page', 'index', 'home', 'about', 'contact', 'blog', 'post', 'article', 'product', 'landing', 'layout'] if any(p in stem for p in page_names): return True # HTML files are usually pages if file_path.suffix.lower() in ['.html', '.htm']: return True return False def find_pages(project_path: Path) -> list: """Find page files to check.""" patterns = ['**/*.html', '**/*.htm', '**/*.jsx', '**/*.tsx'] files = [] for pattern in patterns: for f in project_path.glob(pattern): # Skip excluded directories if any(skip in f.parts for skip in SKIP_DIRS): continue # Check if it's likely a page if is_page_file(f): files.append(f) return files[:50] # Limit to 50 files def check_page(file_path: Path) -> dict: """Check a single page for SEO issues.""" issues = [] try: content = file_path.read_text(encoding='utf-8', errors='ignore') except Exception as e: return {"file": str(file_path.name), "issues": [f"Error: {e}"]} # Detect if this is a layout/template file (has Head component) is_layout = 'Head>' in content or '<head' in content.lower() # 1. Title tag has_title = '<title' in content.lower() or 'title=' in content or 'Head>' in content if not has_title and is_layout: issues.append("Missing <title> tag") # 2. Meta description has_description = 'name="description"' in content.lower() or 'name=\'description\'' in content.lower() if not has_description and is_layout: issues.append("Missing meta description") # 3. Open Graph tags has_og = 'og:' in content or 'property="og:' in content.lower() if not has_og and is_layout: issues.append("Missing Open Graph tags") # 4. Heading hierarchy - multiple H1s h1_matches = re.findall(r'<h1[^>]*>', content, re.I) if len(h1_matches) > 1: issues.append(f"Multiple H1 tags ({len(h1_matches)})") # 5. Images without alt img_pattern = r'<img[^>]+>' imgs = re.findall(img_pattern, content, re.I) for img in imgs: if 'alt=' not in img.lower(): issues.append("Image missing alt attribute") break if 'alt=""' in img or "alt=''" in img: issues.append("Image has empty alt attribute") break # 6. Check for canonical link (nice to have) # has_canonical = 'rel="canonical"' in content.lower() return { "file": str(file_path.name), "issues": issues } def main(): project_path = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve() print(f"\n{'='*60}") print(f" SEO CHECKER - Search Engine Optimization Audit") print(f"{'='*60}") print(f"Project: {project_path}") print(f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") print("-"*60) # Find pages pages = find_pages(project_path) if not pages: print("\n[!] No page files found.") print(" Looking for: HTML, JSX, TSX in pages/app/routes directories") output = {"script": "seo_checker", "files_checked": 0, "passed": True} print("\n" + json.dumps(output, indent=2)) sys.exit(0) print(f"Found {len(pages)} page files to analyze\n") # Check each page all_issues = [] for f in pages: result = check_page(f) if result["issues"]: all_issues.append(result) # Summary print("=" * 60) print("SEO ANALYSIS RESULTS") print("=" * 60) if all_issues: # Group by issue type issue_counts = {} for item in all_issues: for issue in item["issues"]: issue_counts[issue] = issue_counts.get(issue, 0) + 1 print("\nIssue Summary:") for issue, count in sorted(issue_counts.items(), key=lambda x: -x[1]): print(f" [{count}] {issue}") print(f"\nAffected files ({len(all_issues)}):") for item in all_issues[:5]: print(f" - {item['file']}") if len(all_issues) > 5: print(f" ... and {len(all_issues) - 5} more") else: print("\n[OK] No SEO issues found!") total_issues = sum(len(item["issues"]) for item in all_issues) passed = total_issues == 0 output = { "script": "seo_checker", "project": str(project_path), "files_checked": len(pages), "files_with_issues": len(all_issues), "issues_found": total_issues, "passed": passed } print("\n" + json.dumps(output, indent=2)) sys.exit(0 if passed else 1) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/business-marketing/seo-fundamentals/scripts/seo_checker.py", "license": "MIT License", "lines": 170, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/creative-design/mobile-design/scripts/mobile_audit.py
#!/usr/bin/env python3 """ Mobile UX Audit Script - Full Mobile Design Coverage Analyzes React Native / Flutter code for compliance with: 1. TOUCH PSYCHOLOGY (touch-psychology.md): - Touch Target Sizes (44pt iOS, 48dp Android, 44px WCAG) - Touch Target Spacing (8px minimum gap) - Thumb Zone Placement (primary CTAs at bottom) - Gesture Alternatives (visible buttons for swipe) - Haptic Feedback Patterns - Touch Feedback Timing (<50ms) - Touch Accessibility (motor impairment support) 2. MOBILE PERFORMANCE (mobile-performance.md): - ScrollView vs FlatList (CRITICAL) - React.memo for List Items - useCallback for renderItem - Stable keyExtractor (NOT index) - useNativeDriver for Animations - Memory Leak Prevention (cleanup) - Console.log Detection - Inline Function Detection - Animation Performance (transform/opacity only) 3. MOBILE NAVIGATION (mobile-navigation.md): - Tab Bar Max Items (5) - Tab State Preservation - Proper Back Handling - Deep Link Support - Navigation Structure 4. MOBILE TYPOGRAPHY (mobile-typography.md): - System Font Usage - Dynamic Type Support (iOS) - Text Scaling Constraints - Mobile Line Height - Font Size Limits 5. MOBILE COLOR SYSTEM (mobile-color-system.md): - Pure Black Avoidance (#000000) - OLED Optimization - Dark Mode Support - Contrast Ratios 6. PLATFORM iOS (platform-ios.md): - SF Symbols Usage - iOS Navigation Patterns - iOS Haptic Types - iOS-Specific Components 7. PLATFORM ANDROID (platform-android.md): - Material Icons Usage - Android Navigation Patterns - Ripple Effects - Android-Specific Components 8. MOBILE BACKEND (mobile-backend.md): - Secure Storage (NOT AsyncStorage) - Offline Handling - Push Notification Support - API Response Caching Total: 50+ mobile-specific checks """ import sys import os import re import json from pathlib import Path class MobileAuditor: def __init__(self): self.issues = [] self.warnings = [] self.passed_count = 0 self.files_checked = 0 def audit_file(self, filepath: str) -> None: try: with open(filepath, 'r', encoding='utf-8', errors='replace') as f: content = f.read() except: return self.files_checked += 1 filename = os.path.basename(filepath) # Detect framework is_react_native = bool(re.search(r'react-native|@react-navigation|React\.Native', content)) is_flutter = bool(re.search(r'import \'package:flutter|MaterialApp|Widget\.build', content)) if not (is_react_native or is_flutter): return # Skip non-mobile files # --- 1. TOUCH PSYCHOLOGY CHECKS --- # 1.1 Touch Target Size Check # Look for small touch targets small_sizes = re.findall(r'(?:width|height|size):\s*([0-3]\d)', content) for size in small_sizes: if int(size) < 44: self.issues.append(f"[Touch Target] {filename}: Touch target size {size}px < 44px minimum (iOS: 44pt, Android: 48dp)") # 1.2 Touch Target Spacing Check # Look for inadequate spacing between touchable elements small_gaps = re.findall(r'(?:margin|gap):\s*([0-7])\s*(?:px|dp)', content) for gap in small_gaps: if int(gap) < 8: self.warnings.append(f"[Touch Spacing] {filename}: Touch target spacing {gap}px < 8px minimum. Accidental taps risk.") # 1.3 Thumb Zone Placement Check # Primary CTAs should be at bottom (easy thumb reach) primary_buttons = re.findall(r'(?:testID|id):\s*["\'](?:.*(?:primary|cta|submit|confirm)[^"\']*)["\']', content, re.IGNORECASE) has_bottom_placement = bool(re.search(r'position:\s*["\']?absolute["\']?|bottom:\s*\d+|style.*bottom|justifyContent:\s*["\']?flex-end', content)) if primary_buttons and not has_bottom_placement: self.warnings.append(f"[Thumb Zone] {filename}: Primary CTA may not be in thumb zone (bottom). Place primary actions at bottom for easy reach.") # 1.4 Gesture Alternatives Check # Swipe actions should have visible button alternatives has_swipe_gestures = bool(re.search(r'Swipeable|onSwipe|PanGestureHandler|swipe', content)) has_visible_buttons = bool(re.search(r'Button.*(?:delete|archive|more)|TouchableOpacity|Pressable', content)) if has_swipe_gestures and not has_visible_buttons: self.warnings.append(f"[Gestures] {filename}: Swipe gestures detected without visible button alternatives. Motor impaired users need alternatives.") # 1.5 Haptic Feedback Check # Important actions should have haptic feedback has_important_actions = bool(re.search(r'(?:onPress|onSubmit|delete|remove|confirm|purchase)', content)) has_haptics = bool(re.search(r'Haptics|Vibration|react-native-haptic-feedback|FeedbackManager', content)) if has_important_actions and not has_haptics: self.warnings.append(f"[Haptics] {filename}: Important actions without haptic feedback. Consider adding haptic confirmation.") # 1.6 Touch Feedback Timing Check # Touch feedback should be immediate (<50ms) if is_react_native: has_pressable = bool(re.search(r'Pressable|TouchableOpacity', content)) has_feedback_state = bool(re.search(r'pressed|style.*opacity|underlay', content)) if has_pressable and not has_feedback_state: self.warnings.append(f"[Touch Feedback] {filename}: Pressable without visual feedback state. Add opacity/scale change for tap confirmation.") # --- 2. MOBILE PERFORMANCE CHECKS --- # 2.1 CRITICAL: ScrollView vs FlatList has_scrollview = bool(re.search(r'<ScrollView|ScrollView\.', content)) has_map_in_scrollview = bool(re.search(r'ScrollView.*\.map\(|ScrollView.*\{.*\.map', content)) if has_scrollview and has_map_in_scrollview: self.issues.append(f"[Performance CRITICAL] {filename}: ScrollView with .map() detected. Use FlatList for lists to prevent memory explosion.") # 2.2 React.memo Check if is_react_native: has_list = bool(re.search(r'FlatList|FlashList|SectionList', content)) has_react_memo = bool(re.search(r'React\.memo|memo\(', content)) if has_list and not has_react_memo: self.warnings.append(f"[Performance] {filename}: FlatList without React.memo on list items. Items will re-render on every parent update.") # 2.3 useCallback Check if is_react_native: has_flatlist = bool(re.search(r'FlatList|FlashList', content)) has_use_callback = bool(re.search(r'useCallback', content)) if has_flatlist and not has_use_callback: self.warnings.append(f"[Performance] {filename}: FlatList renderItem without useCallback. New function created every render.") # 2.4 keyExtractor Check (CRITICAL) if is_react_native: has_flatlist = bool(re.search(r'FlatList', content)) has_key_extractor = bool(re.search(r'keyExtractor', content)) uses_index_key = bool(re.search(r'key=\{.*index.*\}|key:\s*index', content)) if has_flatlist and not has_key_extractor: self.issues.append(f"[Performance CRITICAL] {filename}: FlatList without keyExtractor. Index-based keys cause bugs on reorder/delete.") if uses_index_key: self.issues.append(f"[Performance CRITICAL] {filename}: Using index as key. This causes bugs when list changes. Use unique ID from data.") # 2.5 useNativeDriver Check if is_react_native: has_animated = bool(re.search(r'Animated\.', content)) has_native_driver = bool(re.search(r'useNativeDriver:\s*true', content)) has_native_driver_false = bool(re.search(r'useNativeDriver:\s*false', content)) if has_animated and has_native_driver_false: self.warnings.append(f"[Performance] {filename}: Animation with useNativeDriver: false. Use true for 60fps (only supports transform/opacity).") if has_animated and not has_native_driver: self.warnings.append(f"[Performance] {filename}: Animated component without useNativeDriver. Add useNativeDriver: true for 60fps.") # 2.6 Memory Leak Check if is_react_native: has_effect = bool(re.search(r'useEffect', content)) has_cleanup = bool(re.search(r'return\s*\(\)\s*=>|return\s+function', content)) has_subscriptions = bool(re.search(r'addEventListener|subscribe|\.focus\(\)|\.off\(', content)) if has_effect and has_subscriptions and not has_cleanup: self.issues.append(f"[Memory Leak] {filename}: useEffect with subscriptions but no cleanup function. Memory leak on unmount.") # 2.7 Console.log Detection console_logs = len(re.findall(r'console\.log|console\.warn|console\.error|console\.debug', content)) if console_logs > 5: self.warnings.append(f"[Performance] {filename}: {console_logs} console.log statements detected. Remove before production (blocks JS thread).") # 2.8 Inline Function Detection if is_react_native: inline_functions = re.findall(r'(?:onPress|onPressIn|onPressOut|renderItem):\s*\([^)]*\)\s*=>', content) if len(inline_functions) > 3: self.warnings.append(f"[Performance] {filename}: {len(inline_functions)} inline arrow functions in props. Creates new function every render. Use useCallback.") # 2.9 Animation Properties Check # Warn if animating expensive properties animating_layout = bool(re.search(r'Animated\.timing.*(?:width|height|margin|padding)', content)) if animating_layout: self.issues.append(f"[Performance] {filename}: Animating layout properties (width/height/margin). Use transform/opacity for 60fps.") # --- 3. MOBILE NAVIGATION CHECKS --- # 3.1 Tab Bar Max Items Check tab_bar_items = len(re.findall(r'Tab\.Screen|createBottomTabNavigator|BottomTab', content)) if tab_bar_items > 5: self.warnings.append(f"[Navigation] {filename}: {tab_bar_items} tab bar items (max 5 recommended). More than 5 becomes hard to tap.") # 3.2 Tab State Preservation Check has_tab_nav = bool(re.search(r'createBottomTabNavigator|Tab\.Navigator', content)) if has_tab_nav: # Look for lazy prop (false preserves state) has_lazy_false = bool(re.search(r'lazy:\s*false', content)) if not has_lazy_false: self.warnings.append(f"[Navigation] {filename}: Tab navigation without lazy: false. Tabs may lose state on switch.") # 3.3 Back Handling Check has_back_listener = bool(re.search(r'BackHandler|useFocusEffect|navigation\.addListener', content)) has_custom_back = bool(re.search(r'onBackPress|handleBackPress', content)) if has_custom_back and not has_back_listener: self.warnings.append(f"[Navigation] {filename}: Custom back handling without BackHandler listener. May not work correctly.") # 3.4 Deep Link Support Check has_linking = bool(re.search(r'Linking\.|Linking\.openURL|deepLink|universalLink', content)) has_config = bool(re.search(r'apollo-link|react-native-screens|navigation\.link', content)) if not has_linking and not has_config: self.passed_count += 1 else: if has_linking and not has_config: self.warnings.append(f"[Navigation] {filename}: Deep linking detected but may lack proper configuration. Test notification/share flows.") # --- 4. MOBILE TYPOGRAPHY CHECKS --- # 4.1 System Font Check if is_react_native: has_custom_font = bool(re.search(r"fontFamily:\s*[\"'][^\"']+", content)) has_system_font = bool(re.search(r"fontFamily:\s*[\"']?(?:System|San Francisco|Roboto|-apple-system)", content)) if has_custom_font and not has_system_font: self.warnings.append(f"[Typography] {filename}: Custom font detected. Consider system fonts (iOS: SF Pro, Android: Roboto) for native feel.") # 4.2 Text Scaling Check (iOS Dynamic Type) if is_react_native: has_font_sizes = bool(re.search(r'fontSize:', content)) has_scaling = bool(re.search(r'allowFontScaling:\s*true|responsiveFontSize|useWindowDimensions', content)) if has_font_sizes and not has_scaling: self.warnings.append(f"[Typography] {filename}: Fixed font sizes without scaling support. Consider allowFontScaling for accessibility.") # 4.3 Mobile Line Height Check line_heights = re.findall(r'lineHeight:\s*([\d.]+)', content) for lh in line_heights: if float(lh) > 1.8: self.warnings.append(f"[Typography] {filename}: lineHeight {lh} too high for mobile. Mobile text needs tighter spacing (1.3-1.5).") # 4.4 Font Size Limits font_sizes = re.findall(r'fontSize:\s*([\d.]+)', content) for fs in font_sizes: size = float(fs) if size < 12: self.warnings.append(f"[Typography] {filename}: fontSize {size}px below 12px minimum readability.") elif size > 32: self.warnings.append(f"[Typography] {filename}: fontSize {size}px very large. Consider using responsive scaling.") # --- 5. MOBILE COLOR SYSTEM CHECKS --- # 5.1 Pure Black Avoidance if re.search(r'#000000|color:\s*black|backgroundColor:\s*["\']?black', content): self.warnings.append(f"[Color] {filename}: Pure black (#000000) detected. Use dark gray (#1C1C1E iOS, #121212 Android) for better OLED/battery.") # 5.2 Dark Mode Support has_color_schemes = bool(re.search(r'useColorScheme|colorScheme|appearance:\s*["\']?dark', content)) has_dark_mode_style = bool(re.search(r'\\\?.*dark|style:\s*.*dark|isDark', content)) if not has_color_schemes and not has_dark_mode_style: self.warnings.append(f"[Color] {filename}: No dark mode support detected. Consider useColorScheme for system dark mode.") # --- 6. PLATFORM iOS CHECKS --- if is_react_native: # 6.1 SF Symbols Check has_ios_icons = bool(re.search(r'@expo/vector-icons|ionicons', content)) has_sf_symbols = bool(re.search(r'sf-symbol|SF Symbols', content)) if has_ios_icons and not has_sf_symbols: self.passed_count += 1 # 6.2 iOS Haptic Types has_haptic_import = bool(re.search(r'expo-haptics|react-native-haptic-feedback', content)) has_haptic_types = bool(re.search(r'ImpactFeedback|NotificationFeedback|SelectionFeedback', content)) if has_haptic_import and not has_haptic_types: self.warnings.append(f"[iOS Haptics] {filename}: Haptic library imported but not using typed haptics (Impact/Notification/Selection).") # 6.3 iOS Safe Area has_safe_area = bool(re.search(r'SafeAreaView|useSafeAreaInsets|safeArea', content)) if not has_safe_area: self.warnings.append(f"[iOS] {filename}: No SafeArea detected. Content may be hidden by notch/home indicator.") # --- 7. PLATFORM ANDROID CHECKS --- if is_react_native: # 7.1 Material Icons Check has_material_icons = bool(re.search(r'@expo/vector-icons|MaterialIcons', content)) if has_material_icons: self.passed_count += 1 # 7.2 Ripple Effect has_ripple = bool(re.search(r'ripple|android_ripple|foregroundRipple', content)) has_pressable = bool(re.search(r'Pressable|Touchable', content)) if has_pressable and not has_ripple: self.warnings.append(f"[Android] {filename}: Touchable without ripple effect. Android users expect ripple feedback.") # 7.3 Hardware Back Button if is_react_native: has_back_button = bool(re.search(r'BackHandler|useBackHandler', content)) has_navigation = bool(re.search(r'@react-navigation', content)) if has_navigation and not has_back_button: self.warnings.append(f"[Android] {filename}: React Navigation detected without BackHandler listener. Android hardware back may not work correctly.") # --- 8. MOBILE BACKEND CHECKS --- # 8.1 Secure Storage Check has_async_storage = bool(re.search(r'AsyncStorage|@react-native-async-storage', content)) has_secure_storage = bool(re.search(r'SecureStore|Keychain|EncryptedSharedPreferences', content)) has_token_storage = bool(re.search(r'token|jwt|auth.*storage', content, re.IGNORECASE)) if has_token_storage and has_async_storage and not has_secure_storage: self.issues.append(f"[Security] {filename}: Storing auth tokens in AsyncStorage (insecure). Use SecureStore (iOS) / EncryptedSharedPreferences (Android).") # 8.2 Offline Handling Check has_network = bool(re.search(r'fetch|axios|netinfo|@react-native-community/netinfo', content)) has_offline = bool(re.search(r'offline|isConnected|netInfo|cache.*offline', content)) if has_network and not has_offline: self.warnings.append(f"[Offline] {filename}: Network requests detected without offline handling. Consider NetInfo for connection status.") # 8.3 Push Notification Support has_push = bool(re.search(r'Notifications|pushNotification|Firebase\.messaging|PushNotificationIOS', content)) has_push_handler = bool(re.search(r'onNotification|addNotificationListener|notification\.open', content)) if has_push and not has_push_handler: self.warnings.append(f"[Push] {filename}: Push notifications imported but no handler found. May miss notifications.") # --- 9. EXTENDED MOBILE TYPOGRAPHY CHECKS --- # 9.1 iOS Type Scale Check if is_react_native: # Check for iOS text styles that match HIG has_large_title = bool(re.search(r'fontSize:\s*34|largeTitle|font-weight:\s*["\']?bold', content)) has_title_1 = bool(re.search(r'fontSize:\s*28', content)) has_headline = bool(re.search(r'fontSize:\s*17.*semibold|headline', content)) has_body = bool(re.search(r'fontSize:\s*17.*regular|body', content)) # Check if following iOS scale roughly font_sizes = re.findall(r'fontSize:\s*([\d.]+)', content) ios_scale_sizes = [34, 28, 22, 20, 17, 16, 15, 13, 12, 11] matching_ios = sum(1 for size in font_sizes if any(abs(float(size) - ios_size) < 1 for ios_size in ios_scale_sizes)) if len(font_sizes) > 3 and matching_ios < len(font_sizes) / 2: self.warnings.append(f"[iOS Typography] {filename}: Font sizes don't match iOS type scale. Consider iOS text styles for native feel.") # 9.2 Android Material Type Scale Check if is_react_native: # Check for Material 3 text styles has_display = bool(re.search(r'fontSize:\s*[456][0-9]|display', content)) has_headline_material = bool(re.search(r'fontSize:\s*[23][0-9]|headline', content)) has_title_material = bool(re.search(r'fontSize:\s*2[12][0-9].*medium|title', content)) has_body_material = bool(re.search(r'fontSize:\s*1[456].*regular|body', content)) has_label = bool(re.search(r'fontSize:\s*1[1234].*medium|label', content)) # Check if using sp (scale-independent pixels) uses_sp = bool(re.search(r'\d+\s*sp\b', content)) if has_display or has_headline_material: if not uses_sp: self.warnings.append(f"[Android Typography] {filename}: Material typography detected without sp units. Use sp for text to respect user font size preferences.") # 9.3 Modular Scale Check # Check if font sizes follow modular scale font_sizes = re.findall(r'fontSize:\s*(\d+(?:\.\d+)?)', content) if len(font_sizes) > 3: sorted_sizes = sorted(set([float(s) for s in font_sizes])) ratios = [] for i in range(1, len(sorted_sizes)): if sorted_sizes[i-1] > 0: ratios.append(sorted_sizes[i] / sorted_sizes[i-1]) # Common ratios: 1.125, 1.2, 1.25, 1.333, 1.5 common_ratios = {1.125, 1.2, 1.25, 1.333, 1.5} for ratio in ratios[:3]: if not any(abs(ratio - cr) < 0.03 for cr in common_ratios): self.warnings.append(f"[Typography] {filename}: Font sizes may not follow modular scale (ratio: {ratio:.2f}). Consider consistent ratio.") break # 9.4 Line Length Check (Mobile-specific) # Mobile text should be 40-60 characters max if is_react_native: has_long_text = bool(re.search(r'<Text[^>]*>[^<]{40,}', content)) has_max_width = bool(re.search(r'maxWidth|max-w-\d+|width:\s*["\']?\d+', content)) if has_long_text and not has_max_width: self.warnings.append(f"[Mobile Typography] {filename}: Text without max-width constraint. Mobile text should be 40-60 characters per line for readability.") # 9.5 Font Weight Pattern Check # Check for font weight distribution if is_react_native: font_weights = re.findall(r'fontWeight:\s*["\']?(\d+|normal|bold|medium|light)', content) weight_map = {'normal': '400', 'light': '300', 'medium': '500', 'bold': '700'} numeric_weights = [] for w in font_weights: val = weight_map.get(w.lower(), w) try: numeric_weights.append(int(val)) except: pass # Check if overusing bold (mobile should be regular-dominant) bold_count = sum(1 for w in numeric_weights if w >= 700) regular_count = sum(1 for w in numeric_weights if 400 <= w < 500) if bold_count > regular_count: self.warnings.append(f"[Mobile Typography] {filename}: More bold weights than regular. Mobile typography should be regular-dominant for readability.") # --- 10. EXTENDED MOBILE COLOR SYSTEM CHECKS --- # 10.1 OLED Optimization Check # Check for near-black colors instead of pure black if re.search(r'#121212|#1A1A1A|#0D0D0D', content): self.passed_count += 1 # Good OLED optimization elif re.search(r'backgroundColor:\s*["\']?#000000', content): # Using pure black for background is OK for OLED pass elif re.search(r'backgroundColor:\s*["\']?#[0-9A-Fa-f]{6}', content): # Check if using light colors in dark mode (bad for OLED) self.warnings.append(f"[Mobile Color] {filename}: Consider OLED-optimized dark backgrounds (#121212 Android, #000000 iOS) for battery savings.") # 10.2 Saturated Color Detection (Battery) # Highly saturated colors consume more power on OLED hex_colors = re.findall(r'#([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})', content) saturated_count = 0 for r, g, b in hex_colors: # Convert to RGB 0-255 try: r_val, g_val, b_val = int(r, 16), int(g, 16), int(b, 16) max_val = max(r_val, g_val, b_val) min_val = min(r_val, g_val, b_val) # Saturation = (max - min) / max if max_val > 0: saturation = (max_val - min_val) / max_val if saturation > 0.8: # Highly saturated saturated_count += 1 except: pass if saturated_count > 10: self.warnings.append(f"[Mobile Color] {filename}: {saturated_count} highly saturated colors detected. Desaturated colors save battery on OLED screens.") # 10.3 Outdoor Visibility Check # Low contrast combinations fail in outdoor sunlight light_colors = re.findall(r'#[0-9A-Fa-f]{6}|rgba?\([^)]+\)', content) # Check for potential low contrast (light gray on white, dark gray on black) potential_low_contrast = bool(re.search(r'#[EeEeEeEe].*#ffffff|#999999.*#ffffff|#333333.*#000000|#666666.*#000000', content)) if potential_low_contrast: self.warnings.append(f"[Mobile Color] {filename}: Possible low contrast combination detected. Critical for outdoor visibility. Ensure WCAG AAA (7:1) for mobile.") # 10.4 Dark Mode Text Color Check # In dark mode, text should not be pure white has_dark_mode = bool(re.search(r'dark:\s*|isDark|useColorScheme|colorScheme:\s*["\']?dark', content)) if has_dark_mode: has_pure_white_text = bool(re.search(r'color:\s*["\']?#ffffff|#fff["\']?\}|textColor:\s*["\']?white', content)) if has_pure_white_text: self.warnings.append(f"[Mobile Color] {filename}: Pure white text (#FFFFFF) in dark mode. Use #E8E8E8 or light gray for better readability.") # --- 11. EXTENDED PLATFORM IOS CHECKS --- if is_react_native: # 11.1 SF Pro Font Detection has_sf_pro = bool(re.search(r'SF Pro|SFPro|fontFamily:\s*["\']?[-\s]*SF', content)) has_custom_font = bool(re.search(r'fontFamily:\s*["\'][^"\']+', content)) if has_custom_font and not has_sf_pro: self.warnings.append(f"[iOS] {filename}: Custom font without SF Pro fallback. Consider SF Pro Text for body, SF Pro Display for headings.") # 11.2 iOS System Colors Check # Check for semantic color usage has_label = bool(re.search(r'color:\s*["\']?label|\.label', content)) has_secondaryLabel = bool(re.search(r'secondaryLabel|\.secondaryLabel', content)) has_systemBackground = bool(re.search(r'systemBackground|\.systemBackground', content)) has_hardcoded_gray = bool(re.search(r'#[78]0{4}', content)) if has_hardcoded_gray and not (has_label or has_secondaryLabel): self.warnings.append(f"[iOS] {filename}: Hardcoded gray colors detected. Consider iOS semantic colors (label, secondaryLabel) for automatic dark mode.") # 11.3 iOS Accent Colors Check ios_blue = bool(re.search(r'#007AFF|#0A84FF|systemBlue', content)) ios_green = bool(re.search(r'#34C759|#30D158|systemGreen', content)) ios_red = bool(re.search(r'#FF3B30|#FF453A|systemRed', content)) has_custom_primary = bool(re.search(r'primaryColor|theme.*primary|colors\.primary', content)) if has_custom_primary and not (ios_blue or ios_green or ios_red): self.warnings.append(f"[iOS] {filename}: Custom primary color without iOS system color fallback. Consider systemBlue for consistent iOS feel.") # 11.4 iOS Navigation Patterns Check has_navigation_bar = bool(re.search(r'navigationOptions|headerStyle|cardStyle', content)) has_header_title = bool(re.search(r'title:\s*["\']|headerTitle|navigation\.setOptions', content)) if has_navigation_bar and not has_header_title: self.warnings.append(f"[iOS] {filename}: Navigation bar detected without title. iOS apps should have clear context in nav bar.") # 11.5 iOS Component Patterns Check # Check for iOS-specific components has_alert = bool(re.search(r'Alert\.alert|showAlert', content)) has_action_sheet = bool(re.search(r'ActionSheet|ActionSheetIOS|showActionSheetWithOptions', content)) has_activity_indicator = bool(re.search(r'ActivityIndicator|ActivityIndic', content)) if has_alert or has_action_sheet or has_activity_indicator: self.passed_count += 1 # Good iOS component usage # --- 12. EXTENDED PLATFORM ANDROID CHECKS --- if is_react_native: # 12.1 Roboto Font Detection has_roboto = bool(re.search(r'Roboto|fontFamily:\s*["\']?[-\s]*Roboto', content)) has_custom_font = bool(re.search(r'fontFamily:\s*["\'][^"\']+', content)) if has_custom_font and not has_roboto: self.warnings.append(f"[Android] {filename}: Custom font without Roboto fallback. Roboto is optimized for Android displays.") # 12.2 Material 3 Dynamic Color Check has_material_colors = bool(re.search(r'MD3|MaterialYou|dynamicColor|useColorScheme', content)) has_theme_provider = bool(re.search(r'MaterialTheme|ThemeProvider|PaperProvider|ThemeProvider', content)) if not has_material_colors and not has_theme_provider: self.warnings.append(f"[Android] {filename}: No Material 3 dynamic color detected. Consider Material 3 theming for personalized feel.") # 12.3 Material Elevation Check # Check for elevation values (Material 3 uses elevation for depth) has_elevation = bool(re.search(r'elevation:\s*\d+|shadowOpacity|shadowRadius|android:elevation', content)) has_box_shadow = bool(re.search(r'boxShadow:', content)) if has_box_shadow and not has_elevation: self.warnings.append(f"[Android] {filename}: CSS box-shadow detected without elevation. Consider Material elevation system for consistent depth.") # 12.4 Material Component Patterns Check # Check for Material components has_ripple = bool(re.search(r'ripple|android_ripple|foregroundRipple', content)) has_card = bool(re.search(r'Card|Paper|elevation.*\d+', content)) has_fab = bool(re.search(r'FAB|FloatingActionButton|fab', content)) has_snackbar = bool(re.search(r'Snackbar|showSnackBar|Toast', content)) material_component_count = sum([has_ripple, has_card, has_fab, has_snackbar]) if material_component_count >= 2: self.passed_count += 1 # Good Material design usage # 12.5 Android Navigation Patterns Check has_top_app_bar = bool(re.search(r'TopAppBar|AppBar|CollapsingToolbar', content)) has_bottom_nav = bool(re.search(r'BottomNavigation|BottomNav', content)) has_navigation_rail = bool(re.search(r'NavigationRail', content)) if has_bottom_nav: self.passed_count += 1 # Good Android pattern elif has_top_app_bar and not (has_bottom_nav or has_navigation_rail): self.warnings.append(f"[Android] {filename}: TopAppBar without bottom navigation. Consider BottomNavigation for thumb-friendly access.") # --- 13. MOBILE TESTING CHECKS --- # 13.1 Testing Tool Detection has_rntl = bool(re.search(r'react-native-testing-library|@testing-library', content)) has_detox = bool(re.search(r'detox|element\(|by\.text|by\.id', content)) has_maestro = bool(re.search(r'maestro|\.yaml$', content)) has_jest = bool(re.search(r'jest|describe\(|test\(|it\(', content)) testing_tools = [] if has_jest: testing_tools.append('Jest') if has_rntl: testing_tools.append('RNTL') if has_detox: testing_tools.append('Detox') if has_maestro: testing_tools.append('Maestro') if len(testing_tools) == 0: self.warnings.append(f"[Testing] {filename}: No testing framework detected. Consider Jest (unit) + Detox/Maestro (E2E) for mobile.") # 13.2 Test Pyramid Balance Check test_files = len(re.findall(r'\.test\.(tsx|ts|js|jsx)|\.spec\.', content)) e2e_tests = len(re.findall(r'detox|maestro|e2e|spec\.e2e', content.lower())) if test_files > 0 and e2e_tests == 0: self.warnings.append(f"[Testing] {filename}: Unit tests found but no E2E tests. Mobile needs E2E on real devices for complete coverage.") # 13.3 Accessibility Label Check (Mobile-specific) if is_react_native: has_pressable = bool(re.search(r'Pressable|TouchableOpacity|TouchableHighlight', content)) has_a11y_label = bool(re.search(r'accessibilityLabel|aria-label|testID', content)) if has_pressable and not has_a11y_label: self.warnings.append(f"[A11y Mobile] {filename}: Touchable element without accessibilityLabel. Screen readers need labels for all interactive elements.") # --- 14. MOBILE DEBUGGING CHECKS --- # 14.1 Performance Profiling Check has_performance = bool(re.search(r'Performance|systrace|profile|Flipper', content)) has_console_log = len(re.findall(r'console\.(log|warn|error|debug|info)', content)) has_debugger = bool(re.search(r'debugger|__DEV__|React\.DevTools', content)) if has_console_log > 10: self.warnings.append(f"[Debugging] {filename}: {has_console_log} console.log statements. Remove before production; they block JS thread.") if has_performance: self.passed_count += 1 # Good performance monitoring # 14.2 Error Boundary Check has_error_boundary = bool(re.search(r'ErrorBoundary|componentDidCatch|getDerivedStateFromError', content)) if not has_error_boundary and is_react_native: self.warnings.append(f"[Debugging] {filename}: No ErrorBoundary detected. Consider adding ErrorBoundary to prevent app crashes.") # 14.3 Hermes Check (React Native specific) if is_react_native: # Check if using Hermes engine (should be default in modern RN) # This is more of a configuration check, not code pattern self.passed_count += 1 # Hermes is default in RN 0.70+ def audit_directory(self, directory: str) -> None: extensions = {'.tsx', '.ts', '.jsx', '.js', '.dart'} for root, dirs, files in os.walk(directory): dirs[:] = [d for d in dirs if d not in {'node_modules', '.git', 'dist', 'build', '.next', 'ios', 'android', 'build', '.idea'}] for file in files: if Path(file).suffix in extensions: self.audit_file(os.path.join(root, file)) def get_report(self): return { "files_checked": self.files_checked, "issues": self.issues, "warnings": self.warnings, "passed_checks": self.passed_count, "compliant": len(self.issues) == 0 } def main(): if len(sys.argv) < 2: print("Usage: python mobile_audit.py <directory>") sys.exit(1) path = sys.argv[1] is_json = "--json" in sys.argv auditor = MobileAuditor() if os.path.isfile(path): auditor.audit_file(path) else: auditor.audit_directory(path) report = auditor.get_report() if is_json: print(json.dumps(report, indent=2)) else: print(f"\n[MOBILE AUDIT] {report['files_checked']} mobile files checked") print("-" * 50) if report['issues']: print(f"[!] ISSUES ({len(report['issues'])}):") for i in report['issues'][:10]: print(f" - {i}") if report['warnings']: print(f"[*] WARNINGS ({len(report['warnings'])}):") for w in report['warnings'][:15]: print(f" - {w}") print(f"[+] PASSED CHECKS: {report['passed_checks']}") status = "PASS" if report['compliant'] else "FAIL" print(f"STATUS: {status}") sys.exit(0 if report['compliant'] else 1) if __name__ == "__main__": # Fix missing import import re main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/creative-design/mobile-design/scripts/mobile_audit.py", "license": "MIT License", "lines": 554, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/creative-design/ui-ux-pro-max/scripts/core.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ UI/UX Pro Max Core - BM25 search engine for UI/UX style guides """ import csv import re from pathlib import Path from math import log from collections import defaultdict # ============ CONFIGURATION ============ DATA_DIR = Path(__file__).parent.parent / "data" MAX_RESULTS = 3 CSV_CONFIG = { "style": { "file": "styles.csv", "search_cols": ["Style Category", "Keywords", "Best For", "Type"], "output_cols": ["Style Category", "Type", "Keywords", "Primary Colors", "Effects & Animation", "Best For", "Performance", "Accessibility", "Framework Compatibility", "Complexity"] }, "prompt": { "file": "prompts.csv", "search_cols": ["Style Category", "AI Prompt Keywords (Copy-Paste Ready)", "CSS/Technical Keywords"], "output_cols": ["Style Category", "AI Prompt Keywords (Copy-Paste Ready)", "CSS/Technical Keywords", "Implementation Checklist"] }, "color": { "file": "colors.csv", "search_cols": ["Product Type", "Keywords", "Notes"], "output_cols": ["Product Type", "Keywords", "Primary (Hex)", "Secondary (Hex)", "CTA (Hex)", "Background (Hex)", "Text (Hex)", "Border (Hex)", "Notes"] }, "chart": { "file": "charts.csv", "search_cols": ["Data Type", "Keywords", "Best Chart Type", "Accessibility Notes"], "output_cols": ["Data Type", "Keywords", "Best Chart Type", "Secondary Options", "Color Guidance", "Accessibility Notes", "Library Recommendation", "Interactive Level"] }, "landing": { "file": "landing.csv", "search_cols": ["Pattern Name", "Keywords", "Conversion Optimization", "Section Order"], "output_cols": ["Pattern Name", "Keywords", "Section Order", "Primary CTA Placement", "Color Strategy", "Conversion Optimization"] }, "product": { "file": "products.csv", "search_cols": ["Product Type", "Keywords", "Primary Style Recommendation", "Key Considerations"], "output_cols": ["Product Type", "Keywords", "Primary Style Recommendation", "Secondary Styles", "Landing Page Pattern", "Dashboard Style (if applicable)", "Color Palette Focus"] }, "ux": { "file": "ux-guidelines.csv", "search_cols": ["Category", "Issue", "Description", "Platform"], "output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"] }, "typography": { "file": "typography.csv", "search_cols": ["Font Pairing Name", "Category", "Mood/Style Keywords", "Best For", "Heading Font", "Body Font"], "output_cols": ["Font Pairing Name", "Category", "Heading Font", "Body Font", "Mood/Style Keywords", "Best For", "Google Fonts URL", "CSS Import", "Tailwind Config", "Notes"] }, "icons": { "file": "icons.csv", "search_cols": ["Category", "Icon Name", "Keywords", "Best For"], "output_cols": ["Category", "Icon Name", "Keywords", "Library", "Import Code", "Usage", "Best For", "Style"] }, "react": { "file": "react-performance.csv", "search_cols": ["Category", "Issue", "Keywords", "Description"], "output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"] }, "web": { "file": "web-interface.csv", "search_cols": ["Category", "Issue", "Keywords", "Description"], "output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"] } } STACK_CONFIG = { "html-tailwind": {"file": "stacks/html-tailwind.csv"}, "react": {"file": "stacks/react.csv"}, "nextjs": {"file": "stacks/nextjs.csv"}, "vue": {"file": "stacks/vue.csv"}, "nuxtjs": {"file": "stacks/nuxtjs.csv"}, "nuxt-ui": {"file": "stacks/nuxt-ui.csv"}, "svelte": {"file": "stacks/svelte.csv"}, "swiftui": {"file": "stacks/swiftui.csv"}, "react-native": {"file": "stacks/react-native.csv"}, "flutter": {"file": "stacks/flutter.csv"}, "shadcn": {"file": "stacks/shadcn.csv"} } # Common columns for all stacks _STACK_COLS = { "search_cols": ["Category", "Guideline", "Description", "Do", "Don't"], "output_cols": ["Category", "Guideline", "Description", "Do", "Don't", "Code Good", "Code Bad", "Severity", "Docs URL"] } AVAILABLE_STACKS = list(STACK_CONFIG.keys()) # ============ BM25 IMPLEMENTATION ============ class BM25: """BM25 ranking algorithm for text search""" def __init__(self, k1=1.5, b=0.75): self.k1 = k1 self.b = b self.corpus = [] self.doc_lengths = [] self.avgdl = 0 self.idf = {} self.doc_freqs = defaultdict(int) self.N = 0 def tokenize(self, text): """Lowercase, split, remove punctuation, filter short words""" text = re.sub(r'[^\w\s]', ' ', str(text).lower()) return [w for w in text.split() if len(w) > 2] def fit(self, documents): """Build BM25 index from documents""" self.corpus = [self.tokenize(doc) for doc in documents] self.N = len(self.corpus) if self.N == 0: return self.doc_lengths = [len(doc) for doc in self.corpus] self.avgdl = sum(self.doc_lengths) / self.N for doc in self.corpus: seen = set() for word in doc: if word not in seen: self.doc_freqs[word] += 1 seen.add(word) for word, freq in self.doc_freqs.items(): self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1) def score(self, query): """Score all documents against query""" query_tokens = self.tokenize(query) scores = [] for idx, doc in enumerate(self.corpus): score = 0 doc_len = self.doc_lengths[idx] term_freqs = defaultdict(int) for word in doc: term_freqs[word] += 1 for token in query_tokens: if token in self.idf: tf = term_freqs[token] idf = self.idf[token] numerator = tf * (self.k1 + 1) denominator = tf + self.k1 * (1 - self.b + self.b * doc_len / self.avgdl) score += idf * numerator / denominator scores.append((idx, score)) return sorted(scores, key=lambda x: x[1], reverse=True) # ============ SEARCH FUNCTIONS ============ def _load_csv(filepath): """Load CSV and return list of dicts""" with open(filepath, 'r', encoding='utf-8') as f: return list(csv.DictReader(f)) def _search_csv(filepath, search_cols, output_cols, query, max_results): """Core search function using BM25""" if not filepath.exists(): return [] data = _load_csv(filepath) # Build documents from search columns documents = [" ".join(str(row.get(col, "")) for col in search_cols) for row in data] # BM25 search bm25 = BM25() bm25.fit(documents) ranked = bm25.score(query) # Get top results with score > 0 results = [] for idx, score in ranked[:max_results]: if score > 0: row = data[idx] results.append({col: row.get(col, "") for col in output_cols if col in row}) return results def detect_domain(query): """Auto-detect the most relevant domain from query""" query_lower = query.lower() domain_keywords = { "color": ["color", "palette", "hex", "#", "rgb"], "chart": ["chart", "graph", "visualization", "trend", "bar", "pie", "scatter", "heatmap", "funnel"], "landing": ["landing", "page", "cta", "conversion", "hero", "testimonial", "pricing", "section"], "product": ["saas", "ecommerce", "e-commerce", "fintech", "healthcare", "gaming", "portfolio", "crypto", "dashboard"], "prompt": ["prompt", "css", "implementation", "variable", "checklist", "tailwind"], "style": ["style", "design", "ui", "minimalism", "glassmorphism", "neumorphism", "brutalism", "dark mode", "flat", "aurora"], "ux": ["ux", "usability", "accessibility", "wcag", "touch", "scroll", "animation", "keyboard", "navigation", "mobile"], "typography": ["font", "typography", "heading", "serif", "sans"], "icons": ["icon", "icons", "lucide", "heroicons", "symbol", "glyph", "pictogram", "svg icon"], "react": ["react", "next.js", "nextjs", "suspense", "memo", "usecallback", "useeffect", "rerender", "bundle", "waterfall", "barrel", "dynamic import", "rsc", "server component"], "web": ["aria", "focus", "outline", "semantic", "virtualize", "autocomplete", "form", "input type", "preconnect"] } scores = {domain: sum(1 for kw in keywords if kw in query_lower) for domain, keywords in domain_keywords.items()} best = max(scores, key=scores.get) return best if scores[best] > 0 else "style" def search(query, domain=None, max_results=MAX_RESULTS): """Main search function with auto-domain detection""" if domain is None: domain = detect_domain(query) config = CSV_CONFIG.get(domain, CSV_CONFIG["style"]) filepath = DATA_DIR / config["file"] if not filepath.exists(): return {"error": f"File not found: {filepath}", "domain": domain} results = _search_csv(filepath, config["search_cols"], config["output_cols"], query, max_results) return { "domain": domain, "query": query, "file": config["file"], "count": len(results), "results": results } def search_stack(query, stack, max_results=MAX_RESULTS): """Search stack-specific guidelines""" if stack not in STACK_CONFIG: return {"error": f"Unknown stack: {stack}. Available: {', '.join(AVAILABLE_STACKS)}"} filepath = DATA_DIR / STACK_CONFIG[stack]["file"] if not filepath.exists(): return {"error": f"Stack file not found: {filepath}", "stack": stack} results = _search_csv(filepath, _STACK_COLS["search_cols"], _STACK_COLS["output_cols"], query, max_results) return { "domain": "stack", "stack": stack, "query": query, "file": STACK_CONFIG[stack]["file"], "count": len(results), "results": results }
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/creative-design/ui-ux-pro-max/scripts/core.py", "license": "MIT License", "lines": 214, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/creative-design/ui-ux-pro-max/scripts/design_system.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Design System Generator - Aggregates search results and applies reasoning to generate comprehensive design system recommendations. Usage: from design_system import generate_design_system result = generate_design_system("SaaS dashboard", "My Project") """ import csv import json from pathlib import Path from core import search, DATA_DIR # ============ CONFIGURATION ============ REASONING_FILE = "ui-reasoning.csv" SEARCH_CONFIG = { "product": {"max_results": 1}, "style": {"max_results": 3}, "color": {"max_results": 2}, "landing": {"max_results": 2}, "typography": {"max_results": 2} } # ============ DESIGN SYSTEM GENERATOR ============ class DesignSystemGenerator: """Generates design system recommendations from aggregated searches.""" def __init__(self): self.reasoning_data = self._load_reasoning() def _load_reasoning(self) -> list: """Load reasoning rules from CSV.""" filepath = DATA_DIR / REASONING_FILE if not filepath.exists(): return [] with open(filepath, 'r', encoding='utf-8') as f: return list(csv.DictReader(f)) def _multi_domain_search(self, query: str, style_priority: list = None) -> dict: """Execute searches across multiple domains.""" results = {} for domain, config in SEARCH_CONFIG.items(): if domain == "style" and style_priority: # For style, also search with priority keywords priority_query = " ".join(style_priority[:2]) if style_priority else query combined_query = f"{query} {priority_query}" results[domain] = search(combined_query, domain, config["max_results"]) else: results[domain] = search(query, domain, config["max_results"]) return results def _find_reasoning_rule(self, category: str) -> dict: """Find matching reasoning rule for a category.""" category_lower = category.lower() # Try exact match first for rule in self.reasoning_data: if rule.get("UI_Category", "").lower() == category_lower: return rule # Try partial match for rule in self.reasoning_data: ui_cat = rule.get("UI_Category", "").lower() if ui_cat in category_lower or category_lower in ui_cat: return rule # Try keyword match for rule in self.reasoning_data: ui_cat = rule.get("UI_Category", "").lower() keywords = ui_cat.replace("/", " ").replace("-", " ").split() if any(kw in category_lower for kw in keywords): return rule return {} def _apply_reasoning(self, category: str, search_results: dict) -> dict: """Apply reasoning rules to search results.""" rule = self._find_reasoning_rule(category) if not rule: return { "pattern": "Hero + Features + CTA", "style_priority": ["Minimalism", "Flat Design"], "color_mood": "Professional", "typography_mood": "Clean", "key_effects": "Subtle hover transitions", "anti_patterns": "", "decision_rules": {}, "severity": "MEDIUM" } # Parse decision rules JSON decision_rules = {} try: decision_rules = json.loads(rule.get("Decision_Rules", "{}")) except json.JSONDecodeError: pass return { "pattern": rule.get("Recommended_Pattern", ""), "style_priority": [s.strip() for s in rule.get("Style_Priority", "").split("+")], "color_mood": rule.get("Color_Mood", ""), "typography_mood": rule.get("Typography_Mood", ""), "key_effects": rule.get("Key_Effects", ""), "anti_patterns": rule.get("Anti_Patterns", ""), "decision_rules": decision_rules, "severity": rule.get("Severity", "MEDIUM") } def _select_best_match(self, results: list, priority_keywords: list) -> dict: """Select best matching result based on priority keywords.""" if not results: return {} if not priority_keywords: return results[0] # First: try exact style name match for priority in priority_keywords: priority_lower = priority.lower().strip() for result in results: style_name = result.get("Style Category", "").lower() if priority_lower in style_name or style_name in priority_lower: return result # Second: score by keyword match in all fields scored = [] for result in results: result_str = str(result).lower() score = 0 for kw in priority_keywords: kw_lower = kw.lower().strip() # Higher score for style name match if kw_lower in result.get("Style Category", "").lower(): score += 10 # Lower score for keyword field match elif kw_lower in result.get("Keywords", "").lower(): score += 3 # Even lower for other field matches elif kw_lower in result_str: score += 1 scored.append((score, result)) scored.sort(key=lambda x: x[0], reverse=True) return scored[0][1] if scored and scored[0][0] > 0 else results[0] def _extract_results(self, search_result: dict) -> list: """Extract results list from search result dict.""" return search_result.get("results", []) def generate(self, query: str, project_name: str = None) -> dict: """Generate complete design system recommendation.""" # Step 1: First search product to get category product_result = search(query, "product", 1) product_results = product_result.get("results", []) category = "General" if product_results: category = product_results[0].get("Product Type", "General") # Step 2: Get reasoning rules for this category reasoning = self._apply_reasoning(category, {}) style_priority = reasoning.get("style_priority", []) # Step 3: Multi-domain search with style priority hints search_results = self._multi_domain_search(query, style_priority) search_results["product"] = product_result # Reuse product search # Step 4: Select best matches from each domain using priority style_results = self._extract_results(search_results.get("style", {})) color_results = self._extract_results(search_results.get("color", {})) typography_results = self._extract_results(search_results.get("typography", {})) landing_results = self._extract_results(search_results.get("landing", {})) best_style = self._select_best_match(style_results, reasoning.get("style_priority", [])) best_color = color_results[0] if color_results else {} best_typography = typography_results[0] if typography_results else {} best_landing = landing_results[0] if landing_results else {} # Step 5: Build final recommendation # Combine effects from both reasoning and style search style_effects = best_style.get("Effects & Animation", "") reasoning_effects = reasoning.get("key_effects", "") combined_effects = style_effects if style_effects else reasoning_effects return { "project_name": project_name or query.upper(), "category": category, "pattern": { "name": best_landing.get("Pattern Name", reasoning.get("pattern", "Hero + Features + CTA")), "sections": best_landing.get("Section Order", "Hero > Features > CTA"), "cta_placement": best_landing.get("Primary CTA Placement", "Above fold"), "color_strategy": best_landing.get("Color Strategy", ""), "conversion": best_landing.get("Conversion Optimization", "") }, "style": { "name": best_style.get("Style Category", "Minimalism"), "type": best_style.get("Type", "General"), "effects": style_effects, "keywords": best_style.get("Keywords", ""), "best_for": best_style.get("Best For", ""), "performance": best_style.get("Performance", ""), "accessibility": best_style.get("Accessibility", "") }, "colors": { "primary": best_color.get("Primary (Hex)", "#2563EB"), "secondary": best_color.get("Secondary (Hex)", "#3B82F6"), "cta": best_color.get("CTA (Hex)", "#F97316"), "background": best_color.get("Background (Hex)", "#F8FAFC"), "text": best_color.get("Text (Hex)", "#1E293B"), "notes": best_color.get("Notes", "") }, "typography": { "heading": best_typography.get("Heading Font", "Inter"), "body": best_typography.get("Body Font", "Inter"), "mood": best_typography.get("Mood/Style Keywords", reasoning.get("typography_mood", "")), "best_for": best_typography.get("Best For", ""), "google_fonts_url": best_typography.get("Google Fonts URL", ""), "css_import": best_typography.get("CSS Import", "") }, "key_effects": combined_effects, "anti_patterns": reasoning.get("anti_patterns", ""), "decision_rules": reasoning.get("decision_rules", {}), "severity": reasoning.get("severity", "MEDIUM") } # ============ OUTPUT FORMATTERS ============ BOX_WIDTH = 90 # Wider box for more content def format_ascii_box(design_system: dict) -> str: """Format design system as ASCII box with emojis (MCP-style).""" project = design_system.get("project_name", "PROJECT") pattern = design_system.get("pattern", {}) style = design_system.get("style", {}) colors = design_system.get("colors", {}) typography = design_system.get("typography", {}) effects = design_system.get("key_effects", "") anti_patterns = design_system.get("anti_patterns", "") def wrap_text(text: str, prefix: str, width: int) -> list: """Wrap long text into multiple lines.""" if not text: return [] words = text.split() lines = [] current_line = prefix for word in words: if len(current_line) + len(word) + 1 <= width - 2: current_line += (" " if current_line != prefix else "") + word else: if current_line != prefix: lines.append(current_line) current_line = prefix + word if current_line != prefix: lines.append(current_line) return lines # Build sections from pattern sections = pattern.get("sections", "").split(">") sections = [s.strip() for s in sections if s.strip()] # Build output lines lines = [] w = BOX_WIDTH - 1 lines.append("+" + "-" * w + "+") lines.append(f"| TARGET: {project} - RECOMMENDED DESIGN SYSTEM".ljust(BOX_WIDTH) + "|") lines.append("+" + "-" * w + "+") lines.append("|" + " " * BOX_WIDTH + "|") # Pattern section lines.append(f"| PATTERN: {pattern.get('name', '')}".ljust(BOX_WIDTH) + "|") if pattern.get('conversion'): lines.append(f"| Conversion: {pattern.get('conversion', '')}".ljust(BOX_WIDTH) + "|") if pattern.get('cta_placement'): lines.append(f"| CTA: {pattern.get('cta_placement', '')}".ljust(BOX_WIDTH) + "|") lines.append("| Sections:".ljust(BOX_WIDTH) + "|") for i, section in enumerate(sections, 1): lines.append(f"| {i}. {section}".ljust(BOX_WIDTH) + "|") lines.append("|" + " " * BOX_WIDTH + "|") # Style section lines.append(f"| STYLE: {style.get('name', '')}".ljust(BOX_WIDTH) + "|") if style.get("keywords"): for line in wrap_text(f"Keywords: {style.get('keywords', '')}", "| ", BOX_WIDTH): lines.append(line.ljust(BOX_WIDTH) + "|") if style.get("best_for"): for line in wrap_text(f"Best For: {style.get('best_for', '')}", "| ", BOX_WIDTH): lines.append(line.ljust(BOX_WIDTH) + "|") if style.get("performance") or style.get("accessibility"): perf_a11y = f"Performance: {style.get('performance', '')} | Accessibility: {style.get('accessibility', '')}" lines.append(f"| {perf_a11y}".ljust(BOX_WIDTH) + "|") lines.append("|" + " " * BOX_WIDTH + "|") # Colors section lines.append("| COLORS:".ljust(BOX_WIDTH) + "|") lines.append(f"| Primary: {colors.get('primary', '')}".ljust(BOX_WIDTH) + "|") lines.append(f"| Secondary: {colors.get('secondary', '')}".ljust(BOX_WIDTH) + "|") lines.append(f"| CTA: {colors.get('cta', '')}".ljust(BOX_WIDTH) + "|") lines.append(f"| Background: {colors.get('background', '')}".ljust(BOX_WIDTH) + "|") lines.append(f"| Text: {colors.get('text', '')}".ljust(BOX_WIDTH) + "|") if colors.get("notes"): for line in wrap_text(f"Notes: {colors.get('notes', '')}", "| ", BOX_WIDTH): lines.append(line.ljust(BOX_WIDTH) + "|") lines.append("|" + " " * BOX_WIDTH + "|") # Typography section lines.append(f"| TYPOGRAPHY: {typography.get('heading', '')} / {typography.get('body', '')}".ljust(BOX_WIDTH) + "|") if typography.get("mood"): for line in wrap_text(f"Mood: {typography.get('mood', '')}", "| ", BOX_WIDTH): lines.append(line.ljust(BOX_WIDTH) + "|") if typography.get("best_for"): for line in wrap_text(f"Best For: {typography.get('best_for', '')}", "| ", BOX_WIDTH): lines.append(line.ljust(BOX_WIDTH) + "|") if typography.get("google_fonts_url"): lines.append(f"| Google Fonts: {typography.get('google_fonts_url', '')}".ljust(BOX_WIDTH) + "|") if typography.get("css_import"): lines.append(f"| CSS Import: {typography.get('css_import', '')[:70]}...".ljust(BOX_WIDTH) + "|") lines.append("|" + " " * BOX_WIDTH + "|") # Key Effects section if effects: lines.append("| KEY EFFECTS:".ljust(BOX_WIDTH) + "|") for line in wrap_text(effects, "| ", BOX_WIDTH): lines.append(line.ljust(BOX_WIDTH) + "|") lines.append("|" + " " * BOX_WIDTH + "|") # Anti-patterns section if anti_patterns: lines.append("| AVOID (Anti-patterns):".ljust(BOX_WIDTH) + "|") for line in wrap_text(anti_patterns, "| ", BOX_WIDTH): lines.append(line.ljust(BOX_WIDTH) + "|") lines.append("|" + " " * BOX_WIDTH + "|") # Pre-Delivery Checklist section lines.append("| PRE-DELIVERY CHECKLIST:".ljust(BOX_WIDTH) + "|") checklist_items = [ "[ ] No emojis as icons (use SVG: Heroicons/Lucide)", "[ ] cursor-pointer on all clickable elements", "[ ] Hover states with smooth transitions (150-300ms)", "[ ] Light mode: text contrast 4.5:1 minimum", "[ ] Focus states visible for keyboard nav", "[ ] prefers-reduced-motion respected", "[ ] Responsive: 375px, 768px, 1024px, 1440px" ] for item in checklist_items: lines.append(f"| {item}".ljust(BOX_WIDTH) + "|") lines.append("|" + " " * BOX_WIDTH + "|") lines.append("+" + "-" * w + "+") return "\n".join(lines) def format_markdown(design_system: dict) -> str: """Format design system as markdown.""" project = design_system.get("project_name", "PROJECT") pattern = design_system.get("pattern", {}) style = design_system.get("style", {}) colors = design_system.get("colors", {}) typography = design_system.get("typography", {}) effects = design_system.get("key_effects", "") anti_patterns = design_system.get("anti_patterns", "") lines = [] lines.append(f"## Design System: {project}") lines.append("") # Pattern section lines.append("### Pattern") lines.append(f"- **Name:** {pattern.get('name', '')}") if pattern.get('conversion'): lines.append(f"- **Conversion Focus:** {pattern.get('conversion', '')}") if pattern.get('cta_placement'): lines.append(f"- **CTA Placement:** {pattern.get('cta_placement', '')}") if pattern.get('color_strategy'): lines.append(f"- **Color Strategy:** {pattern.get('color_strategy', '')}") lines.append(f"- **Sections:** {pattern.get('sections', '')}") lines.append("") # Style section lines.append("### Style") lines.append(f"- **Name:** {style.get('name', '')}") if style.get('keywords'): lines.append(f"- **Keywords:** {style.get('keywords', '')}") if style.get('best_for'): lines.append(f"- **Best For:** {style.get('best_for', '')}") if style.get('performance') or style.get('accessibility'): lines.append(f"- **Performance:** {style.get('performance', '')} | **Accessibility:** {style.get('accessibility', '')}") lines.append("") # Colors section lines.append("### Colors") lines.append(f"| Role | Hex |") lines.append(f"|------|-----|") lines.append(f"| Primary | {colors.get('primary', '')} |") lines.append(f"| Secondary | {colors.get('secondary', '')} |") lines.append(f"| CTA | {colors.get('cta', '')} |") lines.append(f"| Background | {colors.get('background', '')} |") lines.append(f"| Text | {colors.get('text', '')} |") if colors.get("notes"): lines.append(f"\n*Notes: {colors.get('notes', '')}*") lines.append("") # Typography section lines.append("### Typography") lines.append(f"- **Heading:** {typography.get('heading', '')}") lines.append(f"- **Body:** {typography.get('body', '')}") if typography.get("mood"): lines.append(f"- **Mood:** {typography.get('mood', '')}") if typography.get("best_for"): lines.append(f"- **Best For:** {typography.get('best_for', '')}") if typography.get("google_fonts_url"): lines.append(f"- **Google Fonts:** {typography.get('google_fonts_url', '')}") if typography.get("css_import"): lines.append(f"- **CSS Import:**") lines.append(f"```css") lines.append(f"{typography.get('css_import', '')}") lines.append(f"```") lines.append("") # Key Effects section if effects: lines.append("### Key Effects") lines.append(f"{effects}") lines.append("") # Anti-patterns section if anti_patterns: lines.append("### Avoid (Anti-patterns)") lines.append(f"- {anti_patterns.replace(' + ', '\n- ')}") lines.append("") # Pre-Delivery Checklist section lines.append("### Pre-Delivery Checklist") lines.append("- [ ] No emojis as icons (use SVG: Heroicons/Lucide)") lines.append("- [ ] cursor-pointer on all clickable elements") lines.append("- [ ] Hover states with smooth transitions (150-300ms)") lines.append("- [ ] Light mode: text contrast 4.5:1 minimum") lines.append("- [ ] Focus states visible for keyboard nav") lines.append("- [ ] prefers-reduced-motion respected") lines.append("- [ ] Responsive: 375px, 768px, 1024px, 1440px") lines.append("") return "\n".join(lines) # ============ MAIN ENTRY POINT ============ def generate_design_system(query: str, project_name: str = None, output_format: str = "ascii") -> str: """ Main entry point for design system generation. Args: query: Search query (e.g., "SaaS dashboard", "e-commerce luxury") project_name: Optional project name for output header output_format: "ascii" (default) or "markdown" Returns: Formatted design system string """ generator = DesignSystemGenerator() design_system = generator.generate(query, project_name) if output_format == "markdown": return format_markdown(design_system) return format_ascii_box(design_system) # ============ CLI SUPPORT ============ if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="Generate Design System") parser.add_argument("query", help="Search query (e.g., 'SaaS dashboard')") parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name") parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format") args = parser.parse_args() result = generate_design_system(args.query, args.project_name, args.format) print(result)
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/creative-design/ui-ux-pro-max/scripts/design_system.py", "license": "MIT License", "lines": 418, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/creative-design/ui-ux-pro-max/scripts/search.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ UI/UX Pro Max Search - BM25 search engine for UI/UX style guides Usage: python search.py "<query>" [--domain <domain>] [--stack <stack>] [--max-results 3] python search.py "<query>" --design-system [-p "Project Name"] Domains: style, prompt, color, chart, landing, product, ux, typography Stacks: html-tailwind, react, nextjs """ import argparse from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, search, search_stack from design_system import generate_design_system def format_output(result): """Format results for Claude consumption (token-optimized)""" if "error" in result: return f"Error: {result['error']}" output = [] if result.get("stack"): output.append(f"## UI Pro Max Stack Guidelines") output.append(f"**Stack:** {result['stack']} | **Query:** {result['query']}") else: output.append(f"## UI Pro Max Search Results") output.append(f"**Domain:** {result['domain']} | **Query:** {result['query']}") output.append(f"**Source:** {result['file']} | **Found:** {result['count']} results\n") for i, row in enumerate(result['results'], 1): output.append(f"### Result {i}") for key, value in row.items(): value_str = str(value) if len(value_str) > 300: value_str = value_str[:300] + "..." output.append(f"- **{key}:** {value_str}") output.append("") return "\n".join(output) if __name__ == "__main__": parser = argparse.ArgumentParser(description="UI Pro Max Search") parser.add_argument("query", help="Search query") parser.add_argument("--domain", "-d", choices=list(CSV_CONFIG.keys()), help="Search domain") parser.add_argument("--stack", "-s", choices=AVAILABLE_STACKS, help="Stack-specific search (html-tailwind, react, nextjs)") parser.add_argument("--max-results", "-n", type=int, default=MAX_RESULTS, help="Max results (default: 3)") parser.add_argument("--json", action="store_true", help="Output as JSON") # Design system generation parser.add_argument("--design-system", "-ds", action="store_true", help="Generate complete design system recommendation") parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name for design system output") parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format for design system") args = parser.parse_args() # Design system takes priority if args.design_system: result = generate_design_system(args.query, args.project_name, args.format) print(result) # Stack search elif args.stack: result = search_stack(args.query, args.stack, args.max_results) if args.json: import json print(json.dumps(result, indent=2, ensure_ascii=False)) else: print(format_output(result)) # Domain search else: result = search(args.query, args.domain, args.max_results) if args.json: import json print(json.dumps(result, indent=2, ensure_ascii=False)) else: print(format_output(result))
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/creative-design/ui-ux-pro-max/scripts/search.py", "license": "MIT License", "lines": 65, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/development/api-patterns/scripts/api_validator.py
#!/usr/bin/env python3 """ API Validator - Checks API endpoints for best practices. Validates OpenAPI specs, response formats, and common issues. """ import sys import json import re from pathlib import Path # Fix Windows console encoding for Unicode output try: sys.stdout.reconfigure(encoding='utf-8', errors='replace') sys.stderr.reconfigure(encoding='utf-8', errors='replace') except AttributeError: pass # Python < 3.7 def find_api_files(project_path: Path) -> list: """Find API-related files.""" patterns = [ "**/*api*.ts", "**/*api*.js", "**/*api*.py", "**/routes/*.ts", "**/routes/*.js", "**/routes/*.py", "**/controllers/*.ts", "**/controllers/*.js", "**/endpoints/*.ts", "**/endpoints/*.py", "**/*.openapi.json", "**/*.openapi.yaml", "**/swagger.json", "**/swagger.yaml", "**/openapi.json", "**/openapi.yaml" ] files = [] for pattern in patterns: files.extend(project_path.glob(pattern)) # Exclude node_modules, etc. return [f for f in files if not any(x in str(f) for x in ['node_modules', '.git', 'dist', 'build', '__pycache__'])] def check_openapi_spec(file_path: Path) -> dict: """Check OpenAPI/Swagger specification.""" issues = [] passed = [] try: content = file_path.read_text(encoding='utf-8') if file_path.suffix == '.json': spec = json.loads(content) else: # Basic YAML check if 'openapi:' in content or 'swagger:' in content: passed.append("[OK] OpenAPI/Swagger version defined") else: issues.append("[X] No OpenAPI version found") if 'paths:' in content: passed.append("[OK] Paths section exists") else: issues.append("[X] No paths defined") if 'components:' in content or 'definitions:' in content: passed.append("[OK] Schema components defined") return {'file': str(file_path), 'passed': passed, 'issues': issues, 'type': 'openapi'} # JSON OpenAPI checks if 'openapi' in spec or 'swagger' in spec: passed.append("[OK] OpenAPI version defined") if 'info' in spec: if 'title' in spec['info']: passed.append("[OK] API title defined") if 'version' in spec['info']: passed.append("[OK] API version defined") if 'description' not in spec['info']: issues.append("[!] API description missing") if 'paths' in spec: path_count = len(spec['paths']) passed.append(f"[OK] {path_count} endpoints defined") # Check each path for path, methods in spec['paths'].items(): for method, details in methods.items(): if method in ['get', 'post', 'put', 'patch', 'delete']: if 'responses' not in details: issues.append(f"[X] {method.upper()} {path}: No responses defined") if 'summary' not in details and 'description' not in details: issues.append(f"[!] {method.upper()} {path}: No description") except Exception as e: issues.append(f"[X] Parse error: {e}") return {'file': str(file_path), 'passed': passed, 'issues': issues, 'type': 'openapi'} def check_api_code(file_path: Path) -> dict: """Check API code for common issues.""" issues = [] passed = [] try: content = file_path.read_text(encoding='utf-8') # Check for error handling error_patterns = [ r'try\s*{', r'try:', r'\.catch\(', r'except\s+', r'catch\s*\(' ] has_error_handling = any(re.search(p, content) for p in error_patterns) if has_error_handling: passed.append("[OK] Error handling present") else: issues.append("[X] No error handling found") # Check for status codes status_patterns = [ r'status\s*\(\s*\d{3}\s*\)', r'statusCode\s*[=:]\s*\d{3}', r'HttpStatus\.', r'status_code\s*=\s*\d{3}', r'\.status\(\d{3}\)', r'res\.status\(' ] has_status = any(re.search(p, content) for p in status_patterns) if has_status: passed.append("[OK] HTTP status codes used") else: issues.append("[!] No explicit HTTP status codes") # Check for validation validation_patterns = [ r'validate', r'schema', r'zod', r'joi', r'yup', r'pydantic', r'@Body\(', r'@Query\(' ] has_validation = any(re.search(p, content, re.I) for p in validation_patterns) if has_validation: passed.append("[OK] Input validation present") else: issues.append("[!] No input validation detected") # Check for auth middleware auth_patterns = [ r'auth', r'jwt', r'bearer', r'token', r'middleware', r'guard', r'@Authenticated' ] has_auth = any(re.search(p, content, re.I) for p in auth_patterns) if has_auth: passed.append("[OK] Authentication/authorization detected") # Check for rate limiting rate_patterns = [r'rateLimit', r'throttle', r'rate.?limit'] has_rate = any(re.search(p, content, re.I) for p in rate_patterns) if has_rate: passed.append("[OK] Rate limiting present") # Check for logging log_patterns = [r'console\.log', r'logger\.', r'logging\.', r'log\.'] has_logging = any(re.search(p, content) for p in log_patterns) if has_logging: passed.append("[OK] Logging present") except Exception as e: issues.append(f"[X] Read error: {e}") return {'file': str(file_path), 'passed': passed, 'issues': issues, 'type': 'code'} def main(): target = sys.argv[1] if len(sys.argv) > 1 else "." project_path = Path(target) print("\n" + "=" * 60) print(" API VALIDATOR - Endpoint Best Practices Check") print("=" * 60 + "\n") api_files = find_api_files(project_path) if not api_files: print("[!] No API files found.") print(" Looking for: routes/, controllers/, api/, openapi.json/yaml") sys.exit(0) results = [] for file_path in api_files[:15]: # Limit if 'openapi' in file_path.name.lower() or 'swagger' in file_path.name.lower(): result = check_openapi_spec(file_path) else: result = check_api_code(file_path) results.append(result) # Print results total_issues = 0 total_passed = 0 for result in results: print(f"\n[FILE] {result['file']} [{result['type']}]") for item in result['passed']: print(f" {item}") total_passed += 1 for item in result['issues']: print(f" {item}") if item.startswith("[X]"): total_issues += 1 print("\n" + "=" * 60) print(f"[RESULTS] {total_passed} passed, {total_issues} critical issues") print("=" * 60) if total_issues == 0: print("[OK] API validation passed") sys.exit(0) else: print("[X] Fix critical issues before deployment") sys.exit(1) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/development/api-patterns/scripts/api_validator.py", "license": "MIT License", "lines": 175, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/development/database-design/scripts/schema_validator.py
#!/usr/bin/env python3 """ Schema Validator - Database schema validation Validates Prisma schemas and checks for common issues. Usage: python schema_validator.py <project_path> Checks: - Prisma schema syntax - Missing relations - Index recommendations - Naming conventions """ import sys import json import re from pathlib import Path from datetime import datetime # Fix Windows console encoding try: sys.stdout.reconfigure(encoding='utf-8', errors='replace') except: pass def find_schema_files(project_path: Path) -> list: """Find database schema files.""" schemas = [] # Prisma schema prisma_files = list(project_path.glob('**/prisma/schema.prisma')) schemas.extend([('prisma', f) for f in prisma_files]) # Drizzle schema files drizzle_files = list(project_path.glob('**/drizzle/*.ts')) drizzle_files.extend(project_path.glob('**/schema/*.ts')) for f in drizzle_files: if 'schema' in f.name.lower() or 'table' in f.name.lower(): schemas.append(('drizzle', f)) return schemas[:10] # Limit def validate_prisma_schema(file_path: Path) -> list: """Validate Prisma schema file.""" issues = [] try: content = file_path.read_text(encoding='utf-8', errors='ignore') # Find all models models = re.findall(r'model\s+(\w+)\s*{([^}]+)}', content, re.DOTALL) for model_name, model_body in models: # Check naming convention (PascalCase) if not model_name[0].isupper(): issues.append(f"Model '{model_name}' should be PascalCase") # Check for id field if '@id' not in model_body and 'id' not in model_body.lower(): issues.append(f"Model '{model_name}' might be missing @id field") # Check for createdAt/updatedAt if 'createdAt' not in model_body and 'created_at' not in model_body: issues.append(f"Model '{model_name}' missing createdAt field (recommended)") # Check for @relation without fields relations = re.findall(r'@relation\([^)]*\)', model_body) for rel in relations: if 'fields:' not in rel and 'references:' not in rel: pass # Implicit relation, ok # Check for @@index suggestions foreign_keys = re.findall(r'(\w+Id)\s+\w+', model_body) for fk in foreign_keys: if f'@@index([{fk}])' not in content and f'@@index(["{fk}"])' not in content: issues.append(f"Consider adding @@index([{fk}]) for better query performance in {model_name}") # Check for enum definitions enums = re.findall(r'enum\s+(\w+)\s*{', content) for enum_name in enums: if not enum_name[0].isupper(): issues.append(f"Enum '{enum_name}' should be PascalCase") except Exception as e: issues.append(f"Error reading schema: {str(e)[:50]}") return issues def main(): project_path = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve() print(f"\n{'='*60}") print(f"[SCHEMA VALIDATOR] Database Schema Validation") print(f"{'='*60}") print(f"Project: {project_path}") print(f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") print("-"*60) # Find schema files schemas = find_schema_files(project_path) print(f"Found {len(schemas)} schema files") if not schemas: output = { "script": "schema_validator", "project": str(project_path), "schemas_checked": 0, "issues_found": 0, "passed": True, "message": "No schema files found" } print(json.dumps(output, indent=2)) sys.exit(0) # Validate each schema all_issues = [] for schema_type, file_path in schemas: print(f"\nValidating: {file_path.name} ({schema_type})") if schema_type == 'prisma': issues = validate_prisma_schema(file_path) else: issues = [] # Drizzle validation could be added if issues: all_issues.append({ "file": str(file_path.name), "type": schema_type, "issues": issues }) # Summary print("\n" + "="*60) print("SCHEMA ISSUES") print("="*60) if all_issues: for item in all_issues: print(f"\n{item['file']} ({item['type']}):") for issue in item["issues"][:5]: # Limit per file print(f" - {issue}") if len(item["issues"]) > 5: print(f" ... and {len(item['issues']) - 5} more issues") else: print("No schema issues found!") total_issues = sum(len(item["issues"]) for item in all_issues) # Schema issues are warnings, not failures passed = True output = { "script": "schema_validator", "project": str(project_path), "schemas_checked": len(schemas), "issues_found": total_issues, "passed": passed, "issues": all_issues } print("\n" + json.dumps(output, indent=2)) sys.exit(0) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/development/database-design/scripts/schema_validator.py", "license": "MIT License", "lines": 134, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/development/i18n-localization/scripts/i18n_checker.py
#!/usr/bin/env python3 """ i18n Checker - Detects hardcoded strings and missing translations. Scans for untranslated text in React, Vue, and Python files. """ import sys import re import json from pathlib import Path # Fix Windows console encoding for Unicode output try: sys.stdout.reconfigure(encoding='utf-8', errors='replace') sys.stderr.reconfigure(encoding='utf-8', errors='replace') except AttributeError: pass # Python < 3.7 # Patterns that indicate hardcoded strings (should be translated) HARDCODED_PATTERNS = { 'jsx': [ # Text directly in JSX: <div>Hello World</div> r'>\s*[A-Z][a-zA-Z\s]{3,30}\s*</', # JSX attribute strings: title="Welcome" r'(title|placeholder|label|alt|aria-label)="[A-Z][a-zA-Z\s]{2,}"', # Button/heading text r'<(button|h[1-6]|p|span|label)[^>]*>\s*[A-Z][a-zA-Z\s!?.,]{3,}\s*</', ], 'vue': [ # Vue template text r'>\s*[A-Z][a-zA-Z\s]{3,30}\s*</', r'(placeholder|label|title)="[A-Z][a-zA-Z\s]{2,}"', ], 'python': [ # print/raise with string literals r'(print|raise\s+\w+)\s*\(\s*["\'][A-Z][^"\']{5,}["\']', # Flask flash messages r'flash\s*\(\s*["\'][A-Z][^"\']{5,}["\']', ] } # Patterns that indicate proper i18n usage I18N_PATTERNS = [ r't\(["\']', # t('key') - react-i18next r'useTranslation', # React hook r'\$t\(', # Vue i18n r'_\(["\']', # Python gettext r'gettext\(', # Python gettext r'useTranslations', # next-intl r'FormattedMessage', # react-intl r'i18n\.', # Generic i18n ] def find_locale_files(project_path: Path) -> list: """Find translation/locale files.""" patterns = [ "**/locales/**/*.json", "**/translations/**/*.json", "**/lang/**/*.json", "**/i18n/**/*.json", "**/messages/*.json", "**/*.po", # gettext ] files = [] for pattern in patterns: files.extend(project_path.glob(pattern)) return [f for f in files if 'node_modules' not in str(f)] def check_locale_completeness(locale_files: list) -> dict: """Check if all locales have the same keys.""" issues = [] passed = [] if not locale_files: return {'passed': [], 'issues': ["[!] No locale files found"]} # Group by parent folder (language) locales = {} for f in locale_files: if f.suffix == '.json': try: lang = f.parent.name content = json.loads(f.read_text(encoding='utf-8')) if lang not in locales: locales[lang] = {} locales[lang][f.stem] = set(flatten_keys(content)) except: continue if len(locales) < 2: passed.append(f"[OK] Found {len(locale_files)} locale file(s)") return {'passed': passed, 'issues': issues} passed.append(f"[OK] Found {len(locales)} language(s): {', '.join(locales.keys())}") # Compare keys across locales all_langs = list(locales.keys()) base_lang = all_langs[0] for namespace in locales.get(base_lang, {}): base_keys = locales[base_lang].get(namespace, set()) for lang in all_langs[1:]: other_keys = locales.get(lang, {}).get(namespace, set()) missing = base_keys - other_keys if missing: issues.append(f"[X] {lang}/{namespace}: Missing {len(missing)} keys") extra = other_keys - base_keys if extra: issues.append(f"[!] {lang}/{namespace}: {len(extra)} extra keys") if not issues: passed.append("[OK] All locales have matching keys") return {'passed': passed, 'issues': issues} def flatten_keys(d, prefix=''): """Flatten nested dict keys.""" keys = set() for k, v in d.items(): new_key = f"{prefix}.{k}" if prefix else k if isinstance(v, dict): keys.update(flatten_keys(v, new_key)) else: keys.add(new_key) return keys def check_hardcoded_strings(project_path: Path) -> dict: """Check for hardcoded strings in code files.""" issues = [] passed = [] # Find code files extensions = { '.tsx': 'jsx', '.jsx': 'jsx', '.ts': 'jsx', '.js': 'jsx', '.vue': 'vue', '.py': 'python' } code_files = [] for ext in extensions: code_files.extend(project_path.rglob(f"*{ext}")) code_files = [f for f in code_files if not any(x in str(f) for x in ['node_modules', '.git', 'dist', 'build', '__pycache__', 'venv', 'test', 'spec'])] if not code_files: return {'passed': ["[!] No code files found"], 'issues': []} files_with_i18n = 0 files_with_hardcoded = 0 hardcoded_examples = [] for file_path in code_files[:50]: # Limit try: content = file_path.read_text(encoding='utf-8', errors='ignore') ext = file_path.suffix file_type = extensions.get(ext, 'jsx') # Check for i18n usage has_i18n = any(re.search(p, content) for p in I18N_PATTERNS) if has_i18n: files_with_i18n += 1 # Check for hardcoded strings patterns = HARDCODED_PATTERNS.get(file_type, []) hardcoded_found = False for pattern in patterns: matches = re.findall(pattern, content) if matches and not has_i18n: hardcoded_found = True if len(hardcoded_examples) < 5: hardcoded_examples.append(f"{file_path.name}: {str(matches[0])[:40]}...") if hardcoded_found: files_with_hardcoded += 1 except: continue passed.append(f"[OK] Analyzed {len(code_files)} code files") if files_with_i18n > 0: passed.append(f"[OK] {files_with_i18n} files use i18n") if files_with_hardcoded > 0: issues.append(f"[X] {files_with_hardcoded} files may have hardcoded strings") for ex in hardcoded_examples: issues.append(f" → {ex}") else: passed.append("[OK] No obvious hardcoded strings detected") return {'passed': passed, 'issues': issues} def main(): target = sys.argv[1] if len(sys.argv) > 1 else "." project_path = Path(target) print("\n" + "=" * 60) print(" i18n CHECKER - Internationalization Audit") print("=" * 60 + "\n") # Check locale files locale_files = find_locale_files(project_path) locale_result = check_locale_completeness(locale_files) # Check hardcoded strings code_result = check_hardcoded_strings(project_path) # Print results print("[LOCALE FILES]") print("-" * 40) for item in locale_result['passed']: print(f" {item}") for item in locale_result['issues']: print(f" {item}") print("\n[CODE ANALYSIS]") print("-" * 40) for item in code_result['passed']: print(f" {item}") for item in code_result['issues']: print(f" {item}") # Summary critical_issues = sum(1 for i in locale_result['issues'] + code_result['issues'] if i.startswith("[X]")) print("\n" + "=" * 60) if critical_issues == 0: print("[OK] i18n CHECK: PASSED") sys.exit(0) else: print(f"[X] i18n CHECK: {critical_issues} issues found") sys.exit(1) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/development/i18n-localization/scripts/i18n_checker.py", "license": "MIT License", "lines": 197, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/development/lint-and-validate/scripts/lint_runner.py
#!/usr/bin/env python3 """ Lint Runner - Unified linting and type checking Runs appropriate linters based on project type. Usage: python lint_runner.py <project_path> Supports: - Node.js: npm run lint, npx tsc --noEmit - Python: ruff check, mypy """ import subprocess import sys import json from pathlib import Path from datetime import datetime # Fix Windows console encoding try: sys.stdout.reconfigure(encoding='utf-8', errors='replace') except: pass def detect_project_type(project_path: Path) -> dict: """Detect project type and available linters.""" result = { "type": "unknown", "linters": [] } # Node.js project package_json = project_path / "package.json" if package_json.exists(): result["type"] = "node" try: pkg = json.loads(package_json.read_text(encoding='utf-8')) scripts = pkg.get("scripts", {}) deps = {**pkg.get("dependencies", {}), **pkg.get("devDependencies", {})} # Check for lint script if "lint" in scripts: result["linters"].append({"name": "npm lint", "cmd": ["npm", "run", "lint"]}) elif "eslint" in deps: result["linters"].append({"name": "eslint", "cmd": ["npx", "eslint", "."]}) # Check for TypeScript if "typescript" in deps or (project_path / "tsconfig.json").exists(): result["linters"].append({"name": "tsc", "cmd": ["npx", "tsc", "--noEmit"]}) except: pass # Python project if (project_path / "pyproject.toml").exists() or (project_path / "requirements.txt").exists(): result["type"] = "python" # Check for ruff result["linters"].append({"name": "ruff", "cmd": ["ruff", "check", "."]}) # Check for mypy if (project_path / "mypy.ini").exists() or (project_path / "pyproject.toml").exists(): result["linters"].append({"name": "mypy", "cmd": ["mypy", "."]}) return result def run_linter(linter: dict, cwd: Path) -> dict: """Run a single linter and return results.""" result = { "name": linter["name"], "passed": False, "output": "", "error": "" } try: proc = subprocess.run( linter["cmd"], cwd=str(cwd), capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=120 ) result["output"] = proc.stdout[:2000] if proc.stdout else "" result["error"] = proc.stderr[:500] if proc.stderr else "" result["passed"] = proc.returncode == 0 except FileNotFoundError: result["error"] = f"Command not found: {linter['cmd'][0]}" except subprocess.TimeoutExpired: result["error"] = "Timeout after 120s" except Exception as e: result["error"] = str(e) return result def main(): project_path = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve() print(f"\n{'='*60}") print(f"[LINT RUNNER] Unified Linting") print(f"{'='*60}") print(f"Project: {project_path}") print(f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") # Detect project type project_info = detect_project_type(project_path) print(f"Type: {project_info['type']}") print(f"Linters: {len(project_info['linters'])}") print("-"*60) if not project_info["linters"]: print("No linters found for this project type.") output = { "script": "lint_runner", "project": str(project_path), "type": project_info["type"], "checks": [], "passed": True, "message": "No linters configured" } print(json.dumps(output, indent=2)) sys.exit(0) # Run each linter results = [] all_passed = True for linter in project_info["linters"]: print(f"\nRunning: {linter['name']}...") result = run_linter(linter, project_path) results.append(result) if result["passed"]: print(f" [PASS] {linter['name']}") else: print(f" [FAIL] {linter['name']}") if result["error"]: print(f" Error: {result['error'][:200]}") all_passed = False # Summary print("\n" + "="*60) print("SUMMARY") print("="*60) for r in results: icon = "[PASS]" if r["passed"] else "[FAIL]" print(f"{icon} {r['name']}") output = { "script": "lint_runner", "project": str(project_path), "type": project_info["type"], "checks": results, "passed": all_passed } print("\n" + json.dumps(output, indent=2)) sys.exit(0 if all_passed else 1) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/development/lint-and-validate/scripts/lint_runner.py", "license": "MIT License", "lines": 137, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/development/lint-and-validate/scripts/type_coverage.py
#!/usr/bin/env python3 """ Type Coverage Checker - Measures TypeScript/Python type coverage. Identifies untyped functions, any usage, and type safety issues. """ import sys import re import subprocess from pathlib import Path # Fix Windows console encoding for Unicode output try: sys.stdout.reconfigure(encoding='utf-8', errors='replace') sys.stderr.reconfigure(encoding='utf-8', errors='replace') except AttributeError: pass # Python < 3.7 def check_typescript_coverage(project_path: Path) -> dict: """Check TypeScript type coverage.""" issues = [] passed = [] stats = {'any_count': 0, 'untyped_functions': 0, 'total_functions': 0} ts_files = list(project_path.rglob("*.ts")) + list(project_path.rglob("*.tsx")) ts_files = [f for f in ts_files if 'node_modules' not in str(f) and '.d.ts' not in str(f)] if not ts_files: return {'type': 'typescript', 'files': 0, 'passed': [], 'issues': ["[!] No TypeScript files found"], 'stats': stats} for file_path in ts_files[:30]: # Limit try: content = file_path.read_text(encoding='utf-8', errors='ignore') # Count 'any' usage any_matches = re.findall(r':\s*any\b', content) stats['any_count'] += len(any_matches) # Find functions without return types # function name(params) { - no return type untyped = re.findall(r'function\s+\w+\s*\([^)]*\)\s*{', content) # Arrow functions without types: const fn = (x) => or (x) => untyped += re.findall(r'=\s*\([^:)]*\)\s*=>', content) stats['untyped_functions'] += len(untyped) # Count typed functions typed = re.findall(r'function\s+\w+\s*\([^)]*\)\s*:\s*\w+', content) typed += re.findall(r':\s*\([^)]*\)\s*=>\s*\w+', content) stats['total_functions'] += len(typed) + len(untyped) except Exception: continue # Analyze results if stats['any_count'] == 0: passed.append("[OK] No 'any' types found") elif stats['any_count'] <= 5: issues.append(f"[!] {stats['any_count']} 'any' types found (acceptable)") else: issues.append(f"[X] {stats['any_count']} 'any' types found (too many)") if stats['total_functions'] > 0: typed_ratio = (stats['total_functions'] - stats['untyped_functions']) / stats['total_functions'] * 100 if typed_ratio >= 80: passed.append(f"[OK] Type coverage: {typed_ratio:.0f}%") elif typed_ratio >= 50: issues.append(f"[!] Type coverage: {typed_ratio:.0f}% (improve)") else: issues.append(f"[X] Type coverage: {typed_ratio:.0f}% (too low)") passed.append(f"[OK] Analyzed {len(ts_files)} TypeScript files") return {'type': 'typescript', 'files': len(ts_files), 'passed': passed, 'issues': issues, 'stats': stats} def check_python_coverage(project_path: Path) -> dict: """Check Python type hints coverage.""" issues = [] passed = [] stats = {'untyped_functions': 0, 'typed_functions': 0, 'any_count': 0} py_files = list(project_path.rglob("*.py")) py_files = [f for f in py_files if not any(x in str(f) for x in ['venv', '__pycache__', '.git', 'node_modules'])] if not py_files: return {'type': 'python', 'files': 0, 'passed': [], 'issues': ["[!] No Python files found"], 'stats': stats} for file_path in py_files[:30]: # Limit try: content = file_path.read_text(encoding='utf-8', errors='ignore') # Count Any usage any_matches = re.findall(r':\s*Any\b', content) stats['any_count'] += len(any_matches) # Find functions with type hints typed_funcs = re.findall(r'def\s+\w+\s*\([^)]*:[^)]+\)', content) typed_funcs += re.findall(r'def\s+\w+\s*\([^)]*\)\s*->', content) stats['typed_functions'] += len(typed_funcs) # Find functions without type hints all_funcs = re.findall(r'def\s+\w+\s*\(', content) stats['untyped_functions'] += len(all_funcs) - len(typed_funcs) except Exception: continue total = stats['typed_functions'] + stats['untyped_functions'] if total > 0: typed_ratio = stats['typed_functions'] / total * 100 if typed_ratio >= 70: passed.append(f"[OK] Type hints coverage: {typed_ratio:.0f}%") elif typed_ratio >= 40: issues.append(f"[!] Type hints coverage: {typed_ratio:.0f}%") else: issues.append(f"[X] Type hints coverage: {typed_ratio:.0f}% (add type hints)") if stats['any_count'] == 0: passed.append("[OK] No 'Any' types found") elif stats['any_count'] <= 3: issues.append(f"[!] {stats['any_count']} 'Any' types found") else: issues.append(f"[X] {stats['any_count']} 'Any' types found") passed.append(f"[OK] Analyzed {len(py_files)} Python files") return {'type': 'python', 'files': len(py_files), 'passed': passed, 'issues': issues, 'stats': stats} def main(): target = sys.argv[1] if len(sys.argv) > 1 else "." project_path = Path(target) print("\n" + "=" * 60) print(" TYPE COVERAGE CHECKER") print("=" * 60 + "\n") results = [] # Check TypeScript ts_result = check_typescript_coverage(project_path) if ts_result['files'] > 0: results.append(ts_result) # Check Python py_result = check_python_coverage(project_path) if py_result['files'] > 0: results.append(py_result) if not results: print("[!] No TypeScript or Python files found.") sys.exit(0) # Print results critical_issues = 0 for result in results: print(f"\n[{result['type'].upper()}]") print("-" * 40) for item in result['passed']: print(f" {item}") for item in result['issues']: print(f" {item}") if item.startswith("[X]"): critical_issues += 1 print("\n" + "=" * 60) if critical_issues == 0: print("[OK] TYPE COVERAGE: ACCEPTABLE") sys.exit(0) else: print(f"[X] TYPE COVERAGE: {critical_issues} critical issues") sys.exit(1) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/development/lint-and-validate/scripts/type_coverage.py", "license": "MIT License", "lines": 138, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/development/performance-profiling/scripts/lighthouse_audit.py
#!/usr/bin/env python3 """ Skill: performance-profiling Script: lighthouse_audit.py Purpose: Run Lighthouse performance audit on a URL Usage: python lighthouse_audit.py https://example.com Output: JSON with performance scores Note: Requires lighthouse CLI (npm install -g lighthouse) """ import subprocess import json import sys import os import tempfile def run_lighthouse(url: str) -> dict: """Run Lighthouse audit on URL.""" try: with tempfile.NamedTemporaryFile(suffix='.json', delete=False) as f: output_path = f.name result = subprocess.run( [ "lighthouse", url, "--output=json", f"--output-path={output_path}", "--chrome-flags=--headless", "--only-categories=performance,accessibility,best-practices,seo" ], capture_output=True, text=True, timeout=120 ) if os.path.exists(output_path): with open(output_path, 'r') as f: report = json.load(f) os.unlink(output_path) categories = report.get("categories", {}) return { "url": url, "scores": { "performance": int(categories.get("performance", {}).get("score", 0) * 100), "accessibility": int(categories.get("accessibility", {}).get("score", 0) * 100), "best_practices": int(categories.get("best-practices", {}).get("score", 0) * 100), "seo": int(categories.get("seo", {}).get("score", 0) * 100) }, "summary": get_summary(categories) } else: return {"error": "Lighthouse failed to generate report", "stderr": result.stderr[:500]} except subprocess.TimeoutExpired: return {"error": "Lighthouse audit timed out"} except FileNotFoundError: return {"error": "Lighthouse CLI not found. Install with: npm install -g lighthouse"} def get_summary(categories: dict) -> str: """Generate summary based on scores.""" perf = categories.get("performance", {}).get("score", 0) * 100 if perf >= 90: return "[OK] Excellent performance" elif perf >= 50: return "[!] Needs improvement" else: return "[X] Poor performance" if __name__ == "__main__": if len(sys.argv) < 2: print(json.dumps({"error": "Usage: python lighthouse_audit.py <url>"})) sys.exit(1) result = run_lighthouse(sys.argv[1]) print(json.dumps(result, indent=2))
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/development/performance-profiling/scripts/lighthouse_audit.py", "license": "MIT License", "lines": 68, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
davila7/claude-code-templates:cli-tool/components/skills/development/typescript-expert/scripts/ts_diagnostic.py
#!/usr/bin/env python3 """ TypeScript Project Diagnostic Script Analyzes TypeScript projects for configuration, performance, and common issues. """ import subprocess import sys import os import json from pathlib import Path def run_cmd(cmd: str) -> str: """Run shell command and return output.""" try: result = subprocess.run(cmd, shell=True, capture_output=True, text=True) return result.stdout + result.stderr except Exception as e: return str(e) def check_versions(): """Check TypeScript and Node versions.""" print("\n📦 Versions:") print("-" * 40) ts_version = run_cmd("npx tsc --version 2>/dev/null").strip() node_version = run_cmd("node -v 2>/dev/null").strip() print(f" TypeScript: {ts_version or 'Not found'}") print(f" Node.js: {node_version or 'Not found'}") def check_tsconfig(): """Analyze tsconfig.json settings.""" print("\n⚙️ TSConfig Analysis:") print("-" * 40) tsconfig_path = Path("tsconfig.json") if not tsconfig_path.exists(): print("⚠️ tsconfig.json not found") return try: with open(tsconfig_path) as f: config = json.load(f) compiler_opts = config.get("compilerOptions", {}) # Check strict mode if compiler_opts.get("strict"): print("✅ Strict mode enabled") else: print("⚠️ Strict mode NOT enabled") # Check important flags flags = { "noUncheckedIndexedAccess": "Unchecked index access protection", "noImplicitOverride": "Implicit override protection", "skipLibCheck": "Skip lib check (performance)", "incremental": "Incremental compilation" } for flag, desc in flags.items(): status = "✅" if compiler_opts.get(flag) else "⚪" print(f" {status} {desc}: {compiler_opts.get(flag, 'not set')}") # Check module settings print(f"\n Module: {compiler_opts.get('module', 'not set')}") print(f" Module Resolution: {compiler_opts.get('moduleResolution', 'not set')}") print(f" Target: {compiler_opts.get('target', 'not set')}") except json.JSONDecodeError: print("❌ Invalid JSON in tsconfig.json") def check_tooling(): """Detect TypeScript tooling ecosystem.""" print("\n🛠️ Tooling Detection:") print("-" * 40) pkg_path = Path("package.json") if not pkg_path.exists(): print("⚠️ package.json not found") return try: with open(pkg_path) as f: pkg = json.load(f) all_deps = {**pkg.get("dependencies", {}), **pkg.get("devDependencies", {})} tools = { "biome": "Biome (linter/formatter)", "eslint": "ESLint", "prettier": "Prettier", "vitest": "Vitest (testing)", "jest": "Jest (testing)", "turborepo": "Turborepo (monorepo)", "turbo": "Turbo (monorepo)", "nx": "Nx (monorepo)", "lerna": "Lerna (monorepo)" } for tool, desc in tools.items(): for dep in all_deps: if tool in dep.lower(): print(f" ✅ {desc}") break except json.JSONDecodeError: print("❌ Invalid JSON in package.json") def check_monorepo(): """Check for monorepo configuration.""" print("\n📦 Monorepo Check:") print("-" * 40) indicators = [ ("pnpm-workspace.yaml", "PNPM Workspace"), ("lerna.json", "Lerna"), ("nx.json", "Nx"), ("turbo.json", "Turborepo") ] found = False for file, name in indicators: if Path(file).exists(): print(f" ✅ {name} detected") found = True if not found: print(" ⚪ No monorepo configuration detected") def check_type_errors(): """Run quick type check.""" print("\n🔍 Type Check:") print("-" * 40) result = run_cmd("npx tsc --noEmit 2>&1 | head -20") if "error TS" in result: errors = result.count("error TS") print(f" ❌ {errors}+ type errors found") print(result[:500]) else: print(" ✅ No type errors") def check_any_usage(): """Check for any type usage.""" print("\n⚠️ 'any' Type Usage:") print("-" * 40) result = run_cmd("grep -r ': any' --include='*.ts' --include='*.tsx' src/ 2>/dev/null | wc -l") count = result.strip() if count and count != "0": print(f" ⚠️ Found {count} occurrences of ': any'") sample = run_cmd("grep -rn ': any' --include='*.ts' --include='*.tsx' src/ 2>/dev/null | head -5") if sample: print(sample) else: print(" ✅ No explicit 'any' types found") def check_type_assertions(): """Check for type assertions.""" print("\n⚠️ Type Assertions (as):") print("-" * 40) result = run_cmd("grep -r ' as ' --include='*.ts' --include='*.tsx' src/ 2>/dev/null | grep -v 'import' | wc -l") count = result.strip() if count and count != "0": print(f" ⚠️ Found {count} type assertions") else: print(" ✅ No type assertions found") def check_performance(): """Check type checking performance.""" print("\n⏱️ Type Check Performance:") print("-" * 40) result = run_cmd("npx tsc --extendedDiagnostics --noEmit 2>&1 | grep -E 'Check time|Files:|Lines:|Nodes:'") if result.strip(): for line in result.strip().split('\n'): print(f" {line}") else: print(" ⚠️ Could not measure performance") def main(): print("=" * 50) print("🔍 TypeScript Project Diagnostic Report") print("=" * 50) check_versions() check_tsconfig() check_tooling() check_monorepo() check_any_usage() check_type_assertions() check_type_errors() check_performance() print("\n" + "=" * 50) print("✅ Diagnostic Complete") print("=" * 50) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/development/typescript-expert/scripts/ts_diagnostic.py", "license": "MIT License", "lines": 166, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/document-processing/docx-official/ooxml/scripts/pack.py
#!/usr/bin/env python3 """ Tool to pack a directory into a .docx, .pptx, or .xlsx file with XML formatting undone. Example usage: python pack.py <input_directory> <office_file> [--force] """ import argparse import shutil import subprocess import sys import tempfile import defusedxml.minidom import zipfile from pathlib import Path def main(): parser = argparse.ArgumentParser(description="Pack a directory into an Office file") parser.add_argument("input_directory", help="Unpacked Office document directory") parser.add_argument("output_file", help="Output Office file (.docx/.pptx/.xlsx)") parser.add_argument("--force", action="store_true", help="Skip validation") args = parser.parse_args() try: success = pack_document( args.input_directory, args.output_file, validate=not args.force ) # Show warning if validation was skipped if args.force: print("Warning: Skipped validation, file may be corrupt", file=sys.stderr) # Exit with error if validation failed elif not success: print("Contents would produce a corrupt file.", file=sys.stderr) print("Please validate XML before repacking.", file=sys.stderr) print("Use --force to skip validation and pack anyway.", file=sys.stderr) sys.exit(1) except ValueError as e: sys.exit(f"Error: {e}") def pack_document(input_dir, output_file, validate=False): """Pack a directory into an Office file (.docx/.pptx/.xlsx). Args: input_dir: Path to unpacked Office document directory output_file: Path to output Office file validate: If True, validates with soffice (default: False) Returns: bool: True if successful, False if validation failed """ input_dir = Path(input_dir) output_file = Path(output_file) if not input_dir.is_dir(): raise ValueError(f"{input_dir} is not a directory") if output_file.suffix.lower() not in {".docx", ".pptx", ".xlsx"}: raise ValueError(f"{output_file} must be a .docx, .pptx, or .xlsx file") # Work in temporary directory to avoid modifying original with tempfile.TemporaryDirectory() as temp_dir: temp_content_dir = Path(temp_dir) / "content" shutil.copytree(input_dir, temp_content_dir) # Process XML files to remove pretty-printing whitespace for pattern in ["*.xml", "*.rels"]: for xml_file in temp_content_dir.rglob(pattern): condense_xml(xml_file) # Create final Office file as zip archive output_file.parent.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(output_file, "w", zipfile.ZIP_DEFLATED) as zf: for f in temp_content_dir.rglob("*"): if f.is_file(): zf.write(f, f.relative_to(temp_content_dir)) # Validate if requested if validate: if not validate_document(output_file): output_file.unlink() # Delete the corrupt file return False return True def validate_document(doc_path): """Validate document by converting to HTML with soffice.""" # Determine the correct filter based on file extension match doc_path.suffix.lower(): case ".docx": filter_name = "html:HTML" case ".pptx": filter_name = "html:impress_html_Export" case ".xlsx": filter_name = "html:HTML (StarCalc)" with tempfile.TemporaryDirectory() as temp_dir: try: result = subprocess.run( [ "soffice", "--headless", "--convert-to", filter_name, "--outdir", temp_dir, str(doc_path), ], capture_output=True, timeout=10, text=True, ) if not (Path(temp_dir) / f"{doc_path.stem}.html").exists(): error_msg = result.stderr.strip() or "Document validation failed" print(f"Validation error: {error_msg}", file=sys.stderr) return False return True except FileNotFoundError: print("Warning: soffice not found. Skipping validation.", file=sys.stderr) return True except subprocess.TimeoutExpired: print("Validation error: Timeout during conversion", file=sys.stderr) return False except Exception as e: print(f"Validation error: {e}", file=sys.stderr) return False def condense_xml(xml_file): """Strip unnecessary whitespace and remove comments.""" with open(xml_file, "r", encoding="utf-8") as f: dom = defusedxml.minidom.parse(f) # Process each element to remove whitespace and comments for element in dom.getElementsByTagName("*"): # Skip w:t elements and their processing if element.tagName.endswith(":t"): continue # Remove whitespace-only text nodes and comment nodes for child in list(element.childNodes): if ( child.nodeType == child.TEXT_NODE and child.nodeValue and child.nodeValue.strip() == "" ) or child.nodeType == child.COMMENT_NODE: element.removeChild(child) # Write back the condensed XML with open(xml_file, "wb") as f: f.write(dom.toxml(encoding="UTF-8")) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/docx-official/ooxml/scripts/pack.py", "license": "MIT License", "lines": 132, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/document-processing/docx-official/ooxml/scripts/unpack.py
#!/usr/bin/env python3 """Unpack and format XML contents of Office files (.docx, .pptx, .xlsx)""" import random import sys import defusedxml.minidom import zipfile from pathlib import Path # Get command line arguments assert len(sys.argv) == 3, "Usage: python unpack.py <office_file> <output_dir>" input_file, output_dir = sys.argv[1], sys.argv[2] # Extract and format output_path = Path(output_dir) output_path.mkdir(parents=True, exist_ok=True) zipfile.ZipFile(input_file).extractall(output_path) # Pretty print all XML files xml_files = list(output_path.rglob("*.xml")) + list(output_path.rglob("*.rels")) for xml_file in xml_files: content = xml_file.read_text(encoding="utf-8") dom = defusedxml.minidom.parseString(content) xml_file.write_bytes(dom.toprettyxml(indent=" ", encoding="ascii")) # For .docx files, suggest an RSID for tracked changes if input_file.endswith(".docx"): suggested_rsid = "".join(random.choices("0123456789ABCDEF", k=8)) print(f"Suggested RSID for edit session: {suggested_rsid}")
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/docx-official/ooxml/scripts/unpack.py", "license": "MIT License", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
davila7/claude-code-templates:cli-tool/components/skills/document-processing/docx-official/ooxml/scripts/validate.py
#!/usr/bin/env python3 """ Command line tool to validate Office document XML files against XSD schemas and tracked changes. Usage: python validate.py <dir> --original <original_file> """ import argparse import sys from pathlib import Path from validation import DOCXSchemaValidator, PPTXSchemaValidator, RedliningValidator def main(): parser = argparse.ArgumentParser(description="Validate Office document XML files") parser.add_argument( "unpacked_dir", help="Path to unpacked Office document directory", ) parser.add_argument( "--original", required=True, help="Path to original file (.docx/.pptx/.xlsx)", ) parser.add_argument( "-v", "--verbose", action="store_true", help="Enable verbose output", ) args = parser.parse_args() # Validate paths unpacked_dir = Path(args.unpacked_dir) original_file = Path(args.original) file_extension = original_file.suffix.lower() assert unpacked_dir.is_dir(), f"Error: {unpacked_dir} is not a directory" assert original_file.is_file(), f"Error: {original_file} is not a file" assert file_extension in [".docx", ".pptx", ".xlsx"], ( f"Error: {original_file} must be a .docx, .pptx, or .xlsx file" ) # Run validations match file_extension: case ".docx": validators = [DOCXSchemaValidator, RedliningValidator] case ".pptx": validators = [PPTXSchemaValidator] case _: print(f"Error: Validation not supported for file type {file_extension}") sys.exit(1) # Run validators success = True for V in validators: validator = V(unpacked_dir, original_file, verbose=args.verbose) if not validator.validate(): success = False if success: print("All validations PASSED!") sys.exit(0 if success else 1) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/docx-official/ooxml/scripts/validate.py", "license": "MIT License", "lines": 57, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
davila7/claude-code-templates:cli-tool/components/skills/document-processing/docx-official/ooxml/scripts/validation/base.py
""" Base validator with common validation logic for document files. """ import re from pathlib import Path import lxml.etree class BaseSchemaValidator: """Base validator with common validation logic for document files.""" # Elements whose 'id' attributes must be unique within their file # Format: element_name -> (attribute_name, scope) # scope can be 'file' (unique within file) or 'global' (unique across all files) UNIQUE_ID_REQUIREMENTS = { # Word elements "comment": ("id", "file"), # Comment IDs in comments.xml "commentrangestart": ("id", "file"), # Must match comment IDs "commentrangeend": ("id", "file"), # Must match comment IDs "bookmarkstart": ("id", "file"), # Bookmark start IDs "bookmarkend": ("id", "file"), # Bookmark end IDs # Note: ins and del (track changes) can share IDs when part of same revision # PowerPoint elements "sldid": ("id", "file"), # Slide IDs in presentation.xml "sldmasterid": ("id", "global"), # Slide master IDs must be globally unique "sldlayoutid": ("id", "global"), # Slide layout IDs must be globally unique "cm": ("authorid", "file"), # Comment author IDs # Excel elements "sheet": ("sheetid", "file"), # Sheet IDs in workbook.xml "definedname": ("id", "file"), # Named range IDs # Drawing/Shape elements (all formats) "cxnsp": ("id", "file"), # Connection shape IDs "sp": ("id", "file"), # Shape IDs "pic": ("id", "file"), # Picture IDs "grpsp": ("id", "file"), # Group shape IDs } # Mapping of element names to expected relationship types # Subclasses should override this with format-specific mappings ELEMENT_RELATIONSHIP_TYPES = {} # Unified schema mappings for all Office document types SCHEMA_MAPPINGS = { # Document type specific schemas "word": "ISO-IEC29500-4_2016/wml.xsd", # Word documents "ppt": "ISO-IEC29500-4_2016/pml.xsd", # PowerPoint presentations "xl": "ISO-IEC29500-4_2016/sml.xsd", # Excel spreadsheets # Common file types "[Content_Types].xml": "ecma/fouth-edition/opc-contentTypes.xsd", "app.xml": "ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd", "core.xml": "ecma/fouth-edition/opc-coreProperties.xsd", "custom.xml": "ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd", ".rels": "ecma/fouth-edition/opc-relationships.xsd", # Word-specific files "people.xml": "microsoft/wml-2012.xsd", "commentsIds.xml": "microsoft/wml-cid-2016.xsd", "commentsExtensible.xml": "microsoft/wml-cex-2018.xsd", "commentsExtended.xml": "microsoft/wml-2012.xsd", # Chart files (common across document types) "chart": "ISO-IEC29500-4_2016/dml-chart.xsd", # Theme files (common across document types) "theme": "ISO-IEC29500-4_2016/dml-main.xsd", # Drawing and media files "drawing": "ISO-IEC29500-4_2016/dml-main.xsd", } # Unified namespace constants MC_NAMESPACE = "http://schemas.openxmlformats.org/markup-compatibility/2006" XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace" # Common OOXML namespaces used across validators PACKAGE_RELATIONSHIPS_NAMESPACE = ( "http://schemas.openxmlformats.org/package/2006/relationships" ) OFFICE_RELATIONSHIPS_NAMESPACE = ( "http://schemas.openxmlformats.org/officeDocument/2006/relationships" ) CONTENT_TYPES_NAMESPACE = ( "http://schemas.openxmlformats.org/package/2006/content-types" ) # Folders where we should clean ignorable namespaces MAIN_CONTENT_FOLDERS = {"word", "ppt", "xl"} # All allowed OOXML namespaces (superset of all document types) OOXML_NAMESPACES = { "http://schemas.openxmlformats.org/officeDocument/2006/math", "http://schemas.openxmlformats.org/officeDocument/2006/relationships", "http://schemas.openxmlformats.org/schemaLibrary/2006/main", "http://schemas.openxmlformats.org/drawingml/2006/main", "http://schemas.openxmlformats.org/drawingml/2006/chart", "http://schemas.openxmlformats.org/drawingml/2006/chartDrawing", "http://schemas.openxmlformats.org/drawingml/2006/diagram", "http://schemas.openxmlformats.org/drawingml/2006/picture", "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", "http://schemas.openxmlformats.org/wordprocessingml/2006/main", "http://schemas.openxmlformats.org/presentationml/2006/main", "http://schemas.openxmlformats.org/spreadsheetml/2006/main", "http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes", "http://www.w3.org/XML/1998/namespace", } def __init__(self, unpacked_dir, original_file, verbose=False): self.unpacked_dir = Path(unpacked_dir).resolve() self.original_file = Path(original_file) self.verbose = verbose # Set schemas directory self.schemas_dir = Path(__file__).parent.parent.parent / "schemas" # Get all XML and .rels files patterns = ["*.xml", "*.rels"] self.xml_files = [ f for pattern in patterns for f in self.unpacked_dir.rglob(pattern) ] if not self.xml_files: print(f"Warning: No XML files found in {self.unpacked_dir}") def validate(self): """Run all validation checks and return True if all pass.""" raise NotImplementedError("Subclasses must implement the validate method") def validate_xml(self): """Validate that all XML files are well-formed.""" errors = [] for xml_file in self.xml_files: try: # Try to parse the XML file lxml.etree.parse(str(xml_file)) except lxml.etree.XMLSyntaxError as e: errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: " f"Line {e.lineno}: {e.msg}" ) except Exception as e: errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: " f"Unexpected error: {str(e)}" ) if errors: print(f"FAILED - Found {len(errors)} XML violations:") for error in errors: print(error) return False else: if self.verbose: print("PASSED - All XML files are well-formed") return True def validate_namespaces(self): """Validate that namespace prefixes in Ignorable attributes are declared.""" errors = [] for xml_file in self.xml_files: try: root = lxml.etree.parse(str(xml_file)).getroot() declared = set(root.nsmap.keys()) - {None} # Exclude default namespace for attr_val in [ v for k, v in root.attrib.items() if k.endswith("Ignorable") ]: undeclared = set(attr_val.split()) - declared errors.extend( f" {xml_file.relative_to(self.unpacked_dir)}: " f"Namespace '{ns}' in Ignorable but not declared" for ns in undeclared ) except lxml.etree.XMLSyntaxError: continue if errors: print(f"FAILED - {len(errors)} namespace issues:") for error in errors: print(error) return False if self.verbose: print("PASSED - All namespace prefixes properly declared") return True def validate_unique_ids(self): """Validate that specific IDs are unique according to OOXML requirements.""" errors = [] global_ids = {} # Track globally unique IDs across all files for xml_file in self.xml_files: try: root = lxml.etree.parse(str(xml_file)).getroot() file_ids = {} # Track IDs that must be unique within this file # Remove all mc:AlternateContent elements from the tree mc_elements = root.xpath( ".//mc:AlternateContent", namespaces={"mc": self.MC_NAMESPACE} ) for elem in mc_elements: elem.getparent().remove(elem) # Now check IDs in the cleaned tree for elem in root.iter(): # Get the element name without namespace tag = ( elem.tag.split("}")[-1].lower() if "}" in elem.tag else elem.tag.lower() ) # Check if this element type has ID uniqueness requirements if tag in self.UNIQUE_ID_REQUIREMENTS: attr_name, scope = self.UNIQUE_ID_REQUIREMENTS[tag] # Look for the specified attribute id_value = None for attr, value in elem.attrib.items(): attr_local = ( attr.split("}")[-1].lower() if "}" in attr else attr.lower() ) if attr_local == attr_name: id_value = value break if id_value is not None: if scope == "global": # Check global uniqueness if id_value in global_ids: prev_file, prev_line, prev_tag = global_ids[ id_value ] errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: " f"Line {elem.sourceline}: Global ID '{id_value}' in <{tag}> " f"already used in {prev_file} at line {prev_line} in <{prev_tag}>" ) else: global_ids[id_value] = ( xml_file.relative_to(self.unpacked_dir), elem.sourceline, tag, ) elif scope == "file": # Check file-level uniqueness key = (tag, attr_name) if key not in file_ids: file_ids[key] = {} if id_value in file_ids[key]: prev_line = file_ids[key][id_value] errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: " f"Line {elem.sourceline}: Duplicate {attr_name}='{id_value}' in <{tag}> " f"(first occurrence at line {prev_line})" ) else: file_ids[key][id_value] = elem.sourceline except (lxml.etree.XMLSyntaxError, Exception) as e: errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}" ) if errors: print(f"FAILED - Found {len(errors)} ID uniqueness violations:") for error in errors: print(error) return False else: if self.verbose: print("PASSED - All required IDs are unique") return True def validate_file_references(self): """ Validate that all .rels files properly reference files and that all files are referenced. """ errors = [] # Find all .rels files rels_files = list(self.unpacked_dir.rglob("*.rels")) if not rels_files: if self.verbose: print("PASSED - No .rels files found") return True # Get all files in the unpacked directory (excluding reference files) all_files = [] for file_path in self.unpacked_dir.rglob("*"): if ( file_path.is_file() and file_path.name != "[Content_Types].xml" and not file_path.name.endswith(".rels") ): # This file is not referenced by .rels all_files.append(file_path.resolve()) # Track all files that are referenced by any .rels file all_referenced_files = set() if self.verbose: print( f"Found {len(rels_files)} .rels files and {len(all_files)} target files" ) # Check each .rels file for rels_file in rels_files: try: # Parse relationships file rels_root = lxml.etree.parse(str(rels_file)).getroot() # Get the directory where this .rels file is located rels_dir = rels_file.parent # Find all relationships and their targets referenced_files = set() broken_refs = [] for rel in rels_root.findall( ".//ns:Relationship", namespaces={"ns": self.PACKAGE_RELATIONSHIPS_NAMESPACE}, ): target = rel.get("Target") if target and not target.startswith( ("http", "mailto:") ): # Skip external URLs # Resolve the target path relative to the .rels file location if rels_file.name == ".rels": # Root .rels file - targets are relative to unpacked_dir target_path = self.unpacked_dir / target else: # Other .rels files - targets are relative to their parent's parent # e.g., word/_rels/document.xml.rels -> targets relative to word/ base_dir = rels_dir.parent target_path = base_dir / target # Normalize the path and check if it exists try: target_path = target_path.resolve() if target_path.exists() and target_path.is_file(): referenced_files.add(target_path) all_referenced_files.add(target_path) else: broken_refs.append((target, rel.sourceline)) except (OSError, ValueError): broken_refs.append((target, rel.sourceline)) # Report broken references if broken_refs: rel_path = rels_file.relative_to(self.unpacked_dir) for broken_ref, line_num in broken_refs: errors.append( f" {rel_path}: Line {line_num}: Broken reference to {broken_ref}" ) except Exception as e: rel_path = rels_file.relative_to(self.unpacked_dir) errors.append(f" Error parsing {rel_path}: {e}") # Check for unreferenced files (files that exist but are not referenced anywhere) unreferenced_files = set(all_files) - all_referenced_files if unreferenced_files: for unref_file in sorted(unreferenced_files): unref_rel_path = unref_file.relative_to(self.unpacked_dir) errors.append(f" Unreferenced file: {unref_rel_path}") if errors: print(f"FAILED - Found {len(errors)} relationship validation errors:") for error in errors: print(error) print( "CRITICAL: These errors will cause the document to appear corrupt. " + "Broken references MUST be fixed, " + "and unreferenced files MUST be referenced or removed." ) return False else: if self.verbose: print( "PASSED - All references are valid and all files are properly referenced" ) return True def validate_all_relationship_ids(self): """ Validate that all r:id attributes in XML files reference existing IDs in their corresponding .rels files, and optionally validate relationship types. """ import lxml.etree errors = [] # Process each XML file that might contain r:id references for xml_file in self.xml_files: # Skip .rels files themselves if xml_file.suffix == ".rels": continue # Determine the corresponding .rels file # For dir/file.xml, it's dir/_rels/file.xml.rels rels_dir = xml_file.parent / "_rels" rels_file = rels_dir / f"{xml_file.name}.rels" # Skip if there's no corresponding .rels file (that's okay) if not rels_file.exists(): continue try: # Parse the .rels file to get valid relationship IDs and their types rels_root = lxml.etree.parse(str(rels_file)).getroot() rid_to_type = {} for rel in rels_root.findall( f".//{{{self.PACKAGE_RELATIONSHIPS_NAMESPACE}}}Relationship" ): rid = rel.get("Id") rel_type = rel.get("Type", "") if rid: # Check for duplicate rIds if rid in rid_to_type: rels_rel_path = rels_file.relative_to(self.unpacked_dir) errors.append( f" {rels_rel_path}: Line {rel.sourceline}: " f"Duplicate relationship ID '{rid}' (IDs must be unique)" ) # Extract just the type name from the full URL type_name = ( rel_type.split("/")[-1] if "/" in rel_type else rel_type ) rid_to_type[rid] = type_name # Parse the XML file to find all r:id references xml_root = lxml.etree.parse(str(xml_file)).getroot() # Find all elements with r:id attributes for elem in xml_root.iter(): # Check for r:id attribute (relationship ID) rid_attr = elem.get(f"{{{self.OFFICE_RELATIONSHIPS_NAMESPACE}}}id") if rid_attr: xml_rel_path = xml_file.relative_to(self.unpacked_dir) elem_name = ( elem.tag.split("}")[-1] if "}" in elem.tag else elem.tag ) # Check if the ID exists if rid_attr not in rid_to_type: errors.append( f" {xml_rel_path}: Line {elem.sourceline}: " f"<{elem_name}> references non-existent relationship '{rid_attr}' " f"(valid IDs: {', '.join(sorted(rid_to_type.keys())[:5])}{'...' if len(rid_to_type) > 5 else ''})" ) # Check if we have type expectations for this element elif self.ELEMENT_RELATIONSHIP_TYPES: expected_type = self._get_expected_relationship_type( elem_name ) if expected_type: actual_type = rid_to_type[rid_attr] # Check if the actual type matches or contains the expected type if expected_type not in actual_type.lower(): errors.append( f" {xml_rel_path}: Line {elem.sourceline}: " f"<{elem_name}> references '{rid_attr}' which points to '{actual_type}' " f"but should point to a '{expected_type}' relationship" ) except Exception as e: xml_rel_path = xml_file.relative_to(self.unpacked_dir) errors.append(f" Error processing {xml_rel_path}: {e}") if errors: print(f"FAILED - Found {len(errors)} relationship ID reference errors:") for error in errors: print(error) print("\nThese ID mismatches will cause the document to appear corrupt!") return False else: if self.verbose: print("PASSED - All relationship ID references are valid") return True def _get_expected_relationship_type(self, element_name): """ Get the expected relationship type for an element. First checks the explicit mapping, then tries pattern detection. """ # Normalize element name to lowercase elem_lower = element_name.lower() # Check explicit mapping first if elem_lower in self.ELEMENT_RELATIONSHIP_TYPES: return self.ELEMENT_RELATIONSHIP_TYPES[elem_lower] # Try pattern detection for common patterns # Pattern 1: Elements ending in "Id" often expect a relationship of the prefix type if elem_lower.endswith("id") and len(elem_lower) > 2: # e.g., "sldId" -> "sld", "sldMasterId" -> "sldMaster" prefix = elem_lower[:-2] # Remove "id" # Check if this might be a compound like "sldMasterId" if prefix.endswith("master"): return prefix.lower() elif prefix.endswith("layout"): return prefix.lower() else: # Simple case like "sldId" -> "slide" # Common transformations if prefix == "sld": return "slide" return prefix.lower() # Pattern 2: Elements ending in "Reference" expect a relationship of the prefix type if elem_lower.endswith("reference") and len(elem_lower) > 9: prefix = elem_lower[:-9] # Remove "reference" return prefix.lower() return None def validate_content_types(self): """Validate that all content files are properly declared in [Content_Types].xml.""" errors = [] # Find [Content_Types].xml file content_types_file = self.unpacked_dir / "[Content_Types].xml" if not content_types_file.exists(): print("FAILED - [Content_Types].xml file not found") return False try: # Parse and get all declared parts and extensions root = lxml.etree.parse(str(content_types_file)).getroot() declared_parts = set() declared_extensions = set() # Get Override declarations (specific files) for override in root.findall( f".//{{{self.CONTENT_TYPES_NAMESPACE}}}Override" ): part_name = override.get("PartName") if part_name is not None: declared_parts.add(part_name.lstrip("/")) # Get Default declarations (by extension) for default in root.findall( f".//{{{self.CONTENT_TYPES_NAMESPACE}}}Default" ): extension = default.get("Extension") if extension is not None: declared_extensions.add(extension.lower()) # Root elements that require content type declaration declarable_roots = { "sld", "sldLayout", "sldMaster", "presentation", # PowerPoint "document", # Word "workbook", "worksheet", # Excel "theme", # Common } # Common media file extensions that should be declared media_extensions = { "png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "gif": "image/gif", "bmp": "image/bmp", "tiff": "image/tiff", "wmf": "image/x-wmf", "emf": "image/x-emf", } # Get all files in the unpacked directory all_files = list(self.unpacked_dir.rglob("*")) all_files = [f for f in all_files if f.is_file()] # Check all XML files for Override declarations for xml_file in self.xml_files: path_str = str(xml_file.relative_to(self.unpacked_dir)).replace( "\\", "/" ) # Skip non-content files if any( skip in path_str for skip in [".rels", "[Content_Types]", "docProps/", "_rels/"] ): continue try: root_tag = lxml.etree.parse(str(xml_file)).getroot().tag root_name = root_tag.split("}")[-1] if "}" in root_tag else root_tag if root_name in declarable_roots and path_str not in declared_parts: errors.append( f" {path_str}: File with <{root_name}> root not declared in [Content_Types].xml" ) except Exception: continue # Skip unparseable files # Check all non-XML files for Default extension declarations for file_path in all_files: # Skip XML files and metadata files (already checked above) if file_path.suffix.lower() in {".xml", ".rels"}: continue if file_path.name == "[Content_Types].xml": continue if "_rels" in file_path.parts or "docProps" in file_path.parts: continue extension = file_path.suffix.lstrip(".").lower() if extension and extension not in declared_extensions: # Check if it's a known media extension that should be declared if extension in media_extensions: relative_path = file_path.relative_to(self.unpacked_dir) errors.append( f' {relative_path}: File with extension \'{extension}\' not declared in [Content_Types].xml - should add: <Default Extension="{extension}" ContentType="{media_extensions[extension]}"/>' ) except Exception as e: errors.append(f" Error parsing [Content_Types].xml: {e}") if errors: print(f"FAILED - Found {len(errors)} content type declaration errors:") for error in errors: print(error) return False else: if self.verbose: print( "PASSED - All content files are properly declared in [Content_Types].xml" ) return True def validate_file_against_xsd(self, xml_file, verbose=False): """Validate a single XML file against XSD schema, comparing with original. Args: xml_file: Path to XML file to validate verbose: Enable verbose output Returns: tuple: (is_valid, new_errors_set) where is_valid is True/False/None (skipped) """ # Resolve both paths to handle symlinks xml_file = Path(xml_file).resolve() unpacked_dir = self.unpacked_dir.resolve() # Validate current file is_valid, current_errors = self._validate_single_file_xsd( xml_file, unpacked_dir ) if is_valid is None: return None, set() # Skipped elif is_valid: return True, set() # Valid, no errors # Get errors from original file for this specific file original_errors = self._get_original_file_errors(xml_file) # Compare with original (both are guaranteed to be sets here) assert current_errors is not None new_errors = current_errors - original_errors if new_errors: if verbose: relative_path = xml_file.relative_to(unpacked_dir) print(f"FAILED - {relative_path}: {len(new_errors)} new error(s)") for error in list(new_errors)[:3]: truncated = error[:250] + "..." if len(error) > 250 else error print(f" - {truncated}") return False, new_errors else: # All errors existed in original if verbose: print( f"PASSED - No new errors (original had {len(current_errors)} errors)" ) return True, set() def validate_against_xsd(self): """Validate XML files against XSD schemas, showing only new errors compared to original.""" new_errors = [] original_error_count = 0 valid_count = 0 skipped_count = 0 for xml_file in self.xml_files: relative_path = str(xml_file.relative_to(self.unpacked_dir)) is_valid, new_file_errors = self.validate_file_against_xsd( xml_file, verbose=False ) if is_valid is None: skipped_count += 1 continue elif is_valid and not new_file_errors: valid_count += 1 continue elif is_valid: # Had errors but all existed in original original_error_count += 1 valid_count += 1 continue # Has new errors new_errors.append(f" {relative_path}: {len(new_file_errors)} new error(s)") for error in list(new_file_errors)[:3]: # Show first 3 errors new_errors.append( f" - {error[:250]}..." if len(error) > 250 else f" - {error}" ) # Print summary if self.verbose: print(f"Validated {len(self.xml_files)} files:") print(f" - Valid: {valid_count}") print(f" - Skipped (no schema): {skipped_count}") if original_error_count: print(f" - With original errors (ignored): {original_error_count}") print( f" - With NEW errors: {len(new_errors) > 0 and len([e for e in new_errors if not e.startswith(' ')]) or 0}" ) if new_errors: print("\nFAILED - Found NEW validation errors:") for error in new_errors: print(error) return False else: if self.verbose: print("\nPASSED - No new XSD validation errors introduced") return True def _get_schema_path(self, xml_file): """Determine the appropriate schema path for an XML file.""" # Check exact filename match if xml_file.name in self.SCHEMA_MAPPINGS: return self.schemas_dir / self.SCHEMA_MAPPINGS[xml_file.name] # Check .rels files if xml_file.suffix == ".rels": return self.schemas_dir / self.SCHEMA_MAPPINGS[".rels"] # Check chart files if "charts/" in str(xml_file) and xml_file.name.startswith("chart"): return self.schemas_dir / self.SCHEMA_MAPPINGS["chart"] # Check theme files if "theme/" in str(xml_file) and xml_file.name.startswith("theme"): return self.schemas_dir / self.SCHEMA_MAPPINGS["theme"] # Check if file is in a main content folder and use appropriate schema if xml_file.parent.name in self.MAIN_CONTENT_FOLDERS: return self.schemas_dir / self.SCHEMA_MAPPINGS[xml_file.parent.name] return None def _clean_ignorable_namespaces(self, xml_doc): """Remove attributes and elements not in allowed namespaces.""" # Create a clean copy xml_string = lxml.etree.tostring(xml_doc, encoding="unicode") xml_copy = lxml.etree.fromstring(xml_string) # Remove attributes not in allowed namespaces for elem in xml_copy.iter(): attrs_to_remove = [] for attr in elem.attrib: # Check if attribute is from a namespace other than allowed ones if "{" in attr: ns = attr.split("}")[0][1:] if ns not in self.OOXML_NAMESPACES: attrs_to_remove.append(attr) # Remove collected attributes for attr in attrs_to_remove: del elem.attrib[attr] # Remove elements not in allowed namespaces self._remove_ignorable_elements(xml_copy) return lxml.etree.ElementTree(xml_copy) def _remove_ignorable_elements(self, root): """Recursively remove all elements not in allowed namespaces.""" elements_to_remove = [] # Find elements to remove for elem in list(root): # Skip non-element nodes (comments, processing instructions, etc.) if not hasattr(elem, "tag") or callable(elem.tag): continue tag_str = str(elem.tag) if tag_str.startswith("{"): ns = tag_str.split("}")[0][1:] if ns not in self.OOXML_NAMESPACES: elements_to_remove.append(elem) continue # Recursively clean child elements self._remove_ignorable_elements(elem) # Remove collected elements for elem in elements_to_remove: root.remove(elem) def _preprocess_for_mc_ignorable(self, xml_doc): """Preprocess XML to handle mc:Ignorable attribute properly.""" # Remove mc:Ignorable attributes before validation root = xml_doc.getroot() # Remove mc:Ignorable attribute from root if f"{{{self.MC_NAMESPACE}}}Ignorable" in root.attrib: del root.attrib[f"{{{self.MC_NAMESPACE}}}Ignorable"] return xml_doc def _validate_single_file_xsd(self, xml_file, base_path): """Validate a single XML file against XSD schema. Returns (is_valid, errors_set).""" schema_path = self._get_schema_path(xml_file) if not schema_path: return None, None # Skip file try: # Load schema with open(schema_path, "rb") as xsd_file: parser = lxml.etree.XMLParser() xsd_doc = lxml.etree.parse( xsd_file, parser=parser, base_url=str(schema_path) ) schema = lxml.etree.XMLSchema(xsd_doc) # Load and preprocess XML with open(xml_file, "r") as f: xml_doc = lxml.etree.parse(f) xml_doc, _ = self._remove_template_tags_from_text_nodes(xml_doc) xml_doc = self._preprocess_for_mc_ignorable(xml_doc) # Clean ignorable namespaces if needed relative_path = xml_file.relative_to(base_path) if ( relative_path.parts and relative_path.parts[0] in self.MAIN_CONTENT_FOLDERS ): xml_doc = self._clean_ignorable_namespaces(xml_doc) # Validate if schema.validate(xml_doc): return True, set() else: errors = set() for error in schema.error_log: # Store normalized error message (without line numbers for comparison) errors.add(error.message) return False, errors except Exception as e: return False, {str(e)} def _get_original_file_errors(self, xml_file): """Get XSD validation errors from a single file in the original document. Args: xml_file: Path to the XML file in unpacked_dir to check Returns: set: Set of error messages from the original file """ import tempfile import zipfile # Resolve both paths to handle symlinks (e.g., /var vs /private/var on macOS) xml_file = Path(xml_file).resolve() unpacked_dir = self.unpacked_dir.resolve() relative_path = xml_file.relative_to(unpacked_dir) with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) # Extract original file with zipfile.ZipFile(self.original_file, "r") as zip_ref: zip_ref.extractall(temp_path) # Find corresponding file in original original_xml_file = temp_path / relative_path if not original_xml_file.exists(): # File didn't exist in original, so no original errors return set() # Validate the specific file in original is_valid, errors = self._validate_single_file_xsd( original_xml_file, temp_path ) return errors if errors else set() def _remove_template_tags_from_text_nodes(self, xml_doc): """Remove template tags from XML text nodes and collect warnings. Template tags follow the pattern {{ ... }} and are used as placeholders for content replacement. They should be removed from text content before XSD validation while preserving XML structure. Returns: tuple: (cleaned_xml_doc, warnings_list) """ warnings = [] template_pattern = re.compile(r"\{\{[^}]*\}\}") # Create a copy of the document to avoid modifying the original xml_string = lxml.etree.tostring(xml_doc, encoding="unicode") xml_copy = lxml.etree.fromstring(xml_string) def process_text_content(text, content_type): if not text: return text matches = list(template_pattern.finditer(text)) if matches: for match in matches: warnings.append( f"Found template tag in {content_type}: {match.group()}" ) return template_pattern.sub("", text) return text # Process all text nodes in the document for elem in xml_copy.iter(): # Skip processing if this is a w:t element if not hasattr(elem, "tag") or callable(elem.tag): continue tag_str = str(elem.tag) if tag_str.endswith("}t") or tag_str == "t": continue elem.text = process_text_content(elem.text, "text content") elem.tail = process_text_content(elem.tail, "tail content") return lxml.etree.ElementTree(xml_copy), warnings if __name__ == "__main__": raise RuntimeError("This module should not be run directly.")
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/docx-official/ooxml/scripts/validation/base.py", "license": "MIT License", "lines": 808, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/document-processing/docx-official/ooxml/scripts/validation/docx.py
""" Validator for Word document XML files against XSD schemas. """ import re import tempfile import zipfile import lxml.etree from .base import BaseSchemaValidator class DOCXSchemaValidator(BaseSchemaValidator): """Validator for Word document XML files against XSD schemas.""" # Word-specific namespace WORD_2006_NAMESPACE = "http://schemas.openxmlformats.org/wordprocessingml/2006/main" # Word-specific element to relationship type mappings # Start with empty mapping - add specific cases as we discover them ELEMENT_RELATIONSHIP_TYPES = {} def validate(self): """Run all validation checks and return True if all pass.""" # Test 0: XML well-formedness if not self.validate_xml(): return False # Test 1: Namespace declarations all_valid = True if not self.validate_namespaces(): all_valid = False # Test 2: Unique IDs if not self.validate_unique_ids(): all_valid = False # Test 3: Relationship and file reference validation if not self.validate_file_references(): all_valid = False # Test 4: Content type declarations if not self.validate_content_types(): all_valid = False # Test 5: XSD schema validation if not self.validate_against_xsd(): all_valid = False # Test 6: Whitespace preservation if not self.validate_whitespace_preservation(): all_valid = False # Test 7: Deletion validation if not self.validate_deletions(): all_valid = False # Test 8: Insertion validation if not self.validate_insertions(): all_valid = False # Test 9: Relationship ID reference validation if not self.validate_all_relationship_ids(): all_valid = False # Count and compare paragraphs self.compare_paragraph_counts() return all_valid def validate_whitespace_preservation(self): """ Validate that w:t elements with whitespace have xml:space='preserve'. """ errors = [] for xml_file in self.xml_files: # Only check document.xml files if xml_file.name != "document.xml": continue try: root = lxml.etree.parse(str(xml_file)).getroot() # Find all w:t elements for elem in root.iter(f"{{{self.WORD_2006_NAMESPACE}}}t"): if elem.text: text = elem.text # Check if text starts or ends with whitespace if re.match(r"^\s.*", text) or re.match(r".*\s$", text): # Check if xml:space="preserve" attribute exists xml_space_attr = f"{{{self.XML_NAMESPACE}}}space" if ( xml_space_attr not in elem.attrib or elem.attrib[xml_space_attr] != "preserve" ): # Show a preview of the text text_preview = ( repr(text)[:50] + "..." if len(repr(text)) > 50 else repr(text) ) errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: " f"Line {elem.sourceline}: w:t element with whitespace missing xml:space='preserve': {text_preview}" ) except (lxml.etree.XMLSyntaxError, Exception) as e: errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}" ) if errors: print(f"FAILED - Found {len(errors)} whitespace preservation violations:") for error in errors: print(error) return False else: if self.verbose: print("PASSED - All whitespace is properly preserved") return True def validate_deletions(self): """ Validate that w:t elements are not within w:del elements. For some reason, XSD validation does not catch this, so we do it manually. """ errors = [] for xml_file in self.xml_files: # Only check document.xml files if xml_file.name != "document.xml": continue try: root = lxml.etree.parse(str(xml_file)).getroot() # Find all w:t elements that are descendants of w:del elements namespaces = {"w": self.WORD_2006_NAMESPACE} xpath_expression = ".//w:del//w:t" problematic_t_elements = root.xpath( xpath_expression, namespaces=namespaces ) for t_elem in problematic_t_elements: if t_elem.text: # Show a preview of the text text_preview = ( repr(t_elem.text)[:50] + "..." if len(repr(t_elem.text)) > 50 else repr(t_elem.text) ) errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: " f"Line {t_elem.sourceline}: <w:t> found within <w:del>: {text_preview}" ) except (lxml.etree.XMLSyntaxError, Exception) as e: errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}" ) if errors: print(f"FAILED - Found {len(errors)} deletion validation violations:") for error in errors: print(error) return False else: if self.verbose: print("PASSED - No w:t elements found within w:del elements") return True def count_paragraphs_in_unpacked(self): """Count the number of paragraphs in the unpacked document.""" count = 0 for xml_file in self.xml_files: # Only check document.xml files if xml_file.name != "document.xml": continue try: root = lxml.etree.parse(str(xml_file)).getroot() # Count all w:p elements paragraphs = root.findall(f".//{{{self.WORD_2006_NAMESPACE}}}p") count = len(paragraphs) except Exception as e: print(f"Error counting paragraphs in unpacked document: {e}") return count def count_paragraphs_in_original(self): """Count the number of paragraphs in the original docx file.""" count = 0 try: # Create temporary directory to unpack original with tempfile.TemporaryDirectory() as temp_dir: # Unpack original docx with zipfile.ZipFile(self.original_file, "r") as zip_ref: zip_ref.extractall(temp_dir) # Parse document.xml doc_xml_path = temp_dir + "/word/document.xml" root = lxml.etree.parse(doc_xml_path).getroot() # Count all w:p elements paragraphs = root.findall(f".//{{{self.WORD_2006_NAMESPACE}}}p") count = len(paragraphs) except Exception as e: print(f"Error counting paragraphs in original document: {e}") return count def validate_insertions(self): """ Validate that w:delText elements are not within w:ins elements. w:delText is only allowed in w:ins if nested within a w:del. """ errors = [] for xml_file in self.xml_files: if xml_file.name != "document.xml": continue try: root = lxml.etree.parse(str(xml_file)).getroot() namespaces = {"w": self.WORD_2006_NAMESPACE} # Find w:delText in w:ins that are NOT within w:del invalid_elements = root.xpath( ".//w:ins//w:delText[not(ancestor::w:del)]", namespaces=namespaces ) for elem in invalid_elements: text_preview = ( repr(elem.text or "")[:50] + "..." if len(repr(elem.text or "")) > 50 else repr(elem.text or "") ) errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: " f"Line {elem.sourceline}: <w:delText> within <w:ins>: {text_preview}" ) except (lxml.etree.XMLSyntaxError, Exception) as e: errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}" ) if errors: print(f"FAILED - Found {len(errors)} insertion validation violations:") for error in errors: print(error) return False else: if self.verbose: print("PASSED - No w:delText elements within w:ins elements") return True def compare_paragraph_counts(self): """Compare paragraph counts between original and new document.""" original_count = self.count_paragraphs_in_original() new_count = self.count_paragraphs_in_unpacked() diff = new_count - original_count diff_str = f"+{diff}" if diff > 0 else str(diff) print(f"\nParagraphs: {original_count} → {new_count} ({diff_str})") if __name__ == "__main__": raise RuntimeError("This module should not be run directly.")
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/docx-official/ooxml/scripts/validation/docx.py", "license": "MIT License", "lines": 222, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/document-processing/docx-official/ooxml/scripts/validation/pptx.py
""" Validator for PowerPoint presentation XML files against XSD schemas. """ import re from .base import BaseSchemaValidator class PPTXSchemaValidator(BaseSchemaValidator): """Validator for PowerPoint presentation XML files against XSD schemas.""" # PowerPoint presentation namespace PRESENTATIONML_NAMESPACE = ( "http://schemas.openxmlformats.org/presentationml/2006/main" ) # PowerPoint-specific element to relationship type mappings ELEMENT_RELATIONSHIP_TYPES = { "sldid": "slide", "sldmasterid": "slidemaster", "notesmasterid": "notesmaster", "sldlayoutid": "slidelayout", "themeid": "theme", "tablestyleid": "tablestyles", } def validate(self): """Run all validation checks and return True if all pass.""" # Test 0: XML well-formedness if not self.validate_xml(): return False # Test 1: Namespace declarations all_valid = True if not self.validate_namespaces(): all_valid = False # Test 2: Unique IDs if not self.validate_unique_ids(): all_valid = False # Test 3: UUID ID validation if not self.validate_uuid_ids(): all_valid = False # Test 4: Relationship and file reference validation if not self.validate_file_references(): all_valid = False # Test 5: Slide layout ID validation if not self.validate_slide_layout_ids(): all_valid = False # Test 6: Content type declarations if not self.validate_content_types(): all_valid = False # Test 7: XSD schema validation if not self.validate_against_xsd(): all_valid = False # Test 8: Notes slide reference validation if not self.validate_notes_slide_references(): all_valid = False # Test 9: Relationship ID reference validation if not self.validate_all_relationship_ids(): all_valid = False # Test 10: Duplicate slide layout references validation if not self.validate_no_duplicate_slide_layouts(): all_valid = False return all_valid def validate_uuid_ids(self): """Validate that ID attributes that look like UUIDs contain only hex values.""" import lxml.etree errors = [] # UUID pattern: 8-4-4-4-12 hex digits with optional braces/hyphens uuid_pattern = re.compile( r"^[\{\(]?[0-9A-Fa-f]{8}-?[0-9A-Fa-f]{4}-?[0-9A-Fa-f]{4}-?[0-9A-Fa-f]{4}-?[0-9A-Fa-f]{12}[\}\)]?$" ) for xml_file in self.xml_files: try: root = lxml.etree.parse(str(xml_file)).getroot() # Check all elements for ID attributes for elem in root.iter(): for attr, value in elem.attrib.items(): # Check if this is an ID attribute attr_name = attr.split("}")[-1].lower() if attr_name == "id" or attr_name.endswith("id"): # Check if value looks like a UUID (has the right length and pattern structure) if self._looks_like_uuid(value): # Validate that it contains only hex characters in the right positions if not uuid_pattern.match(value): errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: " f"Line {elem.sourceline}: ID '{value}' appears to be a UUID but contains invalid hex characters" ) except (lxml.etree.XMLSyntaxError, Exception) as e: errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}" ) if errors: print(f"FAILED - Found {len(errors)} UUID ID validation errors:") for error in errors: print(error) return False else: if self.verbose: print("PASSED - All UUID-like IDs contain valid hex values") return True def _looks_like_uuid(self, value): """Check if a value has the general structure of a UUID.""" # Remove common UUID delimiters clean_value = value.strip("{}()").replace("-", "") # Check if it's 32 hex-like characters (could include invalid hex chars) return len(clean_value) == 32 and all(c.isalnum() for c in clean_value) def validate_slide_layout_ids(self): """Validate that sldLayoutId elements in slide masters reference valid slide layouts.""" import lxml.etree errors = [] # Find all slide master files slide_masters = list(self.unpacked_dir.glob("ppt/slideMasters/*.xml")) if not slide_masters: if self.verbose: print("PASSED - No slide masters found") return True for slide_master in slide_masters: try: # Parse the slide master file root = lxml.etree.parse(str(slide_master)).getroot() # Find the corresponding _rels file for this slide master rels_file = slide_master.parent / "_rels" / f"{slide_master.name}.rels" if not rels_file.exists(): errors.append( f" {slide_master.relative_to(self.unpacked_dir)}: " f"Missing relationships file: {rels_file.relative_to(self.unpacked_dir)}" ) continue # Parse the relationships file rels_root = lxml.etree.parse(str(rels_file)).getroot() # Build a set of valid relationship IDs that point to slide layouts valid_layout_rids = set() for rel in rels_root.findall( f".//{{{self.PACKAGE_RELATIONSHIPS_NAMESPACE}}}Relationship" ): rel_type = rel.get("Type", "") if "slideLayout" in rel_type: valid_layout_rids.add(rel.get("Id")) # Find all sldLayoutId elements in the slide master for sld_layout_id in root.findall( f".//{{{self.PRESENTATIONML_NAMESPACE}}}sldLayoutId" ): r_id = sld_layout_id.get( f"{{{self.OFFICE_RELATIONSHIPS_NAMESPACE}}}id" ) layout_id = sld_layout_id.get("id") if r_id and r_id not in valid_layout_rids: errors.append( f" {slide_master.relative_to(self.unpacked_dir)}: " f"Line {sld_layout_id.sourceline}: sldLayoutId with id='{layout_id}' " f"references r:id='{r_id}' which is not found in slide layout relationships" ) except (lxml.etree.XMLSyntaxError, Exception) as e: errors.append( f" {slide_master.relative_to(self.unpacked_dir)}: Error: {e}" ) if errors: print(f"FAILED - Found {len(errors)} slide layout ID validation errors:") for error in errors: print(error) print( "Remove invalid references or add missing slide layouts to the relationships file." ) return False else: if self.verbose: print("PASSED - All slide layout IDs reference valid slide layouts") return True def validate_no_duplicate_slide_layouts(self): """Validate that each slide has exactly one slideLayout reference.""" import lxml.etree errors = [] slide_rels_files = list(self.unpacked_dir.glob("ppt/slides/_rels/*.xml.rels")) for rels_file in slide_rels_files: try: root = lxml.etree.parse(str(rels_file)).getroot() # Find all slideLayout relationships layout_rels = [ rel for rel in root.findall( f".//{{{self.PACKAGE_RELATIONSHIPS_NAMESPACE}}}Relationship" ) if "slideLayout" in rel.get("Type", "") ] if len(layout_rels) > 1: errors.append( f" {rels_file.relative_to(self.unpacked_dir)}: has {len(layout_rels)} slideLayout references" ) except Exception as e: errors.append( f" {rels_file.relative_to(self.unpacked_dir)}: Error: {e}" ) if errors: print("FAILED - Found slides with duplicate slideLayout references:") for error in errors: print(error) return False else: if self.verbose: print("PASSED - All slides have exactly one slideLayout reference") return True def validate_notes_slide_references(self): """Validate that each notesSlide file is referenced by only one slide.""" import lxml.etree errors = [] notes_slide_references = {} # Track which slides reference each notesSlide # Find all slide relationship files slide_rels_files = list(self.unpacked_dir.glob("ppt/slides/_rels/*.xml.rels")) if not slide_rels_files: if self.verbose: print("PASSED - No slide relationship files found") return True for rels_file in slide_rels_files: try: # Parse the relationships file root = lxml.etree.parse(str(rels_file)).getroot() # Find all notesSlide relationships for rel in root.findall( f".//{{{self.PACKAGE_RELATIONSHIPS_NAMESPACE}}}Relationship" ): rel_type = rel.get("Type", "") if "notesSlide" in rel_type: target = rel.get("Target", "") if target: # Normalize the target path to handle relative paths normalized_target = target.replace("../", "") # Track which slide references this notesSlide slide_name = rels_file.stem.replace( ".xml", "" ) # e.g., "slide1" if normalized_target not in notes_slide_references: notes_slide_references[normalized_target] = [] notes_slide_references[normalized_target].append( (slide_name, rels_file) ) except (lxml.etree.XMLSyntaxError, Exception) as e: errors.append( f" {rels_file.relative_to(self.unpacked_dir)}: Error: {e}" ) # Check for duplicate references for target, references in notes_slide_references.items(): if len(references) > 1: slide_names = [ref[0] for ref in references] errors.append( f" Notes slide '{target}' is referenced by multiple slides: {', '.join(slide_names)}" ) for slide_name, rels_file in references: errors.append(f" - {rels_file.relative_to(self.unpacked_dir)}") if errors: print( f"FAILED - Found {len([e for e in errors if not e.startswith(' ')])} notes slide reference validation errors:" ) for error in errors: print(error) print("Each slide may optionally have its own slide file.") return False else: if self.verbose: print("PASSED - All notes slide references are unique") return True if __name__ == "__main__": raise RuntimeError("This module should not be run directly.")
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/docx-official/ooxml/scripts/validation/pptx.py", "license": "MIT License", "lines": 257, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/document-processing/docx-official/ooxml/scripts/validation/redlining.py
""" Validator for tracked changes in Word documents. """ import subprocess import tempfile import zipfile from pathlib import Path class RedliningValidator: """Validator for tracked changes in Word documents.""" def __init__(self, unpacked_dir, original_docx, verbose=False): self.unpacked_dir = Path(unpacked_dir) self.original_docx = Path(original_docx) self.verbose = verbose self.namespaces = { "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main" } def validate(self): """Main validation method that returns True if valid, False otherwise.""" # Verify unpacked directory exists and has correct structure modified_file = self.unpacked_dir / "word" / "document.xml" if not modified_file.exists(): print(f"FAILED - Modified document.xml not found at {modified_file}") return False # First, check if there are any tracked changes by Claude to validate try: import xml.etree.ElementTree as ET tree = ET.parse(modified_file) root = tree.getroot() # Check for w:del or w:ins tags authored by Claude del_elements = root.findall(".//w:del", self.namespaces) ins_elements = root.findall(".//w:ins", self.namespaces) # Filter to only include changes by Claude claude_del_elements = [ elem for elem in del_elements if elem.get(f"{{{self.namespaces['w']}}}author") == "Claude" ] claude_ins_elements = [ elem for elem in ins_elements if elem.get(f"{{{self.namespaces['w']}}}author") == "Claude" ] # Redlining validation is only needed if tracked changes by Claude have been used. if not claude_del_elements and not claude_ins_elements: if self.verbose: print("PASSED - No tracked changes by Claude found.") return True except Exception: # If we can't parse the XML, continue with full validation pass # Create temporary directory for unpacking original docx with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) # Unpack original docx try: with zipfile.ZipFile(self.original_docx, "r") as zip_ref: zip_ref.extractall(temp_path) except Exception as e: print(f"FAILED - Error unpacking original docx: {e}") return False original_file = temp_path / "word" / "document.xml" if not original_file.exists(): print( f"FAILED - Original document.xml not found in {self.original_docx}" ) return False # Parse both XML files using xml.etree.ElementTree for redlining validation try: import xml.etree.ElementTree as ET modified_tree = ET.parse(modified_file) modified_root = modified_tree.getroot() original_tree = ET.parse(original_file) original_root = original_tree.getroot() except ET.ParseError as e: print(f"FAILED - Error parsing XML files: {e}") return False # Remove Claude's tracked changes from both documents self._remove_claude_tracked_changes(original_root) self._remove_claude_tracked_changes(modified_root) # Extract and compare text content modified_text = self._extract_text_content(modified_root) original_text = self._extract_text_content(original_root) if modified_text != original_text: # Show detailed character-level differences for each paragraph error_message = self._generate_detailed_diff( original_text, modified_text ) print(error_message) return False if self.verbose: print("PASSED - All changes by Claude are properly tracked") return True def _generate_detailed_diff(self, original_text, modified_text): """Generate detailed word-level differences using git word diff.""" error_parts = [ "FAILED - Document text doesn't match after removing Claude's tracked changes", "", "Likely causes:", " 1. Modified text inside another author's <w:ins> or <w:del> tags", " 2. Made edits without proper tracked changes", " 3. Didn't nest <w:del> inside <w:ins> when deleting another's insertion", "", "For pre-redlined documents, use correct patterns:", " - To reject another's INSERTION: Nest <w:del> inside their <w:ins>", " - To restore another's DELETION: Add new <w:ins> AFTER their <w:del>", "", ] # Show git word diff git_diff = self._get_git_word_diff(original_text, modified_text) if git_diff: error_parts.extend(["Differences:", "============", git_diff]) else: error_parts.append("Unable to generate word diff (git not available)") return "\n".join(error_parts) def _get_git_word_diff(self, original_text, modified_text): """Generate word diff using git with character-level precision.""" try: with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) # Create two files original_file = temp_path / "original.txt" modified_file = temp_path / "modified.txt" original_file.write_text(original_text, encoding="utf-8") modified_file.write_text(modified_text, encoding="utf-8") # Try character-level diff first for precise differences result = subprocess.run( [ "git", "diff", "--word-diff=plain", "--word-diff-regex=.", # Character-by-character diff "-U0", # Zero lines of context - show only changed lines "--no-index", str(original_file), str(modified_file), ], capture_output=True, text=True, ) if result.stdout.strip(): # Clean up the output - remove git diff header lines lines = result.stdout.split("\n") # Skip the header lines (diff --git, index, +++, ---, @@) content_lines = [] in_content = False for line in lines: if line.startswith("@@"): in_content = True continue if in_content and line.strip(): content_lines.append(line) if content_lines: return "\n".join(content_lines) # Fallback to word-level diff if character-level is too verbose result = subprocess.run( [ "git", "diff", "--word-diff=plain", "-U0", # Zero lines of context "--no-index", str(original_file), str(modified_file), ], capture_output=True, text=True, ) if result.stdout.strip(): lines = result.stdout.split("\n") content_lines = [] in_content = False for line in lines: if line.startswith("@@"): in_content = True continue if in_content and line.strip(): content_lines.append(line) return "\n".join(content_lines) except (subprocess.CalledProcessError, FileNotFoundError, Exception): # Git not available or other error, return None to use fallback pass return None def _remove_claude_tracked_changes(self, root): """Remove tracked changes authored by Claude from the XML root.""" ins_tag = f"{{{self.namespaces['w']}}}ins" del_tag = f"{{{self.namespaces['w']}}}del" author_attr = f"{{{self.namespaces['w']}}}author" # Remove w:ins elements for parent in root.iter(): to_remove = [] for child in parent: if child.tag == ins_tag and child.get(author_attr) == "Claude": to_remove.append(child) for elem in to_remove: parent.remove(elem) # Unwrap content in w:del elements where author is "Claude" deltext_tag = f"{{{self.namespaces['w']}}}delText" t_tag = f"{{{self.namespaces['w']}}}t" for parent in root.iter(): to_process = [] for child in parent: if child.tag == del_tag and child.get(author_attr) == "Claude": to_process.append((child, list(parent).index(child))) # Process in reverse order to maintain indices for del_elem, del_index in reversed(to_process): # Convert w:delText to w:t before moving for elem in del_elem.iter(): if elem.tag == deltext_tag: elem.tag = t_tag # Move all children of w:del to its parent before removing w:del for child in reversed(list(del_elem)): parent.insert(del_index, child) parent.remove(del_elem) def _extract_text_content(self, root): """Extract text content from Word XML, preserving paragraph structure. Empty paragraphs are skipped to avoid false positives when tracked insertions add only structural elements without text content. """ p_tag = f"{{{self.namespaces['w']}}}p" t_tag = f"{{{self.namespaces['w']}}}t" paragraphs = [] for p_elem in root.findall(f".//{p_tag}"): # Get all text elements within this paragraph text_parts = [] for t_elem in p_elem.findall(f".//{t_tag}"): if t_elem.text: text_parts.append(t_elem.text) paragraph_text = "".join(text_parts) # Skip empty paragraphs - they don't affect content validation if paragraph_text: paragraphs.append(paragraph_text) return "\n".join(paragraphs) if __name__ == "__main__": raise RuntimeError("This module should not be run directly.")
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/docx-official/ooxml/scripts/validation/redlining.py", "license": "MIT License", "lines": 234, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/document-processing/docx-official/scripts/document.py
#!/usr/bin/env python3 """ Library for working with Word documents: comments, tracked changes, and editing. Usage: from skills.docx.scripts.document import Document # Initialize doc = Document('workspace/unpacked') doc = Document('workspace/unpacked', author="John Doe", initials="JD") # Find nodes node = doc["word/document.xml"].get_node(tag="w:del", attrs={"w:id": "1"}) node = doc["word/document.xml"].get_node(tag="w:p", line_number=10) # Add comments doc.add_comment(start=node, end=node, text="Comment text") doc.reply_to_comment(parent_comment_id=0, text="Reply text") # Suggest tracked changes doc["word/document.xml"].suggest_deletion(node) # Delete content doc["word/document.xml"].revert_insertion(ins_node) # Reject insertion doc["word/document.xml"].revert_deletion(del_node) # Reject deletion # Save doc.save() """ import html import random import shutil import tempfile from datetime import datetime, timezone from pathlib import Path from defusedxml import minidom from ooxml.scripts.pack import pack_document from ooxml.scripts.validation.docx import DOCXSchemaValidator from ooxml.scripts.validation.redlining import RedliningValidator from .utilities import XMLEditor # Path to template files TEMPLATE_DIR = Path(__file__).parent / "templates" class DocxXMLEditor(XMLEditor): """XMLEditor that automatically applies RSID, author, and date to new elements. Automatically adds attributes to elements that support them when inserting new content: - w:rsidR, w:rsidRDefault, w:rsidP (for w:p and w:r elements) - w:author and w:date (for w:ins, w:del, w:comment elements) - w:id (for w:ins and w:del elements) Attributes: dom (defusedxml.minidom.Document): The DOM document for direct manipulation """ def __init__( self, xml_path, rsid: str, author: str = "Claude", initials: str = "C" ): """Initialize with required RSID and optional author. Args: xml_path: Path to XML file to edit rsid: RSID to automatically apply to new elements author: Author name for tracked changes and comments (default: "Claude") initials: Author initials (default: "C") """ super().__init__(xml_path) self.rsid = rsid self.author = author self.initials = initials def _get_next_change_id(self): """Get the next available change ID by checking all tracked change elements.""" max_id = -1 for tag in ("w:ins", "w:del"): elements = self.dom.getElementsByTagName(tag) for elem in elements: change_id = elem.getAttribute("w:id") if change_id: try: max_id = max(max_id, int(change_id)) except ValueError: pass return max_id + 1 def _ensure_w16du_namespace(self): """Ensure w16du namespace is declared on the root element.""" root = self.dom.documentElement if not root.hasAttribute("xmlns:w16du"): # type: ignore root.setAttribute( # type: ignore "xmlns:w16du", "http://schemas.microsoft.com/office/word/2023/wordml/word16du", ) def _ensure_w16cex_namespace(self): """Ensure w16cex namespace is declared on the root element.""" root = self.dom.documentElement if not root.hasAttribute("xmlns:w16cex"): # type: ignore root.setAttribute( # type: ignore "xmlns:w16cex", "http://schemas.microsoft.com/office/word/2018/wordml/cex", ) def _ensure_w14_namespace(self): """Ensure w14 namespace is declared on the root element.""" root = self.dom.documentElement if not root.hasAttribute("xmlns:w14"): # type: ignore root.setAttribute( # type: ignore "xmlns:w14", "http://schemas.microsoft.com/office/word/2010/wordml", ) def _inject_attributes_to_nodes(self, nodes): """Inject RSID, author, and date attributes into DOM nodes where applicable. Adds attributes to elements that support them: - w:r: gets w:rsidR (or w:rsidDel if inside w:del) - w:p: gets w:rsidR, w:rsidRDefault, w:rsidP, w14:paraId, w14:textId - w:t: gets xml:space="preserve" if text has leading/trailing whitespace - w:ins, w:del: get w:id, w:author, w:date, w16du:dateUtc - w:comment: gets w:author, w:date, w:initials - w16cex:commentExtensible: gets w16cex:dateUtc Args: nodes: List of DOM nodes to process """ from datetime import datetime, timezone timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") def is_inside_deletion(elem): """Check if element is inside a w:del element.""" parent = elem.parentNode while parent: if parent.nodeType == parent.ELEMENT_NODE and parent.tagName == "w:del": return True parent = parent.parentNode return False def add_rsid_to_p(elem): if not elem.hasAttribute("w:rsidR"): elem.setAttribute("w:rsidR", self.rsid) if not elem.hasAttribute("w:rsidRDefault"): elem.setAttribute("w:rsidRDefault", self.rsid) if not elem.hasAttribute("w:rsidP"): elem.setAttribute("w:rsidP", self.rsid) # Add w14:paraId and w14:textId if not present if not elem.hasAttribute("w14:paraId"): self._ensure_w14_namespace() elem.setAttribute("w14:paraId", _generate_hex_id()) if not elem.hasAttribute("w14:textId"): self._ensure_w14_namespace() elem.setAttribute("w14:textId", _generate_hex_id()) def add_rsid_to_r(elem): # Use w:rsidDel for <w:r> inside <w:del>, otherwise w:rsidR if is_inside_deletion(elem): if not elem.hasAttribute("w:rsidDel"): elem.setAttribute("w:rsidDel", self.rsid) else: if not elem.hasAttribute("w:rsidR"): elem.setAttribute("w:rsidR", self.rsid) def add_tracked_change_attrs(elem): # Auto-assign w:id if not present if not elem.hasAttribute("w:id"): elem.setAttribute("w:id", str(self._get_next_change_id())) if not elem.hasAttribute("w:author"): elem.setAttribute("w:author", self.author) if not elem.hasAttribute("w:date"): elem.setAttribute("w:date", timestamp) # Add w16du:dateUtc for tracked changes (same as w:date since we generate UTC timestamps) if elem.tagName in ("w:ins", "w:del") and not elem.hasAttribute( "w16du:dateUtc" ): self._ensure_w16du_namespace() elem.setAttribute("w16du:dateUtc", timestamp) def add_comment_attrs(elem): if not elem.hasAttribute("w:author"): elem.setAttribute("w:author", self.author) if not elem.hasAttribute("w:date"): elem.setAttribute("w:date", timestamp) if not elem.hasAttribute("w:initials"): elem.setAttribute("w:initials", self.initials) def add_comment_extensible_date(elem): # Add w16cex:dateUtc for comment extensible elements if not elem.hasAttribute("w16cex:dateUtc"): self._ensure_w16cex_namespace() elem.setAttribute("w16cex:dateUtc", timestamp) def add_xml_space_to_t(elem): # Add xml:space="preserve" to w:t if text has leading/trailing whitespace if ( elem.firstChild and elem.firstChild.nodeType == elem.firstChild.TEXT_NODE ): text = elem.firstChild.data if text and (text[0].isspace() or text[-1].isspace()): if not elem.hasAttribute("xml:space"): elem.setAttribute("xml:space", "preserve") for node in nodes: if node.nodeType != node.ELEMENT_NODE: continue # Handle the node itself if node.tagName == "w:p": add_rsid_to_p(node) elif node.tagName == "w:r": add_rsid_to_r(node) elif node.tagName == "w:t": add_xml_space_to_t(node) elif node.tagName in ("w:ins", "w:del"): add_tracked_change_attrs(node) elif node.tagName == "w:comment": add_comment_attrs(node) elif node.tagName == "w16cex:commentExtensible": add_comment_extensible_date(node) # Process descendants (getElementsByTagName doesn't return the element itself) for elem in node.getElementsByTagName("w:p"): add_rsid_to_p(elem) for elem in node.getElementsByTagName("w:r"): add_rsid_to_r(elem) for elem in node.getElementsByTagName("w:t"): add_xml_space_to_t(elem) for tag in ("w:ins", "w:del"): for elem in node.getElementsByTagName(tag): add_tracked_change_attrs(elem) for elem in node.getElementsByTagName("w:comment"): add_comment_attrs(elem) for elem in node.getElementsByTagName("w16cex:commentExtensible"): add_comment_extensible_date(elem) def replace_node(self, elem, new_content): """Replace node with automatic attribute injection.""" nodes = super().replace_node(elem, new_content) self._inject_attributes_to_nodes(nodes) return nodes def insert_after(self, elem, xml_content): """Insert after with automatic attribute injection.""" nodes = super().insert_after(elem, xml_content) self._inject_attributes_to_nodes(nodes) return nodes def insert_before(self, elem, xml_content): """Insert before with automatic attribute injection.""" nodes = super().insert_before(elem, xml_content) self._inject_attributes_to_nodes(nodes) return nodes def append_to(self, elem, xml_content): """Append to with automatic attribute injection.""" nodes = super().append_to(elem, xml_content) self._inject_attributes_to_nodes(nodes) return nodes def revert_insertion(self, elem): """Reject an insertion by wrapping its content in a deletion. Wraps all runs inside w:ins in w:del, converting w:t to w:delText. Can process a single w:ins element or a container element with multiple w:ins. Args: elem: Element to process (w:ins, w:p, w:body, etc.) Returns: list: List containing the processed element(s) Raises: ValueError: If the element contains no w:ins elements Example: # Reject a single insertion ins = doc["word/document.xml"].get_node(tag="w:ins", attrs={"w:id": "5"}) doc["word/document.xml"].revert_insertion(ins) # Reject all insertions in a paragraph para = doc["word/document.xml"].get_node(tag="w:p", line_number=42) doc["word/document.xml"].revert_insertion(para) """ # Collect insertions ins_elements = [] if elem.tagName == "w:ins": ins_elements.append(elem) else: ins_elements.extend(elem.getElementsByTagName("w:ins")) # Validate that there are insertions to reject if not ins_elements: raise ValueError( f"revert_insertion requires w:ins elements. " f"The provided element <{elem.tagName}> contains no insertions. " ) # Process all insertions - wrap all children in w:del for ins_elem in ins_elements: runs = list(ins_elem.getElementsByTagName("w:r")) if not runs: continue # Create deletion wrapper del_wrapper = self.dom.createElement("w:del") # Process each run for run in runs: # Convert w:t → w:delText and w:rsidR → w:rsidDel if run.hasAttribute("w:rsidR"): run.setAttribute("w:rsidDel", run.getAttribute("w:rsidR")) run.removeAttribute("w:rsidR") elif not run.hasAttribute("w:rsidDel"): run.setAttribute("w:rsidDel", self.rsid) for t_elem in list(run.getElementsByTagName("w:t")): del_text = self.dom.createElement("w:delText") # Copy ALL child nodes (not just firstChild) to handle entities while t_elem.firstChild: del_text.appendChild(t_elem.firstChild) for i in range(t_elem.attributes.length): attr = t_elem.attributes.item(i) del_text.setAttribute(attr.name, attr.value) t_elem.parentNode.replaceChild(del_text, t_elem) # Move all children from ins to del wrapper while ins_elem.firstChild: del_wrapper.appendChild(ins_elem.firstChild) # Add del wrapper back to ins ins_elem.appendChild(del_wrapper) # Inject attributes to the deletion wrapper self._inject_attributes_to_nodes([del_wrapper]) return [elem] def revert_deletion(self, elem): """Reject a deletion by re-inserting the deleted content. Creates w:ins elements after each w:del, copying deleted content and converting w:delText back to w:t. Can process a single w:del element or a container element with multiple w:del. Args: elem: Element to process (w:del, w:p, w:body, etc.) Returns: list: If elem is w:del, returns [elem, new_ins]. Otherwise returns [elem]. Raises: ValueError: If the element contains no w:del elements Example: # Reject a single deletion - returns [w:del, w:ins] del_elem = doc["word/document.xml"].get_node(tag="w:del", attrs={"w:id": "3"}) nodes = doc["word/document.xml"].revert_deletion(del_elem) # Reject all deletions in a paragraph - returns [para] para = doc["word/document.xml"].get_node(tag="w:p", line_number=42) nodes = doc["word/document.xml"].revert_deletion(para) """ # Collect deletions FIRST - before we modify the DOM del_elements = [] is_single_del = elem.tagName == "w:del" if is_single_del: del_elements.append(elem) else: del_elements.extend(elem.getElementsByTagName("w:del")) # Validate that there are deletions to reject if not del_elements: raise ValueError( f"revert_deletion requires w:del elements. " f"The provided element <{elem.tagName}> contains no deletions. " ) # Track created insertion (only relevant if elem is a single w:del) created_insertion = None # Process all deletions - create insertions that copy the deleted content for del_elem in del_elements: # Clone the deleted runs and convert them to insertions runs = list(del_elem.getElementsByTagName("w:r")) if not runs: continue # Create insertion wrapper ins_elem = self.dom.createElement("w:ins") for run in runs: # Clone the run new_run = run.cloneNode(True) # Convert w:delText → w:t for del_text in list(new_run.getElementsByTagName("w:delText")): t_elem = self.dom.createElement("w:t") # Copy ALL child nodes (not just firstChild) to handle entities while del_text.firstChild: t_elem.appendChild(del_text.firstChild) for i in range(del_text.attributes.length): attr = del_text.attributes.item(i) t_elem.setAttribute(attr.name, attr.value) del_text.parentNode.replaceChild(t_elem, del_text) # Update run attributes: w:rsidDel → w:rsidR if new_run.hasAttribute("w:rsidDel"): new_run.setAttribute("w:rsidR", new_run.getAttribute("w:rsidDel")) new_run.removeAttribute("w:rsidDel") elif not new_run.hasAttribute("w:rsidR"): new_run.setAttribute("w:rsidR", self.rsid) ins_elem.appendChild(new_run) # Insert the new insertion after the deletion nodes = self.insert_after(del_elem, ins_elem.toxml()) # If processing a single w:del, track the created insertion if is_single_del and nodes: created_insertion = nodes[0] # Return based on input type if is_single_del and created_insertion: return [elem, created_insertion] else: return [elem] @staticmethod def suggest_paragraph(xml_content: str) -> str: """Transform paragraph XML to add tracked change wrapping for insertion. Wraps runs in <w:ins> and adds <w:ins/> to w:rPr in w:pPr for numbered lists. Args: xml_content: XML string containing a <w:p> element Returns: str: Transformed XML with tracked change wrapping """ wrapper = f'<root xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{xml_content}</root>' doc = minidom.parseString(wrapper) para = doc.getElementsByTagName("w:p")[0] # Ensure w:pPr exists pPr_list = para.getElementsByTagName("w:pPr") if not pPr_list: pPr = doc.createElement("w:pPr") para.insertBefore( pPr, para.firstChild ) if para.firstChild else para.appendChild(pPr) else: pPr = pPr_list[0] # Ensure w:rPr exists in w:pPr rPr_list = pPr.getElementsByTagName("w:rPr") if not rPr_list: rPr = doc.createElement("w:rPr") pPr.appendChild(rPr) else: rPr = rPr_list[0] # Add <w:ins/> to w:rPr ins_marker = doc.createElement("w:ins") rPr.insertBefore( ins_marker, rPr.firstChild ) if rPr.firstChild else rPr.appendChild(ins_marker) # Wrap all non-pPr children in <w:ins> ins_wrapper = doc.createElement("w:ins") for child in [c for c in para.childNodes if c.nodeName != "w:pPr"]: para.removeChild(child) ins_wrapper.appendChild(child) para.appendChild(ins_wrapper) return para.toxml() def suggest_deletion(self, elem): """Mark a w:r or w:p element as deleted with tracked changes (in-place DOM manipulation). For w:r: wraps in <w:del>, converts <w:t> to <w:delText>, preserves w:rPr For w:p (regular): wraps content in <w:del>, converts <w:t> to <w:delText> For w:p (numbered list): adds <w:del/> to w:rPr in w:pPr, wraps content in <w:del> Args: elem: A w:r or w:p DOM element without existing tracked changes Returns: Element: The modified element Raises: ValueError: If element has existing tracked changes or invalid structure """ if elem.nodeName == "w:r": # Check for existing w:delText if elem.getElementsByTagName("w:delText"): raise ValueError("w:r element already contains w:delText") # Convert w:t → w:delText for t_elem in list(elem.getElementsByTagName("w:t")): del_text = self.dom.createElement("w:delText") # Copy ALL child nodes (not just firstChild) to handle entities while t_elem.firstChild: del_text.appendChild(t_elem.firstChild) # Preserve attributes like xml:space for i in range(t_elem.attributes.length): attr = t_elem.attributes.item(i) del_text.setAttribute(attr.name, attr.value) t_elem.parentNode.replaceChild(del_text, t_elem) # Update run attributes: w:rsidR → w:rsidDel if elem.hasAttribute("w:rsidR"): elem.setAttribute("w:rsidDel", elem.getAttribute("w:rsidR")) elem.removeAttribute("w:rsidR") elif not elem.hasAttribute("w:rsidDel"): elem.setAttribute("w:rsidDel", self.rsid) # Wrap in w:del del_wrapper = self.dom.createElement("w:del") parent = elem.parentNode parent.insertBefore(del_wrapper, elem) parent.removeChild(elem) del_wrapper.appendChild(elem) # Inject attributes to the deletion wrapper self._inject_attributes_to_nodes([del_wrapper]) return del_wrapper elif elem.nodeName == "w:p": # Check for existing tracked changes if elem.getElementsByTagName("w:ins") or elem.getElementsByTagName("w:del"): raise ValueError("w:p element already contains tracked changes") # Check if it's a numbered list item pPr_list = elem.getElementsByTagName("w:pPr") is_numbered = pPr_list and pPr_list[0].getElementsByTagName("w:numPr") if is_numbered: # Add <w:del/> to w:rPr in w:pPr pPr = pPr_list[0] rPr_list = pPr.getElementsByTagName("w:rPr") if not rPr_list: rPr = self.dom.createElement("w:rPr") pPr.appendChild(rPr) else: rPr = rPr_list[0] # Add <w:del/> marker del_marker = self.dom.createElement("w:del") rPr.insertBefore( del_marker, rPr.firstChild ) if rPr.firstChild else rPr.appendChild(del_marker) # Convert w:t → w:delText in all runs for t_elem in list(elem.getElementsByTagName("w:t")): del_text = self.dom.createElement("w:delText") # Copy ALL child nodes (not just firstChild) to handle entities while t_elem.firstChild: del_text.appendChild(t_elem.firstChild) # Preserve attributes like xml:space for i in range(t_elem.attributes.length): attr = t_elem.attributes.item(i) del_text.setAttribute(attr.name, attr.value) t_elem.parentNode.replaceChild(del_text, t_elem) # Update run attributes: w:rsidR → w:rsidDel for run in elem.getElementsByTagName("w:r"): if run.hasAttribute("w:rsidR"): run.setAttribute("w:rsidDel", run.getAttribute("w:rsidR")) run.removeAttribute("w:rsidR") elif not run.hasAttribute("w:rsidDel"): run.setAttribute("w:rsidDel", self.rsid) # Wrap all non-pPr children in <w:del> del_wrapper = self.dom.createElement("w:del") for child in [c for c in elem.childNodes if c.nodeName != "w:pPr"]: elem.removeChild(child) del_wrapper.appendChild(child) elem.appendChild(del_wrapper) # Inject attributes to the deletion wrapper self._inject_attributes_to_nodes([del_wrapper]) return elem else: raise ValueError(f"Element must be w:r or w:p, got {elem.nodeName}") def _generate_hex_id() -> str: """Generate random 8-character hex ID for para/durable IDs. Values are constrained to be less than 0x7FFFFFFF per OOXML spec: - paraId must be < 0x80000000 - durableId must be < 0x7FFFFFFF We use the stricter constraint (0x7FFFFFFF) for both. """ return f"{random.randint(1, 0x7FFFFFFE):08X}" def _generate_rsid() -> str: """Generate random 8-character hex RSID.""" return "".join(random.choices("0123456789ABCDEF", k=8)) class Document: """Manages comments in unpacked Word documents.""" def __init__( self, unpacked_dir, rsid=None, track_revisions=False, author="Claude", initials="C", ): """ Initialize with path to unpacked Word document directory. Automatically sets up comment infrastructure (people.xml, RSIDs). Args: unpacked_dir: Path to unpacked DOCX directory (must contain word/ subdirectory) rsid: Optional RSID to use for all comment elements. If not provided, one will be generated. track_revisions: If True, enables track revisions in settings.xml (default: False) author: Default author name for comments (default: "Claude") initials: Default author initials for comments (default: "C") """ self.original_path = Path(unpacked_dir) if not self.original_path.exists() or not self.original_path.is_dir(): raise ValueError(f"Directory not found: {unpacked_dir}") # Create temporary directory with subdirectories for unpacked content and baseline self.temp_dir = tempfile.mkdtemp(prefix="docx_") self.unpacked_path = Path(self.temp_dir) / "unpacked" shutil.copytree(self.original_path, self.unpacked_path) # Pack original directory into temporary .docx for validation baseline (outside unpacked dir) self.original_docx = Path(self.temp_dir) / "original.docx" pack_document(self.original_path, self.original_docx, validate=False) self.word_path = self.unpacked_path / "word" # Generate RSID if not provided self.rsid = rsid if rsid else _generate_rsid() print(f"Using RSID: {self.rsid}") # Set default author and initials self.author = author self.initials = initials # Cache for lazy-loaded editors self._editors = {} # Comment file paths self.comments_path = self.word_path / "comments.xml" self.comments_extended_path = self.word_path / "commentsExtended.xml" self.comments_ids_path = self.word_path / "commentsIds.xml" self.comments_extensible_path = self.word_path / "commentsExtensible.xml" # Load existing comments and determine next ID (before setup modifies files) self.existing_comments = self._load_existing_comments() self.next_comment_id = self._get_next_comment_id() # Convenient access to document.xml editor (semi-private) self._document = self["word/document.xml"] # Setup tracked changes infrastructure self._setup_tracking(track_revisions=track_revisions) # Add author to people.xml self._add_author_to_people(author) def __getitem__(self, xml_path: str) -> DocxXMLEditor: """ Get or create a DocxXMLEditor for the specified XML file. Enables lazy-loaded editors with bracket notation: node = doc["word/document.xml"].get_node(tag="w:p", line_number=42) Args: xml_path: Relative path to XML file (e.g., "word/document.xml", "word/comments.xml") Returns: DocxXMLEditor instance for the specified file Raises: ValueError: If the file does not exist Example: # Get node from document.xml node = doc["word/document.xml"].get_node(tag="w:del", attrs={"w:id": "1"}) # Get node from comments.xml comment = doc["word/comments.xml"].get_node(tag="w:comment", attrs={"w:id": "0"}) """ if xml_path not in self._editors: file_path = self.unpacked_path / xml_path if not file_path.exists(): raise ValueError(f"XML file not found: {xml_path}") # Use DocxXMLEditor with RSID, author, and initials for all editors self._editors[xml_path] = DocxXMLEditor( file_path, rsid=self.rsid, author=self.author, initials=self.initials ) return self._editors[xml_path] def add_comment(self, start, end, text: str) -> int: """ Add a comment spanning from one element to another. Args: start: DOM element for the starting point end: DOM element for the ending point text: Comment content Returns: The comment ID that was created Example: start_node = cm.get_document_node(tag="w:del", id="1") end_node = cm.get_document_node(tag="w:ins", id="2") cm.add_comment(start=start_node, end=end_node, text="Explanation") """ comment_id = self.next_comment_id para_id = _generate_hex_id() durable_id = _generate_hex_id() timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") # Add comment ranges to document.xml immediately self._document.insert_before(start, self._comment_range_start_xml(comment_id)) # If end node is a paragraph, append comment markup inside it # Otherwise insert after it (for run-level anchors) if end.tagName == "w:p": self._document.append_to(end, self._comment_range_end_xml(comment_id)) else: self._document.insert_after(end, self._comment_range_end_xml(comment_id)) # Add to comments.xml immediately self._add_to_comments_xml( comment_id, para_id, text, self.author, self.initials, timestamp ) # Add to commentsExtended.xml immediately self._add_to_comments_extended_xml(para_id, parent_para_id=None) # Add to commentsIds.xml immediately self._add_to_comments_ids_xml(para_id, durable_id) # Add to commentsExtensible.xml immediately self._add_to_comments_extensible_xml(durable_id) # Update existing_comments so replies work self.existing_comments[comment_id] = {"para_id": para_id} self.next_comment_id += 1 return comment_id def reply_to_comment( self, parent_comment_id: int, text: str, ) -> int: """ Add a reply to an existing comment. Args: parent_comment_id: The w:id of the parent comment to reply to text: Reply text Returns: The comment ID that was created for the reply Example: cm.reply_to_comment(parent_comment_id=0, text="I agree with this change") """ if parent_comment_id not in self.existing_comments: raise ValueError(f"Parent comment with id={parent_comment_id} not found") parent_info = self.existing_comments[parent_comment_id] comment_id = self.next_comment_id para_id = _generate_hex_id() durable_id = _generate_hex_id() timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") # Add comment ranges to document.xml immediately parent_start_elem = self._document.get_node( tag="w:commentRangeStart", attrs={"w:id": str(parent_comment_id)} ) parent_ref_elem = self._document.get_node( tag="w:commentReference", attrs={"w:id": str(parent_comment_id)} ) self._document.insert_after( parent_start_elem, self._comment_range_start_xml(comment_id) ) parent_ref_run = parent_ref_elem.parentNode self._document.insert_after( parent_ref_run, f'<w:commentRangeEnd w:id="{comment_id}"/>' ) self._document.insert_after( parent_ref_run, self._comment_ref_run_xml(comment_id) ) # Add to comments.xml immediately self._add_to_comments_xml( comment_id, para_id, text, self.author, self.initials, timestamp ) # Add to commentsExtended.xml immediately (with parent) self._add_to_comments_extended_xml( para_id, parent_para_id=parent_info["para_id"] ) # Add to commentsIds.xml immediately self._add_to_comments_ids_xml(para_id, durable_id) # Add to commentsExtensible.xml immediately self._add_to_comments_extensible_xml(durable_id) # Update existing_comments so replies work self.existing_comments[comment_id] = {"para_id": para_id} self.next_comment_id += 1 return comment_id def __del__(self): """Clean up temporary directory on deletion.""" if hasattr(self, "temp_dir") and Path(self.temp_dir).exists(): shutil.rmtree(self.temp_dir) def validate(self) -> None: """ Validate the document against XSD schema and redlining rules. Raises: ValueError: If validation fails. """ # Create validators with current state schema_validator = DOCXSchemaValidator( self.unpacked_path, self.original_docx, verbose=False ) redlining_validator = RedliningValidator( self.unpacked_path, self.original_docx, verbose=False ) # Run validations if not schema_validator.validate(): raise ValueError("Schema validation failed") if not redlining_validator.validate(): raise ValueError("Redlining validation failed") def save(self, destination=None, validate=True) -> None: """ Save all modified XML files to disk and copy to destination directory. This persists all changes made via add_comment() and reply_to_comment(). Args: destination: Optional path to save to. If None, saves back to original directory. validate: If True, validates document before saving (default: True). """ # Only ensure comment relationships and content types if comment files exist if self.comments_path.exists(): self._ensure_comment_relationships() self._ensure_comment_content_types() # Save all modified XML files in temp directory for editor in self._editors.values(): editor.save() # Validate by default if validate: self.validate() # Copy contents from temp directory to destination (or original directory) target_path = Path(destination) if destination else self.original_path shutil.copytree(self.unpacked_path, target_path, dirs_exist_ok=True) # ==================== Private: Initialization ==================== def _get_next_comment_id(self): """Get the next available comment ID.""" if not self.comments_path.exists(): return 0 editor = self["word/comments.xml"] max_id = -1 for comment_elem in editor.dom.getElementsByTagName("w:comment"): comment_id = comment_elem.getAttribute("w:id") if comment_id: try: max_id = max(max_id, int(comment_id)) except ValueError: pass return max_id + 1 def _load_existing_comments(self): """Load existing comments from files to enable replies.""" if not self.comments_path.exists(): return {} editor = self["word/comments.xml"] existing = {} for comment_elem in editor.dom.getElementsByTagName("w:comment"): comment_id = comment_elem.getAttribute("w:id") if not comment_id: continue # Find para_id from the w:p element within the comment para_id = None for p_elem in comment_elem.getElementsByTagName("w:p"): para_id = p_elem.getAttribute("w14:paraId") if para_id: break if not para_id: continue existing[int(comment_id)] = {"para_id": para_id} return existing # ==================== Private: Setup Methods ==================== def _setup_tracking(self, track_revisions=False): """Set up comment infrastructure in unpacked directory. Args: track_revisions: If True, enables track revisions in settings.xml """ # Create or update word/people.xml people_file = self.word_path / "people.xml" self._update_people_xml(people_file) # Update XML files self._add_content_type_for_people(self.unpacked_path / "[Content_Types].xml") self._add_relationship_for_people( self.word_path / "_rels" / "document.xml.rels" ) # Always add RSID to settings.xml, optionally enable trackRevisions self._update_settings( self.word_path / "settings.xml", track_revisions=track_revisions ) def _update_people_xml(self, path): """Create people.xml if it doesn't exist.""" if not path.exists(): # Copy from template shutil.copy(TEMPLATE_DIR / "people.xml", path) def _add_content_type_for_people(self, path): """Add people.xml content type to [Content_Types].xml if not already present.""" editor = self["[Content_Types].xml"] if self._has_override(editor, "/word/people.xml"): return # Add Override element root = editor.dom.documentElement override_xml = '<Override PartName="/word/people.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.people+xml"/>' editor.append_to(root, override_xml) def _add_relationship_for_people(self, path): """Add people.xml relationship to document.xml.rels if not already present.""" editor = self["word/_rels/document.xml.rels"] if self._has_relationship(editor, "people.xml"): return root = editor.dom.documentElement root_tag = root.tagName # type: ignore prefix = root_tag.split(":")[0] + ":" if ":" in root_tag else "" next_rid = editor.get_next_rid() # Create the relationship entry rel_xml = f'<{prefix}Relationship Id="{next_rid}" Type="http://schemas.microsoft.com/office/2011/relationships/people" Target="people.xml"/>' editor.append_to(root, rel_xml) def _update_settings(self, path, track_revisions=False): """Add RSID and optionally enable track revisions in settings.xml. Args: path: Path to settings.xml track_revisions: If True, adds trackRevisions element Places elements per OOXML schema order: - trackRevisions: early (before defaultTabStop) - rsids: late (after compat) """ editor = self["word/settings.xml"] root = editor.get_node(tag="w:settings") prefix = root.tagName.split(":")[0] if ":" in root.tagName else "w" # Conditionally add trackRevisions if requested if track_revisions: track_revisions_exists = any( elem.tagName == f"{prefix}:trackRevisions" for elem in editor.dom.getElementsByTagName(f"{prefix}:trackRevisions") ) if not track_revisions_exists: track_rev_xml = f"<{prefix}:trackRevisions/>" # Try to insert before documentProtection, defaultTabStop, or at start inserted = False for tag in [f"{prefix}:documentProtection", f"{prefix}:defaultTabStop"]: elements = editor.dom.getElementsByTagName(tag) if elements: editor.insert_before(elements[0], track_rev_xml) inserted = True break if not inserted: # Insert as first child of settings if root.firstChild: editor.insert_before(root.firstChild, track_rev_xml) else: editor.append_to(root, track_rev_xml) # Always check if rsids section exists rsids_elements = editor.dom.getElementsByTagName(f"{prefix}:rsids") if not rsids_elements: # Add new rsids section rsids_xml = f'''<{prefix}:rsids> <{prefix}:rsidRoot {prefix}:val="{self.rsid}"/> <{prefix}:rsid {prefix}:val="{self.rsid}"/> </{prefix}:rsids>''' # Try to insert after compat, before clrSchemeMapping, or before closing tag inserted = False compat_elements = editor.dom.getElementsByTagName(f"{prefix}:compat") if compat_elements: editor.insert_after(compat_elements[0], rsids_xml) inserted = True if not inserted: clr_elements = editor.dom.getElementsByTagName( f"{prefix}:clrSchemeMapping" ) if clr_elements: editor.insert_before(clr_elements[0], rsids_xml) inserted = True if not inserted: editor.append_to(root, rsids_xml) else: # Check if this rsid already exists rsids_elem = rsids_elements[0] rsid_exists = any( elem.getAttribute(f"{prefix}:val") == self.rsid for elem in rsids_elem.getElementsByTagName(f"{prefix}:rsid") ) if not rsid_exists: rsid_xml = f'<{prefix}:rsid {prefix}:val="{self.rsid}"/>' editor.append_to(rsids_elem, rsid_xml) # ==================== Private: XML File Creation ==================== def _add_to_comments_xml( self, comment_id, para_id, text, author, initials, timestamp ): """Add a single comment to comments.xml.""" if not self.comments_path.exists(): shutil.copy(TEMPLATE_DIR / "comments.xml", self.comments_path) editor = self["word/comments.xml"] root = editor.get_node(tag="w:comments") escaped_text = ( text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") ) # Note: w:rsidR, w:rsidRDefault, w:rsidP on w:p, w:rsidR on w:r, # and w:author, w:date, w:initials on w:comment are automatically added by DocxXMLEditor comment_xml = f'''<w:comment w:id="{comment_id}"> <w:p w14:paraId="{para_id}" w14:textId="77777777"> <w:r><w:rPr><w:rStyle w:val="CommentReference"/></w:rPr><w:annotationRef/></w:r> <w:r><w:rPr><w:color w:val="000000"/><w:sz w:val="20"/><w:szCs w:val="20"/></w:rPr><w:t>{escaped_text}</w:t></w:r> </w:p> </w:comment>''' editor.append_to(root, comment_xml) def _add_to_comments_extended_xml(self, para_id, parent_para_id): """Add a single comment to commentsExtended.xml.""" if not self.comments_extended_path.exists(): shutil.copy( TEMPLATE_DIR / "commentsExtended.xml", self.comments_extended_path ) editor = self["word/commentsExtended.xml"] root = editor.get_node(tag="w15:commentsEx") if parent_para_id: xml = f'<w15:commentEx w15:paraId="{para_id}" w15:paraIdParent="{parent_para_id}" w15:done="0"/>' else: xml = f'<w15:commentEx w15:paraId="{para_id}" w15:done="0"/>' editor.append_to(root, xml) def _add_to_comments_ids_xml(self, para_id, durable_id): """Add a single comment to commentsIds.xml.""" if not self.comments_ids_path.exists(): shutil.copy(TEMPLATE_DIR / "commentsIds.xml", self.comments_ids_path) editor = self["word/commentsIds.xml"] root = editor.get_node(tag="w16cid:commentsIds") xml = f'<w16cid:commentId w16cid:paraId="{para_id}" w16cid:durableId="{durable_id}"/>' editor.append_to(root, xml) def _add_to_comments_extensible_xml(self, durable_id): """Add a single comment to commentsExtensible.xml.""" if not self.comments_extensible_path.exists(): shutil.copy( TEMPLATE_DIR / "commentsExtensible.xml", self.comments_extensible_path ) editor = self["word/commentsExtensible.xml"] root = editor.get_node(tag="w16cex:commentsExtensible") xml = f'<w16cex:commentExtensible w16cex:durableId="{durable_id}"/>' editor.append_to(root, xml) # ==================== Private: XML Fragments ==================== def _comment_range_start_xml(self, comment_id): """Generate XML for comment range start.""" return f'<w:commentRangeStart w:id="{comment_id}"/>' def _comment_range_end_xml(self, comment_id): """Generate XML for comment range end with reference run. Note: w:rsidR is automatically added by DocxXMLEditor. """ return f'''<w:commentRangeEnd w:id="{comment_id}"/> <w:r> <w:rPr><w:rStyle w:val="CommentReference"/></w:rPr> <w:commentReference w:id="{comment_id}"/> </w:r>''' def _comment_ref_run_xml(self, comment_id): """Generate XML for comment reference run. Note: w:rsidR is automatically added by DocxXMLEditor. """ return f'''<w:r> <w:rPr><w:rStyle w:val="CommentReference"/></w:rPr> <w:commentReference w:id="{comment_id}"/> </w:r>''' # ==================== Private: Metadata Updates ==================== def _has_relationship(self, editor, target): """Check if a relationship with given target exists.""" for rel_elem in editor.dom.getElementsByTagName("Relationship"): if rel_elem.getAttribute("Target") == target: return True return False def _has_override(self, editor, part_name): """Check if an override with given part name exists.""" for override_elem in editor.dom.getElementsByTagName("Override"): if override_elem.getAttribute("PartName") == part_name: return True return False def _has_author(self, editor, author): """Check if an author already exists in people.xml.""" for person_elem in editor.dom.getElementsByTagName("w15:person"): if person_elem.getAttribute("w15:author") == author: return True return False def _add_author_to_people(self, author): """Add author to people.xml (called during initialization).""" people_path = self.word_path / "people.xml" # people.xml should already exist from _setup_tracking if not people_path.exists(): raise ValueError("people.xml should exist after _setup_tracking") editor = self["word/people.xml"] root = editor.get_node(tag="w15:people") # Check if author already exists if self._has_author(editor, author): return # Add author with proper XML escaping to prevent injection escaped_author = html.escape(author, quote=True) person_xml = f'''<w15:person w15:author="{escaped_author}"> <w15:presenceInfo w15:providerId="None" w15:userId="{escaped_author}"/> </w15:person>''' editor.append_to(root, person_xml) def _ensure_comment_relationships(self): """Ensure word/_rels/document.xml.rels has comment relationships.""" editor = self["word/_rels/document.xml.rels"] if self._has_relationship(editor, "comments.xml"): return root = editor.dom.documentElement root_tag = root.tagName # type: ignore prefix = root_tag.split(":")[0] + ":" if ":" in root_tag else "" next_rid_num = int(editor.get_next_rid()[3:]) # Add relationship elements rels = [ ( next_rid_num, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments", "comments.xml", ), ( next_rid_num + 1, "http://schemas.microsoft.com/office/2011/relationships/commentsExtended", "commentsExtended.xml", ), ( next_rid_num + 2, "http://schemas.microsoft.com/office/2016/09/relationships/commentsIds", "commentsIds.xml", ), ( next_rid_num + 3, "http://schemas.microsoft.com/office/2018/08/relationships/commentsExtensible", "commentsExtensible.xml", ), ] for rel_id, rel_type, target in rels: rel_xml = f'<{prefix}Relationship Id="rId{rel_id}" Type="{rel_type}" Target="{target}"/>' editor.append_to(root, rel_xml) def _ensure_comment_content_types(self): """Ensure [Content_Types].xml has comment content types.""" editor = self["[Content_Types].xml"] if self._has_override(editor, "/word/comments.xml"): return root = editor.dom.documentElement # Add Override elements overrides = [ ( "/word/comments.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml", ), ( "/word/commentsExtended.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml", ), ( "/word/commentsIds.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsIds+xml", ), ( "/word/commentsExtensible.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtensible+xml", ), ] for part_name, content_type in overrides: override_xml = ( f'<Override PartName="{part_name}" ContentType="{content_type}"/>' ) editor.append_to(root, override_xml)
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/docx-official/scripts/document.py", "license": "MIT License", "lines": 1038, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/document-processing/docx-official/scripts/utilities.py
#!/usr/bin/env python3 """ Utilities for editing OOXML documents. This module provides XMLEditor, a tool for manipulating XML files with support for line-number-based node finding and DOM manipulation. Each element is automatically annotated with its original line and column position during parsing. Example usage: editor = XMLEditor("document.xml") # Find node by line number or range elem = editor.get_node(tag="w:r", line_number=519) elem = editor.get_node(tag="w:p", line_number=range(100, 200)) # Find node by text content elem = editor.get_node(tag="w:p", contains="specific text") # Find node by attributes elem = editor.get_node(tag="w:r", attrs={"w:id": "target"}) # Combine filters elem = editor.get_node(tag="w:p", line_number=range(1, 50), contains="text") # Replace, insert, or manipulate new_elem = editor.replace_node(elem, "<w:r><w:t>new text</w:t></w:r>") editor.insert_after(new_elem, "<w:r><w:t>more</w:t></w:r>") # Save changes editor.save() """ import html from pathlib import Path from typing import Optional, Union import defusedxml.minidom import defusedxml.sax class XMLEditor: """ Editor for manipulating OOXML XML files with line-number-based node finding. This class parses XML files and tracks the original line and column position of each element. This enables finding nodes by their line number in the original file, which is useful when working with Read tool output. Attributes: xml_path: Path to the XML file being edited encoding: Detected encoding of the XML file ('ascii' or 'utf-8') dom: Parsed DOM tree with parse_position attributes on elements """ def __init__(self, xml_path): """ Initialize with path to XML file and parse with line number tracking. Args: xml_path: Path to XML file to edit (str or Path) Raises: ValueError: If the XML file does not exist """ self.xml_path = Path(xml_path) if not self.xml_path.exists(): raise ValueError(f"XML file not found: {xml_path}") with open(self.xml_path, "rb") as f: header = f.read(200).decode("utf-8", errors="ignore") self.encoding = "ascii" if 'encoding="ascii"' in header else "utf-8" parser = _create_line_tracking_parser() self.dom = defusedxml.minidom.parse(str(self.xml_path), parser) def get_node( self, tag: str, attrs: Optional[dict[str, str]] = None, line_number: Optional[Union[int, range]] = None, contains: Optional[str] = None, ): """ Get a DOM element by tag and identifier. Finds an element by either its line number in the original file or by matching attribute values. Exactly one match must be found. Args: tag: The XML tag name (e.g., "w:del", "w:ins", "w:r") attrs: Dictionary of attribute name-value pairs to match (e.g., {"w:id": "1"}) line_number: Line number (int) or line range (range) in original XML file (1-indexed) contains: Text string that must appear in any text node within the element. Supports both entity notation (&#8220;) and Unicode characters (\u201c). Returns: defusedxml.minidom.Element: The matching DOM element Raises: ValueError: If node not found or multiple matches found Example: elem = editor.get_node(tag="w:r", line_number=519) elem = editor.get_node(tag="w:r", line_number=range(100, 200)) elem = editor.get_node(tag="w:del", attrs={"w:id": "1"}) elem = editor.get_node(tag="w:p", attrs={"w14:paraId": "12345678"}) elem = editor.get_node(tag="w:commentRangeStart", attrs={"w:id": "0"}) elem = editor.get_node(tag="w:p", contains="specific text") elem = editor.get_node(tag="w:t", contains="&#8220;Agreement") # Entity notation elem = editor.get_node(tag="w:t", contains="\u201cAgreement") # Unicode character """ matches = [] for elem in self.dom.getElementsByTagName(tag): # Check line_number filter if line_number is not None: parse_pos = getattr(elem, "parse_position", (None,)) elem_line = parse_pos[0] # Handle both single line number and range if isinstance(line_number, range): if elem_line not in line_number: continue else: if elem_line != line_number: continue # Check attrs filter if attrs is not None: if not all( elem.getAttribute(attr_name) == attr_value for attr_name, attr_value in attrs.items() ): continue # Check contains filter if contains is not None: elem_text = self._get_element_text(elem) # Normalize the search string: convert HTML entities to Unicode characters # This allows searching for both "&#8220;Rowan" and ""Rowan" normalized_contains = html.unescape(contains) if normalized_contains not in elem_text: continue # If all applicable filters passed, this is a match matches.append(elem) if not matches: # Build descriptive error message filters = [] if line_number is not None: line_str = ( f"lines {line_number.start}-{line_number.stop - 1}" if isinstance(line_number, range) else f"line {line_number}" ) filters.append(f"at {line_str}") if attrs is not None: filters.append(f"with attributes {attrs}") if contains is not None: filters.append(f"containing '{contains}'") filter_desc = " ".join(filters) if filters else "" base_msg = f"Node not found: <{tag}> {filter_desc}".strip() # Add helpful hint based on filters used if contains: hint = "Text may be split across elements or use different wording." elif line_number: hint = "Line numbers may have changed if document was modified." elif attrs: hint = "Verify attribute values are correct." else: hint = "Try adding filters (attrs, line_number, or contains)." raise ValueError(f"{base_msg}. {hint}") if len(matches) > 1: raise ValueError( f"Multiple nodes found: <{tag}>. " f"Add more filters (attrs, line_number, or contains) to narrow the search." ) return matches[0] def _get_element_text(self, elem): """ Recursively extract all text content from an element. Skips text nodes that contain only whitespace (spaces, tabs, newlines), which typically represent XML formatting rather than document content. Args: elem: defusedxml.minidom.Element to extract text from Returns: str: Concatenated text from all non-whitespace text nodes within the element """ text_parts = [] for node in elem.childNodes: if node.nodeType == node.TEXT_NODE: # Skip whitespace-only text nodes (XML formatting) if node.data.strip(): text_parts.append(node.data) elif node.nodeType == node.ELEMENT_NODE: text_parts.append(self._get_element_text(node)) return "".join(text_parts) def replace_node(self, elem, new_content): """ Replace a DOM element with new XML content. Args: elem: defusedxml.minidom.Element to replace new_content: String containing XML to replace the node with Returns: List[defusedxml.minidom.Node]: All inserted nodes Example: new_nodes = editor.replace_node(old_elem, "<w:r><w:t>text</w:t></w:r>") """ parent = elem.parentNode nodes = self._parse_fragment(new_content) for node in nodes: parent.insertBefore(node, elem) parent.removeChild(elem) return nodes def insert_after(self, elem, xml_content): """ Insert XML content after a DOM element. Args: elem: defusedxml.minidom.Element to insert after xml_content: String containing XML to insert Returns: List[defusedxml.minidom.Node]: All inserted nodes Example: new_nodes = editor.insert_after(elem, "<w:r><w:t>text</w:t></w:r>") """ parent = elem.parentNode next_sibling = elem.nextSibling nodes = self._parse_fragment(xml_content) for node in nodes: if next_sibling: parent.insertBefore(node, next_sibling) else: parent.appendChild(node) return nodes def insert_before(self, elem, xml_content): """ Insert XML content before a DOM element. Args: elem: defusedxml.minidom.Element to insert before xml_content: String containing XML to insert Returns: List[defusedxml.minidom.Node]: All inserted nodes Example: new_nodes = editor.insert_before(elem, "<w:r><w:t>text</w:t></w:r>") """ parent = elem.parentNode nodes = self._parse_fragment(xml_content) for node in nodes: parent.insertBefore(node, elem) return nodes def append_to(self, elem, xml_content): """ Append XML content as a child of a DOM element. Args: elem: defusedxml.minidom.Element to append to xml_content: String containing XML to append Returns: List[defusedxml.minidom.Node]: All inserted nodes Example: new_nodes = editor.append_to(elem, "<w:r><w:t>text</w:t></w:r>") """ nodes = self._parse_fragment(xml_content) for node in nodes: elem.appendChild(node) return nodes def get_next_rid(self): """Get the next available rId for relationships files.""" max_id = 0 for rel_elem in self.dom.getElementsByTagName("Relationship"): rel_id = rel_elem.getAttribute("Id") if rel_id.startswith("rId"): try: max_id = max(max_id, int(rel_id[3:])) except ValueError: pass return f"rId{max_id + 1}" def save(self): """ Save the edited XML back to the file. Serializes the DOM tree and writes it back to the original file path, preserving the original encoding (ascii or utf-8). """ content = self.dom.toxml(encoding=self.encoding) self.xml_path.write_bytes(content) def _parse_fragment(self, xml_content): """ Parse XML fragment and return list of imported nodes. Args: xml_content: String containing XML fragment Returns: List of defusedxml.minidom.Node objects imported into this document Raises: AssertionError: If fragment contains no element nodes """ # Extract namespace declarations from the root document element root_elem = self.dom.documentElement namespaces = [] if root_elem and root_elem.attributes: for i in range(root_elem.attributes.length): attr = root_elem.attributes.item(i) if attr.name.startswith("xmlns"): # type: ignore namespaces.append(f'{attr.name}="{attr.value}"') # type: ignore ns_decl = " ".join(namespaces) wrapper = f"<root {ns_decl}>{xml_content}</root>" fragment_doc = defusedxml.minidom.parseString(wrapper) nodes = [ self.dom.importNode(child, deep=True) for child in fragment_doc.documentElement.childNodes # type: ignore ] elements = [n for n in nodes if n.nodeType == n.ELEMENT_NODE] assert elements, "Fragment must contain at least one element" return nodes def _create_line_tracking_parser(): """ Create a SAX parser that tracks line and column numbers for each element. Monkey patches the SAX content handler to store the current line and column position from the underlying expat parser onto each element as a parse_position attribute (line, column) tuple. Returns: defusedxml.sax.xmlreader.XMLReader: Configured SAX parser """ def set_content_handler(dom_handler): def startElementNS(name, tagName, attrs): orig_start_cb(name, tagName, attrs) cur_elem = dom_handler.elementStack[-1] cur_elem.parse_position = ( parser._parser.CurrentLineNumber, # type: ignore parser._parser.CurrentColumnNumber, # type: ignore ) orig_start_cb = dom_handler.startElementNS dom_handler.startElementNS = startElementNS orig_set_content_handler(dom_handler) parser = defusedxml.sax.make_parser() orig_set_content_handler = parser.setContentHandler parser.setContentHandler = set_content_handler # type: ignore return parser
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/docx-official/scripts/utilities.py", "license": "MIT License", "lines": 306, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
davila7/claude-code-templates:cli-tool/components/skills/document-processing/pdf-official/scripts/check_bounding_boxes.py
from dataclasses import dataclass import json import sys # Script to check that the `fields.json` file that Claude creates when analyzing PDFs # does not have overlapping bounding boxes. See forms.md. @dataclass class RectAndField: rect: list[float] rect_type: str field: dict # Returns a list of messages that are printed to stdout for Claude to read. def get_bounding_box_messages(fields_json_stream) -> list[str]: messages = [] fields = json.load(fields_json_stream) messages.append(f"Read {len(fields['form_fields'])} fields") def rects_intersect(r1, r2): disjoint_horizontal = r1[0] >= r2[2] or r1[2] <= r2[0] disjoint_vertical = r1[1] >= r2[3] or r1[3] <= r2[1] return not (disjoint_horizontal or disjoint_vertical) rects_and_fields = [] for f in fields["form_fields"]: rects_and_fields.append(RectAndField(f["label_bounding_box"], "label", f)) rects_and_fields.append(RectAndField(f["entry_bounding_box"], "entry", f)) has_error = False for i, ri in enumerate(rects_and_fields): # This is O(N^2); we can optimize if it becomes a problem. for j in range(i + 1, len(rects_and_fields)): rj = rects_and_fields[j] if ri.field["page_number"] == rj.field["page_number"] and rects_intersect(ri.rect, rj.rect): has_error = True if ri.field is rj.field: messages.append(f"FAILURE: intersection between label and entry bounding boxes for `{ri.field['description']}` ({ri.rect}, {rj.rect})") else: messages.append(f"FAILURE: intersection between {ri.rect_type} bounding box for `{ri.field['description']}` ({ri.rect}) and {rj.rect_type} bounding box for `{rj.field['description']}` ({rj.rect})") if len(messages) >= 20: messages.append("Aborting further checks; fix bounding boxes and try again") return messages if ri.rect_type == "entry": if "entry_text" in ri.field: font_size = ri.field["entry_text"].get("font_size", 14) entry_height = ri.rect[3] - ri.rect[1] if entry_height < font_size: has_error = True messages.append(f"FAILURE: entry bounding box height ({entry_height}) for `{ri.field['description']}` is too short for the text content (font size: {font_size}). Increase the box height or decrease the font size.") if len(messages) >= 20: messages.append("Aborting further checks; fix bounding boxes and try again") return messages if not has_error: messages.append("SUCCESS: All bounding boxes are valid") return messages if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: check_bounding_boxes.py [fields.json]") sys.exit(1) # Input file should be in the `fields.json` format described in forms.md. with open(sys.argv[1]) as f: messages = get_bounding_box_messages(f) for msg in messages: print(msg)
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/pdf-official/scripts/check_bounding_boxes.py", "license": "MIT License", "lines": 59, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/document-processing/pdf-official/scripts/check_bounding_boxes_test.py
import unittest import json import io from check_bounding_boxes import get_bounding_box_messages # Currently this is not run automatically in CI; it's just for documentation and manual checking. class TestGetBoundingBoxMessages(unittest.TestCase): def create_json_stream(self, data): """Helper to create a JSON stream from data""" return io.StringIO(json.dumps(data)) def test_no_intersections(self): """Test case with no bounding box intersections""" data = { "form_fields": [ { "description": "Name", "page_number": 1, "label_bounding_box": [10, 10, 50, 30], "entry_bounding_box": [60, 10, 150, 30] }, { "description": "Email", "page_number": 1, "label_bounding_box": [10, 40, 50, 60], "entry_bounding_box": [60, 40, 150, 60] } ] } stream = self.create_json_stream(data) messages = get_bounding_box_messages(stream) self.assertTrue(any("SUCCESS" in msg for msg in messages)) self.assertFalse(any("FAILURE" in msg for msg in messages)) def test_label_entry_intersection_same_field(self): """Test intersection between label and entry of the same field""" data = { "form_fields": [ { "description": "Name", "page_number": 1, "label_bounding_box": [10, 10, 60, 30], "entry_bounding_box": [50, 10, 150, 30] # Overlaps with label } ] } stream = self.create_json_stream(data) messages = get_bounding_box_messages(stream) self.assertTrue(any("FAILURE" in msg and "intersection" in msg for msg in messages)) self.assertFalse(any("SUCCESS" in msg for msg in messages)) def test_intersection_between_different_fields(self): """Test intersection between bounding boxes of different fields""" data = { "form_fields": [ { "description": "Name", "page_number": 1, "label_bounding_box": [10, 10, 50, 30], "entry_bounding_box": [60, 10, 150, 30] }, { "description": "Email", "page_number": 1, "label_bounding_box": [40, 20, 80, 40], # Overlaps with Name's boxes "entry_bounding_box": [160, 10, 250, 30] } ] } stream = self.create_json_stream(data) messages = get_bounding_box_messages(stream) self.assertTrue(any("FAILURE" in msg and "intersection" in msg for msg in messages)) self.assertFalse(any("SUCCESS" in msg for msg in messages)) def test_different_pages_no_intersection(self): """Test that boxes on different pages don't count as intersecting""" data = { "form_fields": [ { "description": "Name", "page_number": 1, "label_bounding_box": [10, 10, 50, 30], "entry_bounding_box": [60, 10, 150, 30] }, { "description": "Email", "page_number": 2, "label_bounding_box": [10, 10, 50, 30], # Same coordinates but different page "entry_bounding_box": [60, 10, 150, 30] } ] } stream = self.create_json_stream(data) messages = get_bounding_box_messages(stream) self.assertTrue(any("SUCCESS" in msg for msg in messages)) self.assertFalse(any("FAILURE" in msg for msg in messages)) def test_entry_height_too_small(self): """Test that entry box height is checked against font size""" data = { "form_fields": [ { "description": "Name", "page_number": 1, "label_bounding_box": [10, 10, 50, 30], "entry_bounding_box": [60, 10, 150, 20], # Height is 10 "entry_text": { "font_size": 14 # Font size larger than height } } ] } stream = self.create_json_stream(data) messages = get_bounding_box_messages(stream) self.assertTrue(any("FAILURE" in msg and "height" in msg for msg in messages)) self.assertFalse(any("SUCCESS" in msg for msg in messages)) def test_entry_height_adequate(self): """Test that adequate entry box height passes""" data = { "form_fields": [ { "description": "Name", "page_number": 1, "label_bounding_box": [10, 10, 50, 30], "entry_bounding_box": [60, 10, 150, 30], # Height is 20 "entry_text": { "font_size": 14 # Font size smaller than height } } ] } stream = self.create_json_stream(data) messages = get_bounding_box_messages(stream) self.assertTrue(any("SUCCESS" in msg for msg in messages)) self.assertFalse(any("FAILURE" in msg for msg in messages)) def test_default_font_size(self): """Test that default font size is used when not specified""" data = { "form_fields": [ { "description": "Name", "page_number": 1, "label_bounding_box": [10, 10, 50, 30], "entry_bounding_box": [60, 10, 150, 20], # Height is 10 "entry_text": {} # No font_size specified, should use default 14 } ] } stream = self.create_json_stream(data) messages = get_bounding_box_messages(stream) self.assertTrue(any("FAILURE" in msg and "height" in msg for msg in messages)) self.assertFalse(any("SUCCESS" in msg for msg in messages)) def test_no_entry_text(self): """Test that missing entry_text doesn't cause height check""" data = { "form_fields": [ { "description": "Name", "page_number": 1, "label_bounding_box": [10, 10, 50, 30], "entry_bounding_box": [60, 10, 150, 20] # Small height but no entry_text } ] } stream = self.create_json_stream(data) messages = get_bounding_box_messages(stream) self.assertTrue(any("SUCCESS" in msg for msg in messages)) self.assertFalse(any("FAILURE" in msg for msg in messages)) def test_multiple_errors_limit(self): """Test that error messages are limited to prevent excessive output""" fields = [] # Create many overlapping fields for i in range(25): fields.append({ "description": f"Field{i}", "page_number": 1, "label_bounding_box": [10, 10, 50, 30], # All overlap "entry_bounding_box": [20, 15, 60, 35] # All overlap }) data = {"form_fields": fields} stream = self.create_json_stream(data) messages = get_bounding_box_messages(stream) # Should abort after ~20 messages self.assertTrue(any("Aborting" in msg for msg in messages)) # Should have some FAILURE messages but not hundreds failure_count = sum(1 for msg in messages if "FAILURE" in msg) self.assertGreater(failure_count, 0) self.assertLess(len(messages), 30) # Should be limited def test_edge_touching_boxes(self): """Test that boxes touching at edges don't count as intersecting""" data = { "form_fields": [ { "description": "Name", "page_number": 1, "label_bounding_box": [10, 10, 50, 30], "entry_bounding_box": [50, 10, 150, 30] # Touches at x=50 } ] } stream = self.create_json_stream(data) messages = get_bounding_box_messages(stream) self.assertTrue(any("SUCCESS" in msg for msg in messages)) self.assertFalse(any("FAILURE" in msg for msg in messages)) if __name__ == '__main__': unittest.main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/pdf-official/scripts/check_bounding_boxes_test.py", "license": "MIT License", "lines": 200, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
davila7/claude-code-templates:cli-tool/components/skills/document-processing/pdf-official/scripts/check_fillable_fields.py
import sys from pypdf import PdfReader # Script for Claude to run to determine whether a PDF has fillable form fields. See forms.md. reader = PdfReader(sys.argv[1]) if (reader.get_fields()): print("This PDF has fillable form fields") else: print("This PDF does not have fillable form fields; you will need to visually determine where to enter data")
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/pdf-official/scripts/check_fillable_fields.py", "license": "MIT License", "lines": 8, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
davila7/claude-code-templates:cli-tool/components/skills/document-processing/pdf-official/scripts/convert_pdf_to_images.py
import os import sys from pdf2image import convert_from_path # Converts each page of a PDF to a PNG image. def convert(pdf_path, output_dir, max_dim=1000): images = convert_from_path(pdf_path, dpi=200) for i, image in enumerate(images): # Scale image if needed to keep width/height under `max_dim` width, height = image.size if width > max_dim or height > max_dim: scale_factor = min(max_dim / width, max_dim / height) new_width = int(width * scale_factor) new_height = int(height * scale_factor) image = image.resize((new_width, new_height)) image_path = os.path.join(output_dir, f"page_{i+1}.png") image.save(image_path) print(f"Saved page {i+1} as {image_path} (size: {image.size})") print(f"Converted {len(images)} pages to PNG images") if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: convert_pdf_to_images.py [input pdf] [output directory]") sys.exit(1) pdf_path = sys.argv[1] output_directory = sys.argv[2] convert(pdf_path, output_directory)
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/pdf-official/scripts/convert_pdf_to_images.py", "license": "MIT License", "lines": 25, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
davila7/claude-code-templates:cli-tool/components/skills/document-processing/pdf-official/scripts/create_validation_image.py
import json import sys from PIL import Image, ImageDraw # Creates "validation" images with rectangles for the bounding box information that # Claude creates when determining where to add text annotations in PDFs. See forms.md. def create_validation_image(page_number, fields_json_path, input_path, output_path): # Input file should be in the `fields.json` format described in forms.md. with open(fields_json_path, 'r') as f: data = json.load(f) img = Image.open(input_path) draw = ImageDraw.Draw(img) num_boxes = 0 for field in data["form_fields"]: if field["page_number"] == page_number: entry_box = field['entry_bounding_box'] label_box = field['label_bounding_box'] # Draw red rectangle over entry bounding box and blue rectangle over the label. draw.rectangle(entry_box, outline='red', width=2) draw.rectangle(label_box, outline='blue', width=2) num_boxes += 2 img.save(output_path) print(f"Created validation image at {output_path} with {num_boxes} bounding boxes") if __name__ == "__main__": if len(sys.argv) != 5: print("Usage: create_validation_image.py [page number] [fields.json file] [input image path] [output image path]") sys.exit(1) page_number = int(sys.argv[1]) fields_json_path = sys.argv[2] input_image_path = sys.argv[3] output_image_path = sys.argv[4] create_validation_image(page_number, fields_json_path, input_image_path, output_image_path)
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/pdf-official/scripts/create_validation_image.py", "license": "MIT License", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
davila7/claude-code-templates:cli-tool/components/skills/document-processing/pdf-official/scripts/extract_form_field_info.py
import json import sys from pypdf import PdfReader # Extracts data for the fillable form fields in a PDF and outputs JSON that # Claude uses to fill the fields. See forms.md. # This matches the format used by PdfReader `get_fields` and `update_page_form_field_values` methods. def get_full_annotation_field_id(annotation): components = [] while annotation: field_name = annotation.get('/T') if field_name: components.append(field_name) annotation = annotation.get('/Parent') return ".".join(reversed(components)) if components else None def make_field_dict(field, field_id): field_dict = {"field_id": field_id} ft = field.get('/FT') if ft == "/Tx": field_dict["type"] = "text" elif ft == "/Btn": field_dict["type"] = "checkbox" # radio groups handled separately states = field.get("/_States_", []) if len(states) == 2: # "/Off" seems to always be the unchecked value, as suggested by # https://opensource.adobe.com/dc-acrobat-sdk-docs/standards/pdfstandards/pdf/PDF32000_2008.pdf#page=448 # It can be either first or second in the "/_States_" list. if "/Off" in states: field_dict["checked_value"] = states[0] if states[0] != "/Off" else states[1] field_dict["unchecked_value"] = "/Off" else: print(f"Unexpected state values for checkbox `${field_id}`. Its checked and unchecked values may not be correct; if you're trying to check it, visually verify the results.") field_dict["checked_value"] = states[0] field_dict["unchecked_value"] = states[1] elif ft == "/Ch": field_dict["type"] = "choice" states = field.get("/_States_", []) field_dict["choice_options"] = [{ "value": state[0], "text": state[1], } for state in states] else: field_dict["type"] = f"unknown ({ft})" return field_dict # Returns a list of fillable PDF fields: # [ # { # "field_id": "name", # "page": 1, # "type": ("text", "checkbox", "radio_group", or "choice") # // Per-type additional fields described in forms.md # }, # ] def get_field_info(reader: PdfReader): fields = reader.get_fields() field_info_by_id = {} possible_radio_names = set() for field_id, field in fields.items(): # Skip if this is a container field with children, except that it might be # a parent group for radio button options. if field.get("/Kids"): if field.get("/FT") == "/Btn": possible_radio_names.add(field_id) continue field_info_by_id[field_id] = make_field_dict(field, field_id) # Bounding rects are stored in annotations in page objects. # Radio button options have a separate annotation for each choice; # all choices have the same field name. # See https://westhealth.github.io/exploring-fillable-forms-with-pdfrw.html radio_fields_by_id = {} for page_index, page in enumerate(reader.pages): annotations = page.get('/Annots', []) for ann in annotations: field_id = get_full_annotation_field_id(ann) if field_id in field_info_by_id: field_info_by_id[field_id]["page"] = page_index + 1 field_info_by_id[field_id]["rect"] = ann.get('/Rect') elif field_id in possible_radio_names: try: # ann['/AP']['/N'] should have two items. One of them is '/Off', # the other is the active value. on_values = [v for v in ann["/AP"]["/N"] if v != "/Off"] except KeyError: continue if len(on_values) == 1: rect = ann.get("/Rect") if field_id not in radio_fields_by_id: radio_fields_by_id[field_id] = { "field_id": field_id, "type": "radio_group", "page": page_index + 1, "radio_options": [], } # Note: at least on macOS 15.7, Preview.app doesn't show selected # radio buttons correctly. (It does if you remove the leading slash # from the value, but that causes them not to appear correctly in # Chrome/Firefox/Acrobat/etc). radio_fields_by_id[field_id]["radio_options"].append({ "value": on_values[0], "rect": rect, }) # Some PDFs have form field definitions without corresponding annotations, # so we can't tell where they are. Ignore these fields for now. fields_with_location = [] for field_info in field_info_by_id.values(): if "page" in field_info: fields_with_location.append(field_info) else: print(f"Unable to determine location for field id: {field_info.get('field_id')}, ignoring") # Sort by page number, then Y position (flipped in PDF coordinate system), then X. def sort_key(f): if "radio_options" in f: rect = f["radio_options"][0]["rect"] or [0, 0, 0, 0] else: rect = f.get("rect") or [0, 0, 0, 0] adjusted_position = [-rect[1], rect[0]] return [f.get("page"), adjusted_position] sorted_fields = fields_with_location + list(radio_fields_by_id.values()) sorted_fields.sort(key=sort_key) return sorted_fields def write_field_info(pdf_path: str, json_output_path: str): reader = PdfReader(pdf_path) field_info = get_field_info(reader) with open(json_output_path, "w") as f: json.dump(field_info, f, indent=2) print(f"Wrote {len(field_info)} fields to {json_output_path}") if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: extract_form_field_info.py [input pdf] [output json]") sys.exit(1) write_field_info(sys.argv[1], sys.argv[2])
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/pdf-official/scripts/extract_form_field_info.py", "license": "MIT License", "lines": 130, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/document-processing/pdf-official/scripts/fill_fillable_fields.py
import json import sys from pypdf import PdfReader, PdfWriter from extract_form_field_info import get_field_info # Fills fillable form fields in a PDF. See forms.md. def fill_pdf_fields(input_pdf_path: str, fields_json_path: str, output_pdf_path: str): with open(fields_json_path) as f: fields = json.load(f) # Group by page number. fields_by_page = {} for field in fields: if "value" in field: field_id = field["field_id"] page = field["page"] if page not in fields_by_page: fields_by_page[page] = {} fields_by_page[page][field_id] = field["value"] reader = PdfReader(input_pdf_path) has_error = False field_info = get_field_info(reader) fields_by_ids = {f["field_id"]: f for f in field_info} for field in fields: existing_field = fields_by_ids.get(field["field_id"]) if not existing_field: has_error = True print(f"ERROR: `{field['field_id']}` is not a valid field ID") elif field["page"] != existing_field["page"]: has_error = True print(f"ERROR: Incorrect page number for `{field['field_id']}` (got {field['page']}, expected {existing_field['page']})") else: if "value" in field: err = validation_error_for_field_value(existing_field, field["value"]) if err: print(err) has_error = True if has_error: sys.exit(1) writer = PdfWriter(clone_from=reader) for page, field_values in fields_by_page.items(): writer.update_page_form_field_values(writer.pages[page - 1], field_values, auto_regenerate=False) # This seems to be necessary for many PDF viewers to format the form values correctly. # It may cause the viewer to show a "save changes" dialog even if the user doesn't make any changes. writer.set_need_appearances_writer(True) with open(output_pdf_path, "wb") as f: writer.write(f) def validation_error_for_field_value(field_info, field_value): field_type = field_info["type"] field_id = field_info["field_id"] if field_type == "checkbox": checked_val = field_info["checked_value"] unchecked_val = field_info["unchecked_value"] if field_value != checked_val and field_value != unchecked_val: return f'ERROR: Invalid value "{field_value}" for checkbox field "{field_id}". The checked value is "{checked_val}" and the unchecked value is "{unchecked_val}"' elif field_type == "radio_group": option_values = [opt["value"] for opt in field_info["radio_options"]] if field_value not in option_values: return f'ERROR: Invalid value "{field_value}" for radio group field "{field_id}". Valid values are: {option_values}' elif field_type == "choice": choice_values = [opt["value"] for opt in field_info["choice_options"]] if field_value not in choice_values: return f'ERROR: Invalid value "{field_value}" for choice field "{field_id}". Valid values are: {choice_values}' return None # pypdf (at least version 5.7.0) has a bug when setting the value for a selection list field. # In _writer.py around line 966: # # if field.get(FA.FT, "/Tx") == "/Ch" and field_flags & FA.FfBits.Combo == 0: # txt = "\n".join(annotation.get_inherited(FA.Opt, [])) # # The problem is that for selection lists, `get_inherited` returns a list of two-element lists like # [["value1", "Text 1"], ["value2", "Text 2"], ...] # This causes `join` to throw a TypeError because it expects an iterable of strings. # The horrible workaround is to patch `get_inherited` to return a list of the value strings. # We call the original method and adjust the return value only if the argument to `get_inherited` # is `FA.Opt` and if the return value is a list of two-element lists. def monkeypatch_pydpf_method(): from pypdf.generic import DictionaryObject from pypdf.constants import FieldDictionaryAttributes original_get_inherited = DictionaryObject.get_inherited def patched_get_inherited(self, key: str, default = None): result = original_get_inherited(self, key, default) if key == FieldDictionaryAttributes.Opt: if isinstance(result, list) and all(isinstance(v, list) and len(v) == 2 for v in result): result = [r[0] for r in result] return result DictionaryObject.get_inherited = patched_get_inherited if __name__ == "__main__": if len(sys.argv) != 4: print("Usage: fill_fillable_fields.py [input pdf] [field_values.json] [output pdf]") sys.exit(1) monkeypatch_pydpf_method() input_pdf = sys.argv[1] fields_json = sys.argv[2] output_pdf = sys.argv[3] fill_pdf_fields(input_pdf, fields_json, output_pdf)
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/pdf-official/scripts/fill_fillable_fields.py", "license": "MIT License", "lines": 94, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/document-processing/pdf-official/scripts/fill_pdf_form_with_annotations.py
import json import sys from pypdf import PdfReader, PdfWriter from pypdf.annotations import FreeText # Fills a PDF by adding text annotations defined in `fields.json`. See forms.md. def transform_coordinates(bbox, image_width, image_height, pdf_width, pdf_height): """Transform bounding box from image coordinates to PDF coordinates""" # Image coordinates: origin at top-left, y increases downward # PDF coordinates: origin at bottom-left, y increases upward x_scale = pdf_width / image_width y_scale = pdf_height / image_height left = bbox[0] * x_scale right = bbox[2] * x_scale # Flip Y coordinates for PDF top = pdf_height - (bbox[1] * y_scale) bottom = pdf_height - (bbox[3] * y_scale) return left, bottom, right, top def fill_pdf_form(input_pdf_path, fields_json_path, output_pdf_path): """Fill the PDF form with data from fields.json""" # `fields.json` format described in forms.md. with open(fields_json_path, "r") as f: fields_data = json.load(f) # Open the PDF reader = PdfReader(input_pdf_path) writer = PdfWriter() # Copy all pages to writer writer.append(reader) # Get PDF dimensions for each page pdf_dimensions = {} for i, page in enumerate(reader.pages): mediabox = page.mediabox pdf_dimensions[i + 1] = [mediabox.width, mediabox.height] # Process each form field annotations = [] for field in fields_data["form_fields"]: page_num = field["page_number"] # Get page dimensions and transform coordinates. page_info = next(p for p in fields_data["pages"] if p["page_number"] == page_num) image_width = page_info["image_width"] image_height = page_info["image_height"] pdf_width, pdf_height = pdf_dimensions[page_num] transformed_entry_box = transform_coordinates( field["entry_bounding_box"], image_width, image_height, pdf_width, pdf_height ) # Skip empty fields if "entry_text" not in field or "text" not in field["entry_text"]: continue entry_text = field["entry_text"] text = entry_text["text"] if not text: continue font_name = entry_text.get("font", "Arial") font_size = str(entry_text.get("font_size", 14)) + "pt" font_color = entry_text.get("font_color", "000000") # Font size/color seems to not work reliably across viewers: # https://github.com/py-pdf/pypdf/issues/2084 annotation = FreeText( text=text, rect=transformed_entry_box, font=font_name, font_size=font_size, font_color=font_color, border_color=None, background_color=None, ) annotations.append(annotation) # page_number is 0-based for pypdf writer.add_annotation(page_number=page_num - 1, annotation=annotation) # Save the filled PDF with open(output_pdf_path, "wb") as output: writer.write(output) print(f"Successfully filled PDF form and saved to {output_pdf_path}") print(f"Added {len(annotations)} text annotations") if __name__ == "__main__": if len(sys.argv) != 4: print("Usage: fill_pdf_form_with_annotations.py [input pdf] [fields.json] [output pdf]") sys.exit(1) input_pdf = sys.argv[1] fields_json = sys.argv[2] output_pdf = sys.argv[3] fill_pdf_form(input_pdf, fields_json, output_pdf)
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/pdf-official/scripts/fill_pdf_form_with_annotations.py", "license": "MIT License", "lines": 83, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/document-processing/pptx-official/scripts/inventory.py
#!/usr/bin/env python3 """ Extract structured text content from PowerPoint presentations. This module provides functionality to: - Extract all text content from PowerPoint shapes - Preserve paragraph formatting (alignment, bullets, fonts, spacing) - Handle nested GroupShapes recursively with correct absolute positions - Sort shapes by visual position on slides - Filter out slide numbers and non-content placeholders - Export to JSON with clean, structured data Classes: ParagraphData: Represents a text paragraph with formatting ShapeData: Represents a shape with position and text content Main Functions: extract_text_inventory: Extract all text from a presentation save_inventory: Save extracted data to JSON Usage: python inventory.py input.pptx output.json """ import argparse import json import platform import sys from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union from PIL import Image, ImageDraw, ImageFont from pptx import Presentation from pptx.enum.text import PP_ALIGN from pptx.shapes.base import BaseShape # Type aliases for cleaner signatures JsonValue = Union[str, int, float, bool, None] ParagraphDict = Dict[str, JsonValue] ShapeDict = Dict[ str, Union[str, float, bool, List[ParagraphDict], List[str], Dict[str, Any], None] ] InventoryData = Dict[ str, Dict[str, "ShapeData"] ] # Dict of slide_id -> {shape_id -> ShapeData} InventoryDict = Dict[str, Dict[str, ShapeDict]] # JSON-serializable inventory def main(): """Main entry point for command-line usage.""" parser = argparse.ArgumentParser( description="Extract text inventory from PowerPoint with proper GroupShape support.", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: python inventory.py presentation.pptx inventory.json Extracts text inventory with correct absolute positions for grouped shapes python inventory.py presentation.pptx inventory.json --issues-only Extracts only text shapes that have overflow or overlap issues The output JSON includes: - All text content organized by slide and shape - Correct absolute positions for shapes in groups - Visual position and size in inches - Paragraph properties and formatting - Issue detection: text overflow and shape overlaps """, ) parser.add_argument("input", help="Input PowerPoint file (.pptx)") parser.add_argument("output", help="Output JSON file for inventory") parser.add_argument( "--issues-only", action="store_true", help="Include only text shapes that have overflow or overlap issues", ) args = parser.parse_args() input_path = Path(args.input) if not input_path.exists(): print(f"Error: Input file not found: {args.input}") sys.exit(1) if not input_path.suffix.lower() == ".pptx": print("Error: Input must be a PowerPoint file (.pptx)") sys.exit(1) try: print(f"Extracting text inventory from: {args.input}") if args.issues_only: print( "Filtering to include only text shapes with issues (overflow/overlap)" ) inventory = extract_text_inventory(input_path, issues_only=args.issues_only) output_path = Path(args.output) output_path.parent.mkdir(parents=True, exist_ok=True) save_inventory(inventory, output_path) print(f"Output saved to: {args.output}") # Report statistics total_slides = len(inventory) total_shapes = sum(len(shapes) for shapes in inventory.values()) if args.issues_only: if total_shapes > 0: print( f"Found {total_shapes} text elements with issues in {total_slides} slides" ) else: print("No issues discovered") else: print( f"Found text in {total_slides} slides with {total_shapes} text elements" ) except Exception as e: print(f"Error processing presentation: {e}") import traceback traceback.print_exc() sys.exit(1) @dataclass class ShapeWithPosition: """A shape with its absolute position on the slide.""" shape: BaseShape absolute_left: int # in EMUs absolute_top: int # in EMUs class ParagraphData: """Data structure for paragraph properties extracted from a PowerPoint paragraph.""" def __init__(self, paragraph: Any): """Initialize from a PowerPoint paragraph object. Args: paragraph: The PowerPoint paragraph object """ self.text: str = paragraph.text.strip() self.bullet: bool = False self.level: Optional[int] = None self.alignment: Optional[str] = None self.space_before: Optional[float] = None self.space_after: Optional[float] = None self.font_name: Optional[str] = None self.font_size: Optional[float] = None self.bold: Optional[bool] = None self.italic: Optional[bool] = None self.underline: Optional[bool] = None self.color: Optional[str] = None self.theme_color: Optional[str] = None self.line_spacing: Optional[float] = None # Check for bullet formatting if ( hasattr(paragraph, "_p") and paragraph._p is not None and paragraph._p.pPr is not None ): pPr = paragraph._p.pPr ns = "{http://schemas.openxmlformats.org/drawingml/2006/main}" if ( pPr.find(f"{ns}buChar") is not None or pPr.find(f"{ns}buAutoNum") is not None ): self.bullet = True if hasattr(paragraph, "level"): self.level = paragraph.level # Add alignment if not LEFT (default) if hasattr(paragraph, "alignment") and paragraph.alignment is not None: alignment_map = { PP_ALIGN.CENTER: "CENTER", PP_ALIGN.RIGHT: "RIGHT", PP_ALIGN.JUSTIFY: "JUSTIFY", } if paragraph.alignment in alignment_map: self.alignment = alignment_map[paragraph.alignment] # Add spacing properties if set if hasattr(paragraph, "space_before") and paragraph.space_before: self.space_before = paragraph.space_before.pt if hasattr(paragraph, "space_after") and paragraph.space_after: self.space_after = paragraph.space_after.pt # Extract font properties from first run if paragraph.runs: first_run = paragraph.runs[0] if hasattr(first_run, "font"): font = first_run.font if font.name: self.font_name = font.name if font.size: self.font_size = font.size.pt if font.bold is not None: self.bold = font.bold if font.italic is not None: self.italic = font.italic if font.underline is not None: self.underline = font.underline # Handle color - both RGB and theme colors try: # Try RGB color first if font.color.rgb: self.color = str(font.color.rgb) except (AttributeError, TypeError): # Fall back to theme color try: if font.color.theme_color: self.theme_color = font.color.theme_color.name except (AttributeError, TypeError): pass # Add line spacing if set if hasattr(paragraph, "line_spacing") and paragraph.line_spacing is not None: if hasattr(paragraph.line_spacing, "pt"): self.line_spacing = round(paragraph.line_spacing.pt, 2) else: # Multiplier - convert to points font_size = self.font_size if self.font_size else 12.0 self.line_spacing = round(paragraph.line_spacing * font_size, 2) def to_dict(self) -> ParagraphDict: """Convert to dictionary for JSON serialization, excluding None values.""" result: ParagraphDict = {"text": self.text} # Add optional fields only if they have values if self.bullet: result["bullet"] = self.bullet if self.level is not None: result["level"] = self.level if self.alignment: result["alignment"] = self.alignment if self.space_before is not None: result["space_before"] = self.space_before if self.space_after is not None: result["space_after"] = self.space_after if self.font_name: result["font_name"] = self.font_name if self.font_size is not None: result["font_size"] = self.font_size if self.bold is not None: result["bold"] = self.bold if self.italic is not None: result["italic"] = self.italic if self.underline is not None: result["underline"] = self.underline if self.color: result["color"] = self.color if self.theme_color: result["theme_color"] = self.theme_color if self.line_spacing is not None: result["line_spacing"] = self.line_spacing return result class ShapeData: """Data structure for shape properties extracted from a PowerPoint shape.""" @staticmethod def emu_to_inches(emu: int) -> float: """Convert EMUs (English Metric Units) to inches.""" return emu / 914400.0 @staticmethod def inches_to_pixels(inches: float, dpi: int = 96) -> int: """Convert inches to pixels at given DPI.""" return int(inches * dpi) @staticmethod def get_font_path(font_name: str) -> Optional[str]: """Get the font file path for a given font name. Args: font_name: Name of the font (e.g., 'Arial', 'Calibri') Returns: Path to the font file, or None if not found """ system = platform.system() # Common font file variations to try font_variations = [ font_name, font_name.lower(), font_name.replace(" ", ""), font_name.replace(" ", "-"), ] # Define font directories and extensions by platform if system == "Darwin": # macOS font_dirs = [ "/System/Library/Fonts/", "/Library/Fonts/", "~/Library/Fonts/", ] extensions = [".ttf", ".otf", ".ttc", ".dfont"] else: # Linux font_dirs = [ "/usr/share/fonts/truetype/", "/usr/local/share/fonts/", "~/.fonts/", ] extensions = [".ttf", ".otf"] # Try to find the font file from pathlib import Path for font_dir in font_dirs: font_dir_path = Path(font_dir).expanduser() if not font_dir_path.exists(): continue # First try exact matches for variant in font_variations: for ext in extensions: font_path = font_dir_path / f"{variant}{ext}" if font_path.exists(): return str(font_path) # Then try fuzzy matching - find files containing the font name try: for file_path in font_dir_path.iterdir(): if file_path.is_file(): file_name_lower = file_path.name.lower() font_name_lower = font_name.lower().replace(" ", "") if font_name_lower in file_name_lower and any( file_name_lower.endswith(ext) for ext in extensions ): return str(file_path) except (OSError, PermissionError): continue return None @staticmethod def get_slide_dimensions(slide: Any) -> tuple[Optional[int], Optional[int]]: """Get slide dimensions from slide object. Args: slide: Slide object Returns: Tuple of (width_emu, height_emu) or (None, None) if not found """ try: prs = slide.part.package.presentation_part.presentation return prs.slide_width, prs.slide_height except (AttributeError, TypeError): return None, None @staticmethod def get_default_font_size(shape: BaseShape, slide_layout: Any) -> Optional[float]: """Extract default font size from slide layout for a placeholder shape. Args: shape: Placeholder shape slide_layout: Slide layout containing the placeholder definition Returns: Default font size in points, or None if not found """ try: if not hasattr(shape, "placeholder_format"): return None shape_type = shape.placeholder_format.type # type: ignore for layout_placeholder in slide_layout.placeholders: if layout_placeholder.placeholder_format.type == shape_type: # Find first defRPr element with sz (size) attribute for elem in layout_placeholder.element.iter(): if "defRPr" in elem.tag and (sz := elem.get("sz")): return float(sz) / 100.0 # Convert EMUs to points break except Exception: pass return None def __init__( self, shape: BaseShape, absolute_left: Optional[int] = None, absolute_top: Optional[int] = None, slide: Optional[Any] = None, ): """Initialize from a PowerPoint shape object. Args: shape: The PowerPoint shape object (should be pre-validated) absolute_left: Absolute left position in EMUs (for shapes in groups) absolute_top: Absolute top position in EMUs (for shapes in groups) slide: Optional slide object to get dimensions and layout information """ self.shape = shape # Store reference to original shape self.shape_id: str = "" # Will be set after sorting # Get slide dimensions from slide object self.slide_width_emu, self.slide_height_emu = ( self.get_slide_dimensions(slide) if slide else (None, None) ) # Get placeholder type if applicable self.placeholder_type: Optional[str] = None self.default_font_size: Optional[float] = None if hasattr(shape, "is_placeholder") and shape.is_placeholder: # type: ignore if shape.placeholder_format and shape.placeholder_format.type: # type: ignore self.placeholder_type = ( str(shape.placeholder_format.type).split(".")[-1].split(" ")[0] # type: ignore ) # Get default font size from layout if slide and hasattr(slide, "slide_layout"): self.default_font_size = self.get_default_font_size( shape, slide.slide_layout ) # Get position information # Use absolute positions if provided (for shapes in groups), otherwise use shape's position left_emu = ( absolute_left if absolute_left is not None else (shape.left if hasattr(shape, "left") else 0) ) top_emu = ( absolute_top if absolute_top is not None else (shape.top if hasattr(shape, "top") else 0) ) self.left: float = round(self.emu_to_inches(left_emu), 2) # type: ignore self.top: float = round(self.emu_to_inches(top_emu), 2) # type: ignore self.width: float = round( self.emu_to_inches(shape.width if hasattr(shape, "width") else 0), 2, # type: ignore ) self.height: float = round( self.emu_to_inches(shape.height if hasattr(shape, "height") else 0), 2, # type: ignore ) # Store EMU positions for overflow calculations self.left_emu = left_emu self.top_emu = top_emu self.width_emu = shape.width if hasattr(shape, "width") else 0 self.height_emu = shape.height if hasattr(shape, "height") else 0 # Calculate overflow status self.frame_overflow_bottom: Optional[float] = None self.slide_overflow_right: Optional[float] = None self.slide_overflow_bottom: Optional[float] = None self.overlapping_shapes: Dict[ str, float ] = {} # Dict of shape_id -> overlap area in sq inches self.warnings: List[str] = [] self._estimate_frame_overflow() self._calculate_slide_overflow() self._detect_bullet_issues() @property def paragraphs(self) -> List[ParagraphData]: """Calculate paragraphs from the shape's text frame.""" if not self.shape or not hasattr(self.shape, "text_frame"): return [] paragraphs = [] for paragraph in self.shape.text_frame.paragraphs: # type: ignore if paragraph.text.strip(): paragraphs.append(ParagraphData(paragraph)) return paragraphs def _get_default_font_size(self) -> int: """Get default font size from theme text styles or use conservative default.""" try: if not ( hasattr(self.shape, "part") and hasattr(self.shape.part, "slide_layout") ): return 14 slide_master = self.shape.part.slide_layout.slide_master # type: ignore if not hasattr(slide_master, "element"): return 14 # Determine theme style based on placeholder type style_name = "bodyStyle" # Default if self.placeholder_type and "TITLE" in self.placeholder_type: style_name = "titleStyle" # Find font size in theme styles for child in slide_master.element.iter(): tag = child.tag.split("}")[-1] if "}" in child.tag else child.tag if tag == style_name: for elem in child.iter(): if "sz" in elem.attrib: return int(elem.attrib["sz"]) // 100 except Exception: pass return 14 # Conservative default for body text def _get_usable_dimensions(self, text_frame) -> Tuple[int, int]: """Get usable width and height in pixels after accounting for margins.""" # Default PowerPoint margins in inches margins = {"top": 0.05, "bottom": 0.05, "left": 0.1, "right": 0.1} # Override with actual margins if set if hasattr(text_frame, "margin_top") and text_frame.margin_top: margins["top"] = self.emu_to_inches(text_frame.margin_top) if hasattr(text_frame, "margin_bottom") and text_frame.margin_bottom: margins["bottom"] = self.emu_to_inches(text_frame.margin_bottom) if hasattr(text_frame, "margin_left") and text_frame.margin_left: margins["left"] = self.emu_to_inches(text_frame.margin_left) if hasattr(text_frame, "margin_right") and text_frame.margin_right: margins["right"] = self.emu_to_inches(text_frame.margin_right) # Calculate usable area usable_width = self.width - margins["left"] - margins["right"] usable_height = self.height - margins["top"] - margins["bottom"] # Convert to pixels return ( self.inches_to_pixels(usable_width), self.inches_to_pixels(usable_height), ) def _wrap_text_line(self, line: str, max_width_px: int, draw, font) -> List[str]: """Wrap a single line of text to fit within max_width_px.""" if not line: return [""] # Use textlength for efficient width calculation if draw.textlength(line, font=font) <= max_width_px: return [line] # Need to wrap - split into words wrapped = [] words = line.split(" ") current_line = "" for word in words: test_line = current_line + (" " if current_line else "") + word if draw.textlength(test_line, font=font) <= max_width_px: current_line = test_line else: if current_line: wrapped.append(current_line) current_line = word if current_line: wrapped.append(current_line) return wrapped def _estimate_frame_overflow(self) -> None: """Estimate if text overflows the shape bounds using PIL text measurement.""" if not self.shape or not hasattr(self.shape, "text_frame"): return text_frame = self.shape.text_frame # type: ignore if not text_frame or not text_frame.paragraphs: return # Get usable dimensions after accounting for margins usable_width_px, usable_height_px = self._get_usable_dimensions(text_frame) if usable_width_px <= 0 or usable_height_px <= 0: return # Set up PIL for text measurement dummy_img = Image.new("RGB", (1, 1)) draw = ImageDraw.Draw(dummy_img) # Get default font size from placeholder or use conservative estimate default_font_size = self._get_default_font_size() # Calculate total height of all paragraphs total_height_px = 0 for para_idx, paragraph in enumerate(text_frame.paragraphs): if not paragraph.text.strip(): continue para_data = ParagraphData(paragraph) # Load font for this paragraph font_name = para_data.font_name or "Arial" font_size = int(para_data.font_size or default_font_size) font = None font_path = self.get_font_path(font_name) if font_path: try: font = ImageFont.truetype(font_path, size=font_size) except Exception: font = ImageFont.load_default() else: font = ImageFont.load_default() # Wrap all lines in this paragraph all_wrapped_lines = [] for line in paragraph.text.split("\n"): wrapped = self._wrap_text_line(line, usable_width_px, draw, font) all_wrapped_lines.extend(wrapped) if all_wrapped_lines: # Calculate line height if para_data.line_spacing: # Custom line spacing explicitly set line_height_px = para_data.line_spacing * 96 / 72 else: # PowerPoint default single spacing (1.0x font size) line_height_px = font_size * 96 / 72 # Add space_before (except first paragraph) if para_idx > 0 and para_data.space_before: total_height_px += para_data.space_before * 96 / 72 # Add paragraph text height total_height_px += len(all_wrapped_lines) * line_height_px # Add space_after if para_data.space_after: total_height_px += para_data.space_after * 96 / 72 # Check for overflow (ignore negligible overflows <= 0.05") if total_height_px > usable_height_px: overflow_px = total_height_px - usable_height_px overflow_inches = round(overflow_px / 96.0, 2) if overflow_inches > 0.05: # Only report significant overflows self.frame_overflow_bottom = overflow_inches def _calculate_slide_overflow(self) -> None: """Calculate if shape overflows the slide boundaries.""" if self.slide_width_emu is None or self.slide_height_emu is None: return # Check right overflow (ignore negligible overflows <= 0.01") right_edge_emu = self.left_emu + self.width_emu if right_edge_emu > self.slide_width_emu: overflow_emu = right_edge_emu - self.slide_width_emu overflow_inches = round(self.emu_to_inches(overflow_emu), 2) if overflow_inches > 0.01: # Only report significant overflows self.slide_overflow_right = overflow_inches # Check bottom overflow (ignore negligible overflows <= 0.01") bottom_edge_emu = self.top_emu + self.height_emu if bottom_edge_emu > self.slide_height_emu: overflow_emu = bottom_edge_emu - self.slide_height_emu overflow_inches = round(self.emu_to_inches(overflow_emu), 2) if overflow_inches > 0.01: # Only report significant overflows self.slide_overflow_bottom = overflow_inches def _detect_bullet_issues(self) -> None: """Detect bullet point formatting issues in paragraphs.""" if not self.shape or not hasattr(self.shape, "text_frame"): return text_frame = self.shape.text_frame # type: ignore if not text_frame or not text_frame.paragraphs: return # Common bullet symbols that indicate manual bullets bullet_symbols = ["•", "●", "○"] for paragraph in text_frame.paragraphs: text = paragraph.text.strip() # Check for manual bullet symbols if text and any(text.startswith(symbol + " ") for symbol in bullet_symbols): self.warnings.append( "manual_bullet_symbol: use proper bullet formatting" ) break @property def has_any_issues(self) -> bool: """Check if shape has any issues (overflow, overlap, or warnings).""" return ( self.frame_overflow_bottom is not None or self.slide_overflow_right is not None or self.slide_overflow_bottom is not None or len(self.overlapping_shapes) > 0 or len(self.warnings) > 0 ) def to_dict(self) -> ShapeDict: """Convert to dictionary for JSON serialization.""" result: ShapeDict = { "left": self.left, "top": self.top, "width": self.width, "height": self.height, } # Add optional fields if present if self.placeholder_type: result["placeholder_type"] = self.placeholder_type if self.default_font_size: result["default_font_size"] = self.default_font_size # Add overflow information only if there is overflow overflow_data = {} # Add frame overflow if present if self.frame_overflow_bottom is not None: overflow_data["frame"] = {"overflow_bottom": self.frame_overflow_bottom} # Add slide overflow if present slide_overflow = {} if self.slide_overflow_right is not None: slide_overflow["overflow_right"] = self.slide_overflow_right if self.slide_overflow_bottom is not None: slide_overflow["overflow_bottom"] = self.slide_overflow_bottom if slide_overflow: overflow_data["slide"] = slide_overflow # Only add overflow field if there is overflow if overflow_data: result["overflow"] = overflow_data # Add overlap field if there are overlapping shapes if self.overlapping_shapes: result["overlap"] = {"overlapping_shapes": self.overlapping_shapes} # Add warnings field if there are warnings if self.warnings: result["warnings"] = self.warnings # Add paragraphs after placeholder_type result["paragraphs"] = [para.to_dict() for para in self.paragraphs] return result def is_valid_shape(shape: BaseShape) -> bool: """Check if a shape contains meaningful text content.""" # Must have a text frame with content if not hasattr(shape, "text_frame") or not shape.text_frame: # type: ignore return False text = shape.text_frame.text.strip() # type: ignore if not text: return False # Skip slide numbers and numeric footers if hasattr(shape, "is_placeholder") and shape.is_placeholder: # type: ignore if shape.placeholder_format and shape.placeholder_format.type: # type: ignore placeholder_type = ( str(shape.placeholder_format.type).split(".")[-1].split(" ")[0] # type: ignore ) if placeholder_type == "SLIDE_NUMBER": return False if placeholder_type == "FOOTER" and text.isdigit(): return False return True def collect_shapes_with_absolute_positions( shape: BaseShape, parent_left: int = 0, parent_top: int = 0 ) -> List[ShapeWithPosition]: """Recursively collect all shapes with valid text, calculating absolute positions. For shapes within groups, their positions are relative to the group. This function calculates the absolute position on the slide by accumulating parent group offsets. Args: shape: The shape to process parent_left: Accumulated left offset from parent groups (in EMUs) parent_top: Accumulated top offset from parent groups (in EMUs) Returns: List of ShapeWithPosition objects with absolute positions """ if hasattr(shape, "shapes"): # GroupShape result = [] # Get this group's position group_left = shape.left if hasattr(shape, "left") else 0 group_top = shape.top if hasattr(shape, "top") else 0 # Calculate absolute position for this group abs_group_left = parent_left + group_left abs_group_top = parent_top + group_top # Process children with accumulated offsets for child in shape.shapes: # type: ignore result.extend( collect_shapes_with_absolute_positions( child, abs_group_left, abs_group_top ) ) return result # Regular shape - check if it has valid text if is_valid_shape(shape): # Calculate absolute position shape_left = shape.left if hasattr(shape, "left") else 0 shape_top = shape.top if hasattr(shape, "top") else 0 return [ ShapeWithPosition( shape=shape, absolute_left=parent_left + shape_left, absolute_top=parent_top + shape_top, ) ] return [] def sort_shapes_by_position(shapes: List[ShapeData]) -> List[ShapeData]: """Sort shapes by visual position (top-to-bottom, left-to-right). Shapes within 0.5 inches vertically are considered on the same row. """ if not shapes: return shapes # Sort by top position first shapes = sorted(shapes, key=lambda s: (s.top, s.left)) # Group shapes by row (within 0.5 inches vertically) result = [] row = [shapes[0]] row_top = shapes[0].top for shape in shapes[1:]: if abs(shape.top - row_top) <= 0.5: row.append(shape) else: # Sort current row by left position and add to result result.extend(sorted(row, key=lambda s: s.left)) row = [shape] row_top = shape.top # Don't forget the last row result.extend(sorted(row, key=lambda s: s.left)) return result def calculate_overlap( rect1: Tuple[float, float, float, float], rect2: Tuple[float, float, float, float], tolerance: float = 0.05, ) -> Tuple[bool, float]: """Calculate if and how much two rectangles overlap. Args: rect1: (left, top, width, height) of first rectangle in inches rect2: (left, top, width, height) of second rectangle in inches tolerance: Minimum overlap in inches to consider as overlapping (default: 0.05") Returns: Tuple of (overlaps, overlap_area) where: - overlaps: True if rectangles overlap by more than tolerance - overlap_area: Area of overlap in square inches """ left1, top1, w1, h1 = rect1 left2, top2, w2, h2 = rect2 # Calculate overlap dimensions overlap_width = min(left1 + w1, left2 + w2) - max(left1, left2) overlap_height = min(top1 + h1, top2 + h2) - max(top1, top2) # Check if there's meaningful overlap (more than tolerance) if overlap_width > tolerance and overlap_height > tolerance: # Calculate overlap area in square inches overlap_area = overlap_width * overlap_height return True, round(overlap_area, 2) return False, 0 def detect_overlaps(shapes: List[ShapeData]) -> None: """Detect overlapping shapes and update their overlapping_shapes dictionaries. This function requires each ShapeData to have its shape_id already set. It modifies the shapes in-place, adding shape IDs with overlap areas in square inches. Args: shapes: List of ShapeData objects with shape_id attributes set """ n = len(shapes) # Compare each pair of shapes for i in range(n): for j in range(i + 1, n): shape1 = shapes[i] shape2 = shapes[j] # Ensure shape IDs are set assert shape1.shape_id, f"Shape at index {i} has no shape_id" assert shape2.shape_id, f"Shape at index {j} has no shape_id" rect1 = (shape1.left, shape1.top, shape1.width, shape1.height) rect2 = (shape2.left, shape2.top, shape2.width, shape2.height) overlaps, overlap_area = calculate_overlap(rect1, rect2) if overlaps: # Add shape IDs with overlap area in square inches shape1.overlapping_shapes[shape2.shape_id] = overlap_area shape2.overlapping_shapes[shape1.shape_id] = overlap_area def extract_text_inventory( pptx_path: Path, prs: Optional[Any] = None, issues_only: bool = False ) -> InventoryData: """Extract text content from all slides in a PowerPoint presentation. Args: pptx_path: Path to the PowerPoint file prs: Optional Presentation object to use. If not provided, will load from pptx_path. issues_only: If True, only include shapes that have overflow or overlap issues Returns a nested dictionary: {slide-N: {shape-N: ShapeData}} Shapes are sorted by visual position (top-to-bottom, left-to-right). The ShapeData objects contain the full shape information and can be converted to dictionaries for JSON serialization using to_dict(). """ if prs is None: prs = Presentation(str(pptx_path)) inventory: InventoryData = {} for slide_idx, slide in enumerate(prs.slides): # Collect all valid shapes from this slide with absolute positions shapes_with_positions = [] for shape in slide.shapes: # type: ignore shapes_with_positions.extend(collect_shapes_with_absolute_positions(shape)) if not shapes_with_positions: continue # Convert to ShapeData with absolute positions and slide reference shape_data_list = [ ShapeData( swp.shape, swp.absolute_left, swp.absolute_top, slide, ) for swp in shapes_with_positions ] # Sort by visual position and assign stable IDs in one step sorted_shapes = sort_shapes_by_position(shape_data_list) for idx, shape_data in enumerate(sorted_shapes): shape_data.shape_id = f"shape-{idx}" # Detect overlaps using the stable shape IDs if len(sorted_shapes) > 1: detect_overlaps(sorted_shapes) # Filter for issues only if requested (after overlap detection) if issues_only: sorted_shapes = [sd for sd in sorted_shapes if sd.has_any_issues] if not sorted_shapes: continue # Create slide inventory using the stable shape IDs inventory[f"slide-{slide_idx}"] = { shape_data.shape_id: shape_data for shape_data in sorted_shapes } return inventory def get_inventory_as_dict(pptx_path: Path, issues_only: bool = False) -> InventoryDict: """Extract text inventory and return as JSON-serializable dictionaries. This is a convenience wrapper around extract_text_inventory that returns dictionaries instead of ShapeData objects, useful for testing and direct JSON serialization. Args: pptx_path: Path to the PowerPoint file issues_only: If True, only include shapes that have overflow or overlap issues Returns: Nested dictionary with all data serialized for JSON """ inventory = extract_text_inventory(pptx_path, issues_only=issues_only) # Convert ShapeData objects to dictionaries dict_inventory: InventoryDict = {} for slide_key, shapes in inventory.items(): dict_inventory[slide_key] = { shape_key: shape_data.to_dict() for shape_key, shape_data in shapes.items() } return dict_inventory def save_inventory(inventory: InventoryData, output_path: Path) -> None: """Save inventory to JSON file with proper formatting. Converts ShapeData objects to dictionaries for JSON serialization. """ # Convert ShapeData objects to dictionaries json_inventory: InventoryDict = {} for slide_key, shapes in inventory.items(): json_inventory[slide_key] = { shape_key: shape_data.to_dict() for shape_key, shape_data in shapes.items() } with open(output_path, "w", encoding="utf-8") as f: json.dump(json_inventory, f, indent=2, ensure_ascii=False) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/pptx-official/scripts/inventory.py", "license": "MIT License", "lines": 837, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/document-processing/pptx-official/scripts/rearrange.py
#!/usr/bin/env python3 """ Rearrange PowerPoint slides based on a sequence of indices. Usage: python rearrange.py template.pptx output.pptx 0,34,34,50,52 This will create output.pptx using slides from template.pptx in the specified order. Slides can be repeated (e.g., 34 appears twice). """ import argparse import shutil import sys from copy import deepcopy from pathlib import Path import six from pptx import Presentation def main(): parser = argparse.ArgumentParser( description="Rearrange PowerPoint slides based on a sequence of indices.", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: python rearrange.py template.pptx output.pptx 0,34,34,50,52 Creates output.pptx using slides 0, 34 (twice), 50, and 52 from template.pptx python rearrange.py template.pptx output.pptx 5,3,1,2,4 Creates output.pptx with slides reordered as specified Note: Slide indices are 0-based (first slide is 0, second is 1, etc.) """, ) parser.add_argument("template", help="Path to template PPTX file") parser.add_argument("output", help="Path for output PPTX file") parser.add_argument( "sequence", help="Comma-separated sequence of slide indices (0-based)" ) args = parser.parse_args() # Parse the slide sequence try: slide_sequence = [int(x.strip()) for x in args.sequence.split(",")] except ValueError: print( "Error: Invalid sequence format. Use comma-separated integers (e.g., 0,34,34,50,52)" ) sys.exit(1) # Check template exists template_path = Path(args.template) if not template_path.exists(): print(f"Error: Template file not found: {args.template}") sys.exit(1) # Create output directory if needed output_path = Path(args.output) output_path.parent.mkdir(parents=True, exist_ok=True) try: rearrange_presentation(template_path, output_path, slide_sequence) except ValueError as e: print(f"Error: {e}") sys.exit(1) except Exception as e: print(f"Error processing presentation: {e}") sys.exit(1) def duplicate_slide(pres, index): """Duplicate a slide in the presentation.""" source = pres.slides[index] # Use source's layout to preserve formatting new_slide = pres.slides.add_slide(source.slide_layout) # Collect all image and media relationships from the source slide image_rels = {} for rel_id, rel in six.iteritems(source.part.rels): if "image" in rel.reltype or "media" in rel.reltype: image_rels[rel_id] = rel # CRITICAL: Clear placeholder shapes to avoid duplicates for shape in new_slide.shapes: sp = shape.element sp.getparent().remove(sp) # Copy all shapes from source for shape in source.shapes: el = shape.element new_el = deepcopy(el) new_slide.shapes._spTree.insert_element_before(new_el, "p:extLst") # Handle picture shapes - need to update the blip reference # Look for all blip elements (they can be in pic or other contexts) # Using the element's own xpath method without namespaces argument blips = new_el.xpath(".//a:blip[@r:embed]") for blip in blips: old_rId = blip.get( "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed" ) if old_rId in image_rels: # Create a new relationship in the destination slide for this image old_rel = image_rels[old_rId] # get_or_add returns the rId directly, or adds and returns new rId new_rId = new_slide.part.rels.get_or_add( old_rel.reltype, old_rel._target ) # Update the blip's embed reference to use the new relationship ID blip.set( "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed", new_rId, ) # Copy any additional image/media relationships that might be referenced elsewhere for rel_id, rel in image_rels.items(): try: new_slide.part.rels.get_or_add(rel.reltype, rel._target) except Exception: pass # Relationship might already exist return new_slide def delete_slide(pres, index): """Delete a slide from the presentation.""" rId = pres.slides._sldIdLst[index].rId pres.part.drop_rel(rId) del pres.slides._sldIdLst[index] def reorder_slides(pres, slide_index, target_index): """Move a slide from one position to another.""" slides = pres.slides._sldIdLst # Remove slide element from current position slide_element = slides[slide_index] slides.remove(slide_element) # Insert at target position slides.insert(target_index, slide_element) def rearrange_presentation(template_path, output_path, slide_sequence): """ Create a new presentation with slides from template in specified order. Args: template_path: Path to template PPTX file output_path: Path for output PPTX file slide_sequence: List of slide indices (0-based) to include """ # Copy template to preserve dimensions and theme if template_path != output_path: shutil.copy2(template_path, output_path) prs = Presentation(output_path) else: prs = Presentation(template_path) total_slides = len(prs.slides) # Validate indices for idx in slide_sequence: if idx < 0 or idx >= total_slides: raise ValueError(f"Slide index {idx} out of range (0-{total_slides - 1})") # Track original slides and their duplicates slide_map = [] # List of actual slide indices for final presentation duplicated = {} # Track duplicates: original_idx -> [duplicate_indices] # Step 1: DUPLICATE repeated slides print(f"Processing {len(slide_sequence)} slides from template...") for i, template_idx in enumerate(slide_sequence): if template_idx in duplicated and duplicated[template_idx]: # Already duplicated this slide, use the duplicate slide_map.append(duplicated[template_idx].pop(0)) print(f" [{i}] Using duplicate of slide {template_idx}") elif slide_sequence.count(template_idx) > 1 and template_idx not in duplicated: # First occurrence of a repeated slide - create duplicates slide_map.append(template_idx) duplicates = [] count = slide_sequence.count(template_idx) - 1 print( f" [{i}] Using original slide {template_idx}, creating {count} duplicate(s)" ) for _ in range(count): duplicate_slide(prs, template_idx) duplicates.append(len(prs.slides) - 1) duplicated[template_idx] = duplicates else: # Unique slide or first occurrence already handled, use original slide_map.append(template_idx) print(f" [{i}] Using original slide {template_idx}") # Step 2: DELETE unwanted slides (work backwards) slides_to_keep = set(slide_map) print(f"\nDeleting {len(prs.slides) - len(slides_to_keep)} unused slides...") for i in range(len(prs.slides) - 1, -1, -1): if i not in slides_to_keep: delete_slide(prs, i) # Update slide_map indices after deletion slide_map = [idx - 1 if idx > i else idx for idx in slide_map] # Step 3: REORDER to final sequence print(f"Reordering {len(slide_map)} slides to final sequence...") for target_pos in range(len(slide_map)): # Find which slide should be at target_pos current_pos = slide_map[target_pos] if current_pos != target_pos: reorder_slides(prs, current_pos, target_pos) # Update slide_map: the move shifts other slides for i in range(len(slide_map)): if slide_map[i] > current_pos and slide_map[i] <= target_pos: slide_map[i] -= 1 elif slide_map[i] < current_pos and slide_map[i] >= target_pos: slide_map[i] += 1 slide_map[target_pos] = target_pos # Save the presentation prs.save(output_path) print(f"\nSaved rearranged presentation to: {output_path}") print(f"Final presentation has {len(prs.slides)} slides") if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/pptx-official/scripts/rearrange.py", "license": "MIT License", "lines": 190, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/document-processing/pptx-official/scripts/replace.py
#!/usr/bin/env python3 """Apply text replacements to PowerPoint presentation. Usage: python replace.py <input.pptx> <replacements.json> <output.pptx> The replacements JSON should have the structure output by inventory.py. ALL text shapes identified by inventory.py will have their text cleared unless "paragraphs" is specified in the replacements for that shape. """ import json import sys from pathlib import Path from typing import Any, Dict, List from inventory import InventoryData, extract_text_inventory from pptx import Presentation from pptx.dml.color import RGBColor from pptx.enum.dml import MSO_THEME_COLOR from pptx.enum.text import PP_ALIGN from pptx.oxml.xmlchemy import OxmlElement from pptx.util import Pt def clear_paragraph_bullets(paragraph): """Clear bullet formatting from a paragraph.""" pPr = paragraph._element.get_or_add_pPr() # Remove existing bullet elements for child in list(pPr): if ( child.tag.endswith("buChar") or child.tag.endswith("buNone") or child.tag.endswith("buAutoNum") or child.tag.endswith("buFont") ): pPr.remove(child) return pPr def apply_paragraph_properties(paragraph, para_data: Dict[str, Any]): """Apply formatting properties to a paragraph.""" # Get the text but don't set it on paragraph directly yet text = para_data.get("text", "") # Get or create paragraph properties pPr = clear_paragraph_bullets(paragraph) # Handle bullet formatting if para_data.get("bullet", False): level = para_data.get("level", 0) paragraph.level = level # Calculate font-proportional indentation font_size = para_data.get("font_size", 18.0) level_indent_emu = int((font_size * (1.6 + level * 1.6)) * 12700) hanging_indent_emu = int(-font_size * 0.8 * 12700) # Set indentation pPr.attrib["marL"] = str(level_indent_emu) pPr.attrib["indent"] = str(hanging_indent_emu) # Add bullet character buChar = OxmlElement("a:buChar") buChar.set("char", "•") pPr.append(buChar) # Default to left alignment for bullets if not specified if "alignment" not in para_data: paragraph.alignment = PP_ALIGN.LEFT else: # Remove indentation for non-bullet text pPr.attrib["marL"] = "0" pPr.attrib["indent"] = "0" # Add buNone element buNone = OxmlElement("a:buNone") pPr.insert(0, buNone) # Apply alignment if "alignment" in para_data: alignment_map = { "LEFT": PP_ALIGN.LEFT, "CENTER": PP_ALIGN.CENTER, "RIGHT": PP_ALIGN.RIGHT, "JUSTIFY": PP_ALIGN.JUSTIFY, } if para_data["alignment"] in alignment_map: paragraph.alignment = alignment_map[para_data["alignment"]] # Apply spacing if "space_before" in para_data: paragraph.space_before = Pt(para_data["space_before"]) if "space_after" in para_data: paragraph.space_after = Pt(para_data["space_after"]) if "line_spacing" in para_data: paragraph.line_spacing = Pt(para_data["line_spacing"]) # Apply run-level formatting if not paragraph.runs: run = paragraph.add_run() run.text = text else: run = paragraph.runs[0] run.text = text # Apply font properties apply_font_properties(run, para_data) def apply_font_properties(run, para_data: Dict[str, Any]): """Apply font properties to a text run.""" if "bold" in para_data: run.font.bold = para_data["bold"] if "italic" in para_data: run.font.italic = para_data["italic"] if "underline" in para_data: run.font.underline = para_data["underline"] if "font_size" in para_data: run.font.size = Pt(para_data["font_size"]) if "font_name" in para_data: run.font.name = para_data["font_name"] # Apply color - prefer RGB, fall back to theme_color if "color" in para_data: color_hex = para_data["color"].lstrip("#") if len(color_hex) == 6: r = int(color_hex[0:2], 16) g = int(color_hex[2:4], 16) b = int(color_hex[4:6], 16) run.font.color.rgb = RGBColor(r, g, b) elif "theme_color" in para_data: # Get theme color by name (e.g., "DARK_1", "ACCENT_1") theme_name = para_data["theme_color"] try: run.font.color.theme_color = getattr(MSO_THEME_COLOR, theme_name) except AttributeError: print(f" WARNING: Unknown theme color name '{theme_name}'") def detect_frame_overflow(inventory: InventoryData) -> Dict[str, Dict[str, float]]: """Detect text overflow in shapes (text exceeding shape bounds). Returns dict of slide_key -> shape_key -> overflow_inches. Only includes shapes that have text overflow. """ overflow_map = {} for slide_key, shapes_dict in inventory.items(): for shape_key, shape_data in shapes_dict.items(): # Check for frame overflow (text exceeding shape bounds) if shape_data.frame_overflow_bottom is not None: if slide_key not in overflow_map: overflow_map[slide_key] = {} overflow_map[slide_key][shape_key] = shape_data.frame_overflow_bottom return overflow_map def validate_replacements(inventory: InventoryData, replacements: Dict) -> List[str]: """Validate that all shapes in replacements exist in inventory. Returns list of error messages. """ errors = [] for slide_key, shapes_data in replacements.items(): if not slide_key.startswith("slide-"): continue # Check if slide exists if slide_key not in inventory: errors.append(f"Slide '{slide_key}' not found in inventory") continue # Check each shape for shape_key in shapes_data.keys(): if shape_key not in inventory[slide_key]: # Find shapes without replacements defined and show their content unused_with_content = [] for k in inventory[slide_key].keys(): if k not in shapes_data: shape_data = inventory[slide_key][k] # Get text from paragraphs as preview paragraphs = shape_data.paragraphs if paragraphs and paragraphs[0].text: first_text = paragraphs[0].text[:50] if len(paragraphs[0].text) > 50: first_text += "..." unused_with_content.append(f"{k} ('{first_text}')") else: unused_with_content.append(k) errors.append( f"Shape '{shape_key}' not found on '{slide_key}'. " f"Shapes without replacements: {', '.join(sorted(unused_with_content)) if unused_with_content else 'none'}" ) return errors def check_duplicate_keys(pairs): """Check for duplicate keys when loading JSON.""" result = {} for key, value in pairs: if key in result: raise ValueError(f"Duplicate key found in JSON: '{key}'") result[key] = value return result def apply_replacements(pptx_file: str, json_file: str, output_file: str): """Apply text replacements from JSON to PowerPoint presentation.""" # Load presentation prs = Presentation(pptx_file) # Get inventory of all text shapes (returns ShapeData objects) # Pass prs to use same Presentation instance inventory = extract_text_inventory(Path(pptx_file), prs) # Detect text overflow in original presentation original_overflow = detect_frame_overflow(inventory) # Load replacement data with duplicate key detection with open(json_file, "r") as f: replacements = json.load(f, object_pairs_hook=check_duplicate_keys) # Validate replacements errors = validate_replacements(inventory, replacements) if errors: print("ERROR: Invalid shapes in replacement JSON:") for error in errors: print(f" - {error}") print("\nPlease check the inventory and update your replacement JSON.") print( "You can regenerate the inventory with: python inventory.py <input.pptx> <output.json>" ) raise ValueError(f"Found {len(errors)} validation error(s)") # Track statistics shapes_processed = 0 shapes_cleared = 0 shapes_replaced = 0 # Process each slide from inventory for slide_key, shapes_dict in inventory.items(): if not slide_key.startswith("slide-"): continue slide_index = int(slide_key.split("-")[1]) if slide_index >= len(prs.slides): print(f"Warning: Slide {slide_index} not found") continue # Process each shape from inventory for shape_key, shape_data in shapes_dict.items(): shapes_processed += 1 # Get the shape directly from ShapeData shape = shape_data.shape if not shape: print(f"Warning: {shape_key} has no shape reference") continue # ShapeData already validates text_frame in __init__ text_frame = shape.text_frame # type: ignore text_frame.clear() # type: ignore shapes_cleared += 1 # Check for replacement paragraphs replacement_shape_data = replacements.get(slide_key, {}).get(shape_key, {}) if "paragraphs" not in replacement_shape_data: continue shapes_replaced += 1 # Add replacement paragraphs for i, para_data in enumerate(replacement_shape_data["paragraphs"]): if i == 0: p = text_frame.paragraphs[0] # type: ignore else: p = text_frame.add_paragraph() # type: ignore apply_paragraph_properties(p, para_data) # Check for issues after replacements # Save to a temporary file and reload to avoid modifying the presentation during inventory # (extract_text_inventory accesses font.color which adds empty <a:solidFill/> elements) import tempfile with tempfile.NamedTemporaryFile(suffix=".pptx", delete=False) as tmp: tmp_path = Path(tmp.name) prs.save(str(tmp_path)) try: updated_inventory = extract_text_inventory(tmp_path) updated_overflow = detect_frame_overflow(updated_inventory) finally: tmp_path.unlink() # Clean up temp file # Check if any text overflow got worse overflow_errors = [] for slide_key, shape_overflows in updated_overflow.items(): for shape_key, new_overflow in shape_overflows.items(): # Get original overflow (0 if there was no overflow before) original = original_overflow.get(slide_key, {}).get(shape_key, 0.0) # Error if overflow increased if new_overflow > original + 0.01: # Small tolerance for rounding increase = new_overflow - original overflow_errors.append( f'{slide_key}/{shape_key}: overflow worsened by {increase:.2f}" ' f'(was {original:.2f}", now {new_overflow:.2f}")' ) # Collect warnings from updated shapes warnings = [] for slide_key, shapes_dict in updated_inventory.items(): for shape_key, shape_data in shapes_dict.items(): if shape_data.warnings: for warning in shape_data.warnings: warnings.append(f"{slide_key}/{shape_key}: {warning}") # Fail if there are any issues if overflow_errors or warnings: print("\nERROR: Issues detected in replacement output:") if overflow_errors: print("\nText overflow worsened:") for error in overflow_errors: print(f" - {error}") if warnings: print("\nFormatting warnings:") for warning in warnings: print(f" - {warning}") print("\nPlease fix these issues before saving.") raise ValueError( f"Found {len(overflow_errors)} overflow error(s) and {len(warnings)} warning(s)" ) # Save the presentation prs.save(output_file) # Report results print(f"Saved updated presentation to: {output_file}") print(f"Processed {len(prs.slides)} slides") print(f" - Shapes processed: {shapes_processed}") print(f" - Shapes cleared: {shapes_cleared}") print(f" - Shapes replaced: {shapes_replaced}") def main(): """Main entry point for command-line usage.""" if len(sys.argv) != 4: print(__doc__) sys.exit(1) input_pptx = Path(sys.argv[1]) replacements_json = Path(sys.argv[2]) output_pptx = Path(sys.argv[3]) if not input_pptx.exists(): print(f"Error: Input file '{input_pptx}' not found") sys.exit(1) if not replacements_json.exists(): print(f"Error: Replacements JSON file '{replacements_json}' not found") sys.exit(1) try: apply_replacements(str(input_pptx), str(replacements_json), str(output_pptx)) except Exception as e: print(f"Error applying replacements: {e}") import traceback traceback.print_exc() sys.exit(1) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/pptx-official/scripts/replace.py", "license": "MIT License", "lines": 309, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/document-processing/pptx-official/scripts/thumbnail.py
#!/usr/bin/env python3 """ Create thumbnail grids from PowerPoint presentation slides. Creates a grid layout of slide thumbnails with configurable columns (max 6). Each grid contains up to cols×(cols+1) images. For presentations with more slides, multiple numbered grid files are created automatically. The program outputs the names of all files created. Output: - Single grid: {prefix}.jpg (if slides fit in one grid) - Multiple grids: {prefix}-1.jpg, {prefix}-2.jpg, etc. Grid limits by column count: - 3 cols: max 12 slides per grid (3×4) - 4 cols: max 20 slides per grid (4×5) - 5 cols: max 30 slides per grid (5×6) [default] - 6 cols: max 42 slides per grid (6×7) Usage: python thumbnail.py input.pptx [output_prefix] [--cols N] [--outline-placeholders] Examples: python thumbnail.py presentation.pptx # Creates: thumbnails.jpg (using default prefix) # Outputs: # Created 1 grid(s): # - thumbnails.jpg python thumbnail.py large-deck.pptx grid --cols 4 # Creates: grid-1.jpg, grid-2.jpg, grid-3.jpg # Outputs: # Created 3 grid(s): # - grid-1.jpg # - grid-2.jpg # - grid-3.jpg python thumbnail.py template.pptx analysis --outline-placeholders # Creates thumbnail grids with red outlines around text placeholders """ import argparse import subprocess import sys import tempfile from pathlib import Path from inventory import extract_text_inventory from PIL import Image, ImageDraw, ImageFont from pptx import Presentation # Constants THUMBNAIL_WIDTH = 300 # Fixed thumbnail width in pixels CONVERSION_DPI = 100 # DPI for PDF to image conversion MAX_COLS = 6 # Maximum number of columns DEFAULT_COLS = 5 # Default number of columns JPEG_QUALITY = 95 # JPEG compression quality # Grid layout constants GRID_PADDING = 20 # Padding between thumbnails BORDER_WIDTH = 2 # Border width around thumbnails FONT_SIZE_RATIO = 0.12 # Font size as fraction of thumbnail width LABEL_PADDING_RATIO = 0.4 # Label padding as fraction of font size def main(): parser = argparse.ArgumentParser( description="Create thumbnail grids from PowerPoint slides." ) parser.add_argument("input", help="Input PowerPoint file (.pptx)") parser.add_argument( "output_prefix", nargs="?", default="thumbnails", help="Output prefix for image files (default: thumbnails, will create prefix.jpg or prefix-N.jpg)", ) parser.add_argument( "--cols", type=int, default=DEFAULT_COLS, help=f"Number of columns (default: {DEFAULT_COLS}, max: {MAX_COLS})", ) parser.add_argument( "--outline-placeholders", action="store_true", help="Outline text placeholders with a colored border", ) args = parser.parse_args() # Validate columns cols = min(args.cols, MAX_COLS) if args.cols > MAX_COLS: print(f"Warning: Columns limited to {MAX_COLS} (requested {args.cols})") # Validate input input_path = Path(args.input) if not input_path.exists() or input_path.suffix.lower() != ".pptx": print(f"Error: Invalid PowerPoint file: {args.input}") sys.exit(1) # Construct output path (always JPG) output_path = Path(f"{args.output_prefix}.jpg") print(f"Processing: {args.input}") try: with tempfile.TemporaryDirectory() as temp_dir: # Get placeholder regions if outlining is enabled placeholder_regions = None slide_dimensions = None if args.outline_placeholders: print("Extracting placeholder regions...") placeholder_regions, slide_dimensions = get_placeholder_regions( input_path ) if placeholder_regions: print(f"Found placeholders on {len(placeholder_regions)} slides") # Convert slides to images slide_images = convert_to_images(input_path, Path(temp_dir), CONVERSION_DPI) if not slide_images: print("Error: No slides found") sys.exit(1) print(f"Found {len(slide_images)} slides") # Create grids (max cols×(cols+1) images per grid) grid_files = create_grids( slide_images, cols, THUMBNAIL_WIDTH, output_path, placeholder_regions, slide_dimensions, ) # Print saved files print(f"Created {len(grid_files)} grid(s):") for grid_file in grid_files: print(f" - {grid_file}") except Exception as e: print(f"Error: {e}") sys.exit(1) def create_hidden_slide_placeholder(size): """Create placeholder image for hidden slides.""" img = Image.new("RGB", size, color="#F0F0F0") draw = ImageDraw.Draw(img) line_width = max(5, min(size) // 100) draw.line([(0, 0), size], fill="#CCCCCC", width=line_width) draw.line([(size[0], 0), (0, size[1])], fill="#CCCCCC", width=line_width) return img def get_placeholder_regions(pptx_path): """Extract ALL text regions from the presentation. Returns a tuple of (placeholder_regions, slide_dimensions). text_regions is a dict mapping slide indices to lists of text regions. Each region is a dict with 'left', 'top', 'width', 'height' in inches. slide_dimensions is a tuple of (width_inches, height_inches). """ prs = Presentation(str(pptx_path)) inventory = extract_text_inventory(pptx_path, prs) placeholder_regions = {} # Get actual slide dimensions in inches (EMU to inches conversion) slide_width_inches = (prs.slide_width or 9144000) / 914400.0 slide_height_inches = (prs.slide_height or 5143500) / 914400.0 for slide_key, shapes in inventory.items(): # Extract slide index from "slide-N" format slide_idx = int(slide_key.split("-")[1]) regions = [] for shape_key, shape_data in shapes.items(): # The inventory only contains shapes with text, so all shapes should be highlighted regions.append( { "left": shape_data.left, "top": shape_data.top, "width": shape_data.width, "height": shape_data.height, } ) if regions: placeholder_regions[slide_idx] = regions return placeholder_regions, (slide_width_inches, slide_height_inches) def convert_to_images(pptx_path, temp_dir, dpi): """Convert PowerPoint to images via PDF, handling hidden slides.""" # Detect hidden slides print("Analyzing presentation...") prs = Presentation(str(pptx_path)) total_slides = len(prs.slides) # Find hidden slides (1-based indexing for display) hidden_slides = { idx + 1 for idx, slide in enumerate(prs.slides) if slide.element.get("show") == "0" } print(f"Total slides: {total_slides}") if hidden_slides: print(f"Hidden slides: {sorted(hidden_slides)}") pdf_path = temp_dir / f"{pptx_path.stem}.pdf" # Convert to PDF print("Converting to PDF...") result = subprocess.run( [ "soffice", "--headless", "--convert-to", "pdf", "--outdir", str(temp_dir), str(pptx_path), ], capture_output=True, text=True, ) if result.returncode != 0 or not pdf_path.exists(): raise RuntimeError("PDF conversion failed") # Convert PDF to images print(f"Converting to images at {dpi} DPI...") result = subprocess.run( ["pdftoppm", "-jpeg", "-r", str(dpi), str(pdf_path), str(temp_dir / "slide")], capture_output=True, text=True, ) if result.returncode != 0: raise RuntimeError("Image conversion failed") visible_images = sorted(temp_dir.glob("slide-*.jpg")) # Create full list with placeholders for hidden slides all_images = [] visible_idx = 0 # Get placeholder dimensions from first visible slide if visible_images: with Image.open(visible_images[0]) as img: placeholder_size = img.size else: placeholder_size = (1920, 1080) for slide_num in range(1, total_slides + 1): if slide_num in hidden_slides: # Create placeholder image for hidden slide placeholder_path = temp_dir / f"hidden-{slide_num:03d}.jpg" placeholder_img = create_hidden_slide_placeholder(placeholder_size) placeholder_img.save(placeholder_path, "JPEG") all_images.append(placeholder_path) else: # Use the actual visible slide image if visible_idx < len(visible_images): all_images.append(visible_images[visible_idx]) visible_idx += 1 return all_images def create_grids( image_paths, cols, width, output_path, placeholder_regions=None, slide_dimensions=None, ): """Create multiple thumbnail grids from slide images, max cols×(cols+1) images per grid.""" # Maximum images per grid is cols × (cols + 1) for better proportions max_images_per_grid = cols * (cols + 1) grid_files = [] print( f"Creating grids with {cols} columns (max {max_images_per_grid} images per grid)" ) # Split images into chunks for chunk_idx, start_idx in enumerate( range(0, len(image_paths), max_images_per_grid) ): end_idx = min(start_idx + max_images_per_grid, len(image_paths)) chunk_images = image_paths[start_idx:end_idx] # Create grid for this chunk grid = create_grid( chunk_images, cols, width, start_idx, placeholder_regions, slide_dimensions ) # Generate output filename if len(image_paths) <= max_images_per_grid: # Single grid - use base filename without suffix grid_filename = output_path else: # Multiple grids - insert index before extension with dash stem = output_path.stem suffix = output_path.suffix grid_filename = output_path.parent / f"{stem}-{chunk_idx + 1}{suffix}" # Save grid grid_filename.parent.mkdir(parents=True, exist_ok=True) grid.save(str(grid_filename), quality=JPEG_QUALITY) grid_files.append(str(grid_filename)) return grid_files def create_grid( image_paths, cols, width, start_slide_num=0, placeholder_regions=None, slide_dimensions=None, ): """Create thumbnail grid from slide images with optional placeholder outlining.""" font_size = int(width * FONT_SIZE_RATIO) label_padding = int(font_size * LABEL_PADDING_RATIO) # Get dimensions with Image.open(image_paths[0]) as img: aspect = img.height / img.width height = int(width * aspect) # Calculate grid size rows = (len(image_paths) + cols - 1) // cols grid_w = cols * width + (cols + 1) * GRID_PADDING grid_h = rows * (height + font_size + label_padding * 2) + (rows + 1) * GRID_PADDING # Create grid grid = Image.new("RGB", (grid_w, grid_h), "white") draw = ImageDraw.Draw(grid) # Load font with size based on thumbnail width try: # Use Pillow's default font with size font = ImageFont.load_default(size=font_size) except Exception: # Fall back to basic default font if size parameter not supported font = ImageFont.load_default() # Place thumbnails for i, img_path in enumerate(image_paths): row, col = i // cols, i % cols x = col * width + (col + 1) * GRID_PADDING y_base = ( row * (height + font_size + label_padding * 2) + (row + 1) * GRID_PADDING ) # Add label with actual slide number label = f"{start_slide_num + i}" bbox = draw.textbbox((0, 0), label, font=font) text_w = bbox[2] - bbox[0] draw.text( (x + (width - text_w) // 2, y_base + label_padding), label, fill="black", font=font, ) # Add thumbnail below label with proportional spacing y_thumbnail = y_base + label_padding + font_size + label_padding with Image.open(img_path) as img: # Get original dimensions before thumbnail orig_w, orig_h = img.size # Apply placeholder outlines if enabled if placeholder_regions and (start_slide_num + i) in placeholder_regions: # Convert to RGBA for transparency support if img.mode != "RGBA": img = img.convert("RGBA") # Get the regions for this slide regions = placeholder_regions[start_slide_num + i] # Calculate scale factors using actual slide dimensions if slide_dimensions: slide_width_inches, slide_height_inches = slide_dimensions else: # Fallback: estimate from image size at CONVERSION_DPI slide_width_inches = orig_w / CONVERSION_DPI slide_height_inches = orig_h / CONVERSION_DPI x_scale = orig_w / slide_width_inches y_scale = orig_h / slide_height_inches # Create a highlight overlay overlay = Image.new("RGBA", img.size, (255, 255, 255, 0)) overlay_draw = ImageDraw.Draw(overlay) # Highlight each placeholder region for region in regions: # Convert from inches to pixels in the original image px_left = int(region["left"] * x_scale) px_top = int(region["top"] * y_scale) px_width = int(region["width"] * x_scale) px_height = int(region["height"] * y_scale) # Draw highlight outline with red color and thick stroke # Using a bright red outline instead of fill stroke_width = max( 5, min(orig_w, orig_h) // 150 ) # Thicker proportional stroke width overlay_draw.rectangle( [(px_left, px_top), (px_left + px_width, px_top + px_height)], outline=(255, 0, 0, 255), # Bright red, fully opaque width=stroke_width, ) # Composite the overlay onto the image using alpha blending img = Image.alpha_composite(img, overlay) # Convert back to RGB for JPEG saving img = img.convert("RGB") img.thumbnail((width, height), Image.Resampling.LANCZOS) w, h = img.size tx = x + (width - w) // 2 ty = y_thumbnail + (height - h) // 2 grid.paste(img, (tx, ty)) # Add border if BORDER_WIDTH > 0: draw.rectangle( [ (tx - BORDER_WIDTH, ty - BORDER_WIDTH), (tx + w + BORDER_WIDTH - 1, ty + h + BORDER_WIDTH - 1), ], outline="gray", width=BORDER_WIDTH, ) return grid if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/pptx-official/scripts/thumbnail.py", "license": "MIT License", "lines": 372, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/document-processing/xlsx-official/recalc.py
#!/usr/bin/env python3 """ Excel Formula Recalculation Script Recalculates all formulas in an Excel file using LibreOffice """ import json import sys import subprocess import os import platform from pathlib import Path from openpyxl import load_workbook def setup_libreoffice_macro(): """Setup LibreOffice macro for recalculation if not already configured""" if platform.system() == 'Darwin': macro_dir = os.path.expanduser('~/Library/Application Support/LibreOffice/4/user/basic/Standard') else: macro_dir = os.path.expanduser('~/.config/libreoffice/4/user/basic/Standard') macro_file = os.path.join(macro_dir, 'Module1.xba') if os.path.exists(macro_file): with open(macro_file, 'r') as f: if 'RecalculateAndSave' in f.read(): return True if not os.path.exists(macro_dir): subprocess.run(['soffice', '--headless', '--terminate_after_init'], capture_output=True, timeout=10) os.makedirs(macro_dir, exist_ok=True) macro_content = '''<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd"> <script:module xmlns:script="http://openoffice.org/2000/script" script:name="Module1" script:language="StarBasic"> Sub RecalculateAndSave() ThisComponent.calculateAll() ThisComponent.store() ThisComponent.close(True) End Sub </script:module>''' try: with open(macro_file, 'w') as f: f.write(macro_content) return True except Exception: return False def recalc(filename, timeout=30): """ Recalculate formulas in Excel file and report any errors Args: filename: Path to Excel file timeout: Maximum time to wait for recalculation (seconds) Returns: dict with error locations and counts """ if not Path(filename).exists(): return {'error': f'File {filename} does not exist'} abs_path = str(Path(filename).absolute()) if not setup_libreoffice_macro(): return {'error': 'Failed to setup LibreOffice macro'} cmd = [ 'soffice', '--headless', '--norestore', 'vnd.sun.star.script:Standard.Module1.RecalculateAndSave?language=Basic&location=application', abs_path ] # Handle timeout command differences between Linux and macOS if platform.system() != 'Windows': timeout_cmd = 'timeout' if platform.system() == 'Linux' else None if platform.system() == 'Darwin': # Check if gtimeout is available on macOS try: subprocess.run(['gtimeout', '--version'], capture_output=True, timeout=1, check=False) timeout_cmd = 'gtimeout' except (FileNotFoundError, subprocess.TimeoutExpired): pass if timeout_cmd: cmd = [timeout_cmd, str(timeout)] + cmd result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode != 0 and result.returncode != 124: # 124 is timeout exit code error_msg = result.stderr or 'Unknown error during recalculation' if 'Module1' in error_msg or 'RecalculateAndSave' not in error_msg: return {'error': 'LibreOffice macro not configured properly'} else: return {'error': error_msg} # Check for Excel errors in the recalculated file - scan ALL cells try: wb = load_workbook(filename, data_only=True) excel_errors = ['#VALUE!', '#DIV/0!', '#REF!', '#NAME?', '#NULL!', '#NUM!', '#N/A'] error_details = {err: [] for err in excel_errors} total_errors = 0 for sheet_name in wb.sheetnames: ws = wb[sheet_name] # Check ALL rows and columns - no limits for row in ws.iter_rows(): for cell in row: if cell.value is not None and isinstance(cell.value, str): for err in excel_errors: if err in cell.value: location = f"{sheet_name}!{cell.coordinate}" error_details[err].append(location) total_errors += 1 break wb.close() # Build result summary result = { 'status': 'success' if total_errors == 0 else 'errors_found', 'total_errors': total_errors, 'error_summary': {} } # Add non-empty error categories for err_type, locations in error_details.items(): if locations: result['error_summary'][err_type] = { 'count': len(locations), 'locations': locations[:20] # Show up to 20 locations } # Add formula count for context - also check ALL cells wb_formulas = load_workbook(filename, data_only=False) formula_count = 0 for sheet_name in wb_formulas.sheetnames: ws = wb_formulas[sheet_name] for row in ws.iter_rows(): for cell in row: if cell.value and isinstance(cell.value, str) and cell.value.startswith('='): formula_count += 1 wb_formulas.close() result['total_formulas'] = formula_count return result except Exception as e: return {'error': str(e)} def main(): if len(sys.argv) < 2: print("Usage: python recalc.py <excel_file> [timeout_seconds]") print("\nRecalculates all formulas in an Excel file using LibreOffice") print("\nReturns JSON with error details:") print(" - status: 'success' or 'errors_found'") print(" - total_errors: Total number of Excel errors found") print(" - total_formulas: Number of formulas in the file") print(" - error_summary: Breakdown by error type with locations") print(" - #VALUE!, #DIV/0!, #REF!, #NAME?, #NULL!, #NUM!, #N/A") sys.exit(1) filename = sys.argv[1] timeout = int(sys.argv[2]) if len(sys.argv) > 2 else 30 result = recalc(filename, timeout) print(json.dumps(result, indent=2)) if __name__ == '__main__': main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/document-processing/xlsx-official/recalc.py", "license": "MIT License", "lines": 143, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/enterprise-communication/slack-gif-creator/core/easing.py
#!/usr/bin/env python3 """ Easing Functions - Timing functions for smooth animations. Provides various easing functions for natural motion and timing. All functions take a value t (0.0 to 1.0) and return eased value (0.0 to 1.0). """ import math def linear(t: float) -> float: """Linear interpolation (no easing).""" return t def ease_in_quad(t: float) -> float: """Quadratic ease-in (slow start, accelerating).""" return t * t def ease_out_quad(t: float) -> float: """Quadratic ease-out (fast start, decelerating).""" return t * (2 - t) def ease_in_out_quad(t: float) -> float: """Quadratic ease-in-out (slow start and end).""" if t < 0.5: return 2 * t * t return -1 + (4 - 2 * t) * t def ease_in_cubic(t: float) -> float: """Cubic ease-in (slow start).""" return t * t * t def ease_out_cubic(t: float) -> float: """Cubic ease-out (fast start).""" return (t - 1) * (t - 1) * (t - 1) + 1 def ease_in_out_cubic(t: float) -> float: """Cubic ease-in-out.""" if t < 0.5: return 4 * t * t * t return (t - 1) * (2 * t - 2) * (2 * t - 2) + 1 def ease_in_bounce(t: float) -> float: """Bounce ease-in (bouncy start).""" return 1 - ease_out_bounce(1 - t) def ease_out_bounce(t: float) -> float: """Bounce ease-out (bouncy end).""" if t < 1 / 2.75: return 7.5625 * t * t elif t < 2 / 2.75: t -= 1.5 / 2.75 return 7.5625 * t * t + 0.75 elif t < 2.5 / 2.75: t -= 2.25 / 2.75 return 7.5625 * t * t + 0.9375 else: t -= 2.625 / 2.75 return 7.5625 * t * t + 0.984375 def ease_in_out_bounce(t: float) -> float: """Bounce ease-in-out.""" if t < 0.5: return ease_in_bounce(t * 2) * 0.5 return ease_out_bounce(t * 2 - 1) * 0.5 + 0.5 def ease_in_elastic(t: float) -> float: """Elastic ease-in (spring effect).""" if t == 0 or t == 1: return t return -math.pow(2, 10 * (t - 1)) * math.sin((t - 1.1) * 5 * math.pi) def ease_out_elastic(t: float) -> float: """Elastic ease-out (spring effect).""" if t == 0 or t == 1: return t return math.pow(2, -10 * t) * math.sin((t - 0.1) * 5 * math.pi) + 1 def ease_in_out_elastic(t: float) -> float: """Elastic ease-in-out.""" if t == 0 or t == 1: return t t = t * 2 - 1 if t < 0: return -0.5 * math.pow(2, 10 * t) * math.sin((t - 0.1) * 5 * math.pi) return math.pow(2, -10 * t) * math.sin((t - 0.1) * 5 * math.pi) * 0.5 + 1 # Convenience mapping EASING_FUNCTIONS = { "linear": linear, "ease_in": ease_in_quad, "ease_out": ease_out_quad, "ease_in_out": ease_in_out_quad, "bounce_in": ease_in_bounce, "bounce_out": ease_out_bounce, "bounce": ease_in_out_bounce, "elastic_in": ease_in_elastic, "elastic_out": ease_out_elastic, "elastic": ease_in_out_elastic, } def get_easing(name: str = "linear"): """Get easing function by name.""" return EASING_FUNCTIONS.get(name, linear) def interpolate(start: float, end: float, t: float, easing: str = "linear") -> float: """ Interpolate between two values with easing. Args: start: Start value end: End value t: Progress from 0.0 to 1.0 easing: Name of easing function Returns: Interpolated value """ ease_func = get_easing(easing) eased_t = ease_func(t) return start + (end - start) * eased_t def ease_back_in(t: float) -> float: """Back ease-in (slight overshoot backward before forward motion).""" c1 = 1.70158 c3 = c1 + 1 return c3 * t * t * t - c1 * t * t def ease_back_out(t: float) -> float: """Back ease-out (overshoot forward then settle back).""" c1 = 1.70158 c3 = c1 + 1 return 1 + c3 * pow(t - 1, 3) + c1 * pow(t - 1, 2) def ease_back_in_out(t: float) -> float: """Back ease-in-out (overshoot at both ends).""" c1 = 1.70158 c2 = c1 * 1.525 if t < 0.5: return (pow(2 * t, 2) * ((c2 + 1) * 2 * t - c2)) / 2 return (pow(2 * t - 2, 2) * ((c2 + 1) * (t * 2 - 2) + c2) + 2) / 2 def apply_squash_stretch( base_scale: tuple[float, float], intensity: float, direction: str = "vertical" ) -> tuple[float, float]: """ Calculate squash and stretch scales for more dynamic animation. Args: base_scale: (width_scale, height_scale) base scales intensity: Squash/stretch intensity (0.0-1.0) direction: 'vertical', 'horizontal', or 'both' Returns: (width_scale, height_scale) with squash/stretch applied """ width_scale, height_scale = base_scale if direction == "vertical": # Compress vertically, expand horizontally (preserve volume) height_scale *= 1 - intensity * 0.5 width_scale *= 1 + intensity * 0.5 elif direction == "horizontal": # Compress horizontally, expand vertically width_scale *= 1 - intensity * 0.5 height_scale *= 1 + intensity * 0.5 elif direction == "both": # General squash (both dimensions) width_scale *= 1 - intensity * 0.3 height_scale *= 1 - intensity * 0.3 return (width_scale, height_scale) def calculate_arc_motion( start: tuple[float, float], end: tuple[float, float], height: float, t: float ) -> tuple[float, float]: """ Calculate position along a parabolic arc (natural motion path). Args: start: (x, y) starting position end: (x, y) ending position height: Arc height at midpoint (positive = upward) t: Progress (0.0-1.0) Returns: (x, y) position along arc """ x1, y1 = start x2, y2 = end # Linear interpolation for x x = x1 + (x2 - x1) * t # Parabolic interpolation for y # y = start + progress * (end - start) + arc_offset # Arc offset peaks at t=0.5 arc_offset = 4 * height * t * (1 - t) y = y1 + (y2 - y1) * t - arc_offset return (x, y) # Add new easing functions to the convenience mapping EASING_FUNCTIONS.update( { "back_in": ease_back_in, "back_out": ease_back_out, "back_in_out": ease_back_in_out, "anticipate": ease_back_in, # Alias "overshoot": ease_back_out, # Alias } )
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/enterprise-communication/slack-gif-creator/core/easing.py", "license": "MIT License", "lines": 177, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/enterprise-communication/slack-gif-creator/core/frame_composer.py
#!/usr/bin/env python3 """ Frame Composer - Utilities for composing visual elements into frames. Provides functions for drawing shapes, text, emojis, and compositing elements together to create animation frames. """ from typing import Optional import numpy as np from PIL import Image, ImageDraw, ImageFont def create_blank_frame( width: int, height: int, color: tuple[int, int, int] = (255, 255, 255) ) -> Image.Image: """ Create a blank frame with solid color background. Args: width: Frame width height: Frame height color: RGB color tuple (default: white) Returns: PIL Image """ return Image.new("RGB", (width, height), color) def draw_circle( frame: Image.Image, center: tuple[int, int], radius: int, fill_color: Optional[tuple[int, int, int]] = None, outline_color: Optional[tuple[int, int, int]] = None, outline_width: int = 1, ) -> Image.Image: """ Draw a circle on a frame. Args: frame: PIL Image to draw on center: (x, y) center position radius: Circle radius fill_color: RGB fill color (None for no fill) outline_color: RGB outline color (None for no outline) outline_width: Outline width in pixels Returns: Modified frame """ draw = ImageDraw.Draw(frame) x, y = center bbox = [x - radius, y - radius, x + radius, y + radius] draw.ellipse(bbox, fill=fill_color, outline=outline_color, width=outline_width) return frame def draw_text( frame: Image.Image, text: str, position: tuple[int, int], color: tuple[int, int, int] = (0, 0, 0), centered: bool = False, ) -> Image.Image: """ Draw text on a frame. Args: frame: PIL Image to draw on text: Text to draw position: (x, y) position (top-left unless centered=True) color: RGB text color centered: If True, center text at position Returns: Modified frame """ draw = ImageDraw.Draw(frame) # Uses Pillow's default font. # If the font should be changed for the emoji, add additional logic here. font = ImageFont.load_default() if centered: bbox = draw.textbbox((0, 0), text, font=font) text_width = bbox[2] - bbox[0] text_height = bbox[3] - bbox[1] x = position[0] - text_width // 2 y = position[1] - text_height // 2 position = (x, y) draw.text(position, text, fill=color, font=font) return frame def create_gradient_background( width: int, height: int, top_color: tuple[int, int, int], bottom_color: tuple[int, int, int], ) -> Image.Image: """ Create a vertical gradient background. Args: width: Frame width height: Frame height top_color: RGB color at top bottom_color: RGB color at bottom Returns: PIL Image with gradient """ frame = Image.new("RGB", (width, height)) draw = ImageDraw.Draw(frame) # Calculate color step for each row r1, g1, b1 = top_color r2, g2, b2 = bottom_color for y in range(height): # Interpolate color ratio = y / height r = int(r1 * (1 - ratio) + r2 * ratio) g = int(g1 * (1 - ratio) + g2 * ratio) b = int(b1 * (1 - ratio) + b2 * ratio) # Draw horizontal line draw.line([(0, y), (width, y)], fill=(r, g, b)) return frame def draw_star( frame: Image.Image, center: tuple[int, int], size: int, fill_color: tuple[int, int, int], outline_color: Optional[tuple[int, int, int]] = None, outline_width: int = 1, ) -> Image.Image: """ Draw a 5-pointed star. Args: frame: PIL Image to draw on center: (x, y) center position size: Star size (outer radius) fill_color: RGB fill color outline_color: RGB outline color (None for no outline) outline_width: Outline width Returns: Modified frame """ import math draw = ImageDraw.Draw(frame) x, y = center # Calculate star points points = [] for i in range(10): angle = (i * 36 - 90) * math.pi / 180 # 36 degrees per point, start at top radius = size if i % 2 == 0 else size * 0.4 # Alternate between outer and inner px = x + radius * math.cos(angle) py = y + radius * math.sin(angle) points.append((px, py)) # Draw star draw.polygon(points, fill=fill_color, outline=outline_color, width=outline_width) return frame
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/enterprise-communication/slack-gif-creator/core/frame_composer.py", "license": "MIT License", "lines": 142, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
davila7/claude-code-templates:cli-tool/components/skills/enterprise-communication/slack-gif-creator/core/gif_builder.py
#!/usr/bin/env python3 """ GIF Builder - Core module for assembling frames into GIFs optimized for Slack. This module provides the main interface for creating GIFs from programmatically generated frames, with automatic optimization for Slack's requirements. """ from pathlib import Path from typing import Optional import imageio.v3 as imageio import numpy as np from PIL import Image class GIFBuilder: """Builder for creating optimized GIFs from frames.""" def __init__(self, width: int = 480, height: int = 480, fps: int = 15): """ Initialize GIF builder. Args: width: Frame width in pixels height: Frame height in pixels fps: Frames per second """ self.width = width self.height = height self.fps = fps self.frames: list[np.ndarray] = [] def add_frame(self, frame: np.ndarray | Image.Image): """ Add a frame to the GIF. Args: frame: Frame as numpy array or PIL Image (will be converted to RGB) """ if isinstance(frame, Image.Image): frame = np.array(frame.convert("RGB")) # Ensure frame is correct size if frame.shape[:2] != (self.height, self.width): pil_frame = Image.fromarray(frame) pil_frame = pil_frame.resize( (self.width, self.height), Image.Resampling.LANCZOS ) frame = np.array(pil_frame) self.frames.append(frame) def add_frames(self, frames: list[np.ndarray | Image.Image]): """Add multiple frames at once.""" for frame in frames: self.add_frame(frame) def optimize_colors( self, num_colors: int = 128, use_global_palette: bool = True ) -> list[np.ndarray]: """ Reduce colors in all frames using quantization. Args: num_colors: Target number of colors (8-256) use_global_palette: Use a single palette for all frames (better compression) Returns: List of color-optimized frames """ optimized = [] if use_global_palette and len(self.frames) > 1: # Create a global palette from all frames # Sample frames to build palette sample_size = min(5, len(self.frames)) sample_indices = [ int(i * len(self.frames) / sample_size) for i in range(sample_size) ] sample_frames = [self.frames[i] for i in sample_indices] # Combine sample frames into a single image for palette generation # Flatten each frame to get all pixels, then stack them all_pixels = np.vstack( [f.reshape(-1, 3) for f in sample_frames] ) # (total_pixels, 3) # Create a properly-shaped RGB image from the pixel data # We'll make a roughly square image from all the pixels total_pixels = len(all_pixels) width = min(512, int(np.sqrt(total_pixels))) # Reasonable width, max 512 height = (total_pixels + width - 1) // width # Ceiling division # Pad if necessary to fill the rectangle pixels_needed = width * height if pixels_needed > total_pixels: padding = np.zeros((pixels_needed - total_pixels, 3), dtype=np.uint8) all_pixels = np.vstack([all_pixels, padding]) # Reshape to proper RGB image format (H, W, 3) img_array = ( all_pixels[:pixels_needed].reshape(height, width, 3).astype(np.uint8) ) combined_img = Image.fromarray(img_array, mode="RGB") # Generate global palette global_palette = combined_img.quantize(colors=num_colors, method=2) # Apply global palette to all frames for frame in self.frames: pil_frame = Image.fromarray(frame) quantized = pil_frame.quantize(palette=global_palette, dither=1) optimized.append(np.array(quantized.convert("RGB"))) else: # Use per-frame quantization for frame in self.frames: pil_frame = Image.fromarray(frame) quantized = pil_frame.quantize(colors=num_colors, method=2, dither=1) optimized.append(np.array(quantized.convert("RGB"))) return optimized def deduplicate_frames(self, threshold: float = 0.9995) -> int: """ Remove duplicate or near-duplicate consecutive frames. Args: threshold: Similarity threshold (0.0-1.0). Higher = more strict (0.9995 = nearly identical). Use 0.9995+ to preserve subtle animations, 0.98 for aggressive removal. Returns: Number of frames removed """ if len(self.frames) < 2: return 0 deduplicated = [self.frames[0]] removed_count = 0 for i in range(1, len(self.frames)): # Compare with previous frame prev_frame = np.array(deduplicated[-1], dtype=np.float32) curr_frame = np.array(self.frames[i], dtype=np.float32) # Calculate similarity (normalized) diff = np.abs(prev_frame - curr_frame) similarity = 1.0 - (np.mean(diff) / 255.0) # Keep frame if sufficiently different # High threshold (0.9995+) means only remove nearly identical frames if similarity < threshold: deduplicated.append(self.frames[i]) else: removed_count += 1 self.frames = deduplicated return removed_count def save( self, output_path: str | Path, num_colors: int = 128, optimize_for_emoji: bool = False, remove_duplicates: bool = False, ) -> dict: """ Save frames as optimized GIF for Slack. Args: output_path: Where to save the GIF num_colors: Number of colors to use (fewer = smaller file) optimize_for_emoji: If True, optimize for emoji size (128x128, fewer colors) remove_duplicates: If True, remove duplicate consecutive frames (opt-in) Returns: Dictionary with file info (path, size, dimensions, frame_count) """ if not self.frames: raise ValueError("No frames to save. Add frames with add_frame() first.") output_path = Path(output_path) # Remove duplicate frames to reduce file size if remove_duplicates: removed = self.deduplicate_frames(threshold=0.9995) if removed > 0: print( f" Removed {removed} nearly identical frames (preserved subtle animations)" ) # Optimize for emoji if requested if optimize_for_emoji: if self.width > 128 or self.height > 128: print( f" Resizing from {self.width}x{self.height} to 128x128 for emoji" ) self.width = 128 self.height = 128 # Resize all frames resized_frames = [] for frame in self.frames: pil_frame = Image.fromarray(frame) pil_frame = pil_frame.resize((128, 128), Image.Resampling.LANCZOS) resized_frames.append(np.array(pil_frame)) self.frames = resized_frames num_colors = min(num_colors, 48) # More aggressive color limit for emoji # More aggressive FPS reduction for emoji if len(self.frames) > 12: print( f" Reducing frames from {len(self.frames)} to ~12 for emoji size" ) # Keep every nth frame to get close to 12 frames keep_every = max(1, len(self.frames) // 12) self.frames = [ self.frames[i] for i in range(0, len(self.frames), keep_every) ] # Optimize colors with global palette optimized_frames = self.optimize_colors(num_colors, use_global_palette=True) # Calculate frame duration in milliseconds frame_duration = 1000 / self.fps # Save GIF imageio.imwrite( output_path, optimized_frames, duration=frame_duration, loop=0, # Infinite loop ) # Get file info file_size_kb = output_path.stat().st_size / 1024 file_size_mb = file_size_kb / 1024 info = { "path": str(output_path), "size_kb": file_size_kb, "size_mb": file_size_mb, "dimensions": f"{self.width}x{self.height}", "frame_count": len(optimized_frames), "fps": self.fps, "duration_seconds": len(optimized_frames) / self.fps, "colors": num_colors, } # Print info print(f"\n✓ GIF created successfully!") print(f" Path: {output_path}") print(f" Size: {file_size_kb:.1f} KB ({file_size_mb:.2f} MB)") print(f" Dimensions: {self.width}x{self.height}") print(f" Frames: {len(optimized_frames)} @ {self.fps} fps") print(f" Duration: {info['duration_seconds']:.1f}s") print(f" Colors: {num_colors}") # Size info if optimize_for_emoji: print(f" Optimized for emoji (128x128, reduced colors)") if file_size_mb > 1.0: print(f"\n Note: Large file size ({file_size_kb:.1f} KB)") print(" Consider: fewer frames, smaller dimensions, or fewer colors") return info def clear(self): """Clear all frames (useful for creating multiple GIFs).""" self.frames = []
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/enterprise-communication/slack-gif-creator/core/gif_builder.py", "license": "MIT License", "lines": 222, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/enterprise-communication/slack-gif-creator/core/validators.py
#!/usr/bin/env python3 """ Validators - Check if GIFs meet Slack's requirements. These validators help ensure your GIFs meet Slack's size and dimension constraints. """ from pathlib import Path def validate_gif( gif_path: str | Path, is_emoji: bool = True, verbose: bool = True ) -> tuple[bool, dict]: """ Validate GIF for Slack (dimensions, size, frame count). Args: gif_path: Path to GIF file is_emoji: True for emoji (128x128 recommended), False for message GIF verbose: Print validation details Returns: Tuple of (passes: bool, results: dict with all details) """ from PIL import Image gif_path = Path(gif_path) if not gif_path.exists(): return False, {"error": f"File not found: {gif_path}"} # Get file size size_bytes = gif_path.stat().st_size size_kb = size_bytes / 1024 size_mb = size_kb / 1024 # Get dimensions and frame info try: with Image.open(gif_path) as img: width, height = img.size # Count frames frame_count = 0 try: while True: img.seek(frame_count) frame_count += 1 except EOFError: pass # Get duration try: duration_ms = img.info.get("duration", 100) total_duration = (duration_ms * frame_count) / 1000 fps = frame_count / total_duration if total_duration > 0 else 0 except: total_duration = None fps = None except Exception as e: return False, {"error": f"Failed to read GIF: {e}"} # Validate dimensions if is_emoji: optimal = width == height == 128 acceptable = width == height and 64 <= width <= 128 dim_pass = acceptable else: aspect_ratio = ( max(width, height) / min(width, height) if min(width, height) > 0 else float("inf") ) dim_pass = aspect_ratio <= 2.0 and 320 <= min(width, height) <= 640 results = { "file": str(gif_path), "passes": dim_pass, "width": width, "height": height, "size_kb": size_kb, "size_mb": size_mb, "frame_count": frame_count, "duration_seconds": total_duration, "fps": fps, "is_emoji": is_emoji, "optimal": optimal if is_emoji else None, } # Print if verbose if verbose: print(f"\nValidating {gif_path.name}:") print( f" Dimensions: {width}x{height}" + ( f" ({'optimal' if optimal else 'acceptable'})" if is_emoji and acceptable else "" ) ) print( f" Size: {size_kb:.1f} KB" + (f" ({size_mb:.2f} MB)" if size_mb >= 1.0 else "") ) print( f" Frames: {frame_count}" + (f" @ {fps:.1f} fps ({total_duration:.1f}s)" if fps else "") ) if not dim_pass: print( f" Note: {'Emoji should be 128x128' if is_emoji else 'Unusual dimensions for Slack'}" ) if size_mb > 5.0: print(f" Note: Large file size - consider fewer frames/colors") return dim_pass, results def is_slack_ready( gif_path: str | Path, is_emoji: bool = True, verbose: bool = True ) -> bool: """ Quick check if GIF is ready for Slack. Args: gif_path: Path to GIF file is_emoji: True for emoji GIF, False for message GIF verbose: Print feedback Returns: True if dimensions are acceptable """ passes, _ = validate_gif(gif_path, is_emoji, verbose) return passes
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/enterprise-communication/slack-gif-creator/core/validators.py", "license": "MIT License", "lines": 113, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/productivity/notebooklm/scripts/ask_question.py
#!/usr/bin/env python3 """ Simple NotebookLM Question Interface Based on MCP server implementation - simplified without sessions Implements hybrid auth approach: - Persistent browser profile (user_data_dir) for fingerprint consistency - Manual cookie injection from state.json for session cookies (Playwright bug workaround) See: https://github.com/microsoft/playwright/issues/36139 """ import argparse import sys import time import re from pathlib import Path from patchright.sync_api import sync_playwright # Add parent directory to path sys.path.insert(0, str(Path(__file__).parent)) from auth_manager import AuthManager from notebook_manager import NotebookLibrary from config import QUERY_INPUT_SELECTORS, RESPONSE_SELECTORS from browser_utils import BrowserFactory, StealthUtils # Follow-up reminder (adapted from MCP server for stateless operation) # Since we don't have persistent sessions, we encourage comprehensive questions FOLLOW_UP_REMINDER = ( "\n\nEXTREMELY IMPORTANT: Is that ALL you need to know? " "You can always ask another question! Think about it carefully: " "before you reply to the user, review their original request and this answer. " "If anything is still unclear or missing, ask me another comprehensive question " "that includes all necessary context (since each question opens a new browser session)." ) def ask_notebooklm(question: str, notebook_url: str, headless: bool = True) -> str: """ Ask a question to NotebookLM Args: question: Question to ask notebook_url: NotebookLM notebook URL headless: Run browser in headless mode Returns: Answer text from NotebookLM """ auth = AuthManager() if not auth.is_authenticated(): print("⚠️ Not authenticated. Run: python auth_manager.py setup") return None print(f"💬 Asking: {question}") print(f"📚 Notebook: {notebook_url}") playwright = None context = None try: # Start playwright playwright = sync_playwright().start() # Launch persistent browser context using factory context = BrowserFactory.launch_persistent_context( playwright, headless=headless ) # Navigate to notebook page = context.new_page() print(" 🌐 Opening notebook...") page.goto(notebook_url, wait_until="domcontentloaded") # Wait for NotebookLM page.wait_for_url(re.compile(r"^https://notebooklm\.google\.com/"), timeout=10000) # Wait for query input (MCP approach) print(" ⏳ Waiting for query input...") query_element = None for selector in QUERY_INPUT_SELECTORS: try: query_element = page.wait_for_selector( selector, timeout=10000, state="visible" # Only check visibility, not disabled! ) if query_element: print(f" ✓ Found input: {selector}") break except: continue if not query_element: print(" ❌ Could not find query input") return None # Type question (human-like, fast) print(" ⏳ Typing question...") # Use primary selector for typing input_selector = QUERY_INPUT_SELECTORS[0] StealthUtils.human_type(page, input_selector, question) # Submit print(" 📤 Submitting...") page.keyboard.press("Enter") # Small pause StealthUtils.random_delay(500, 1500) # Wait for response (MCP approach: poll for stable text) print(" ⏳ Waiting for answer...") answer = None stable_count = 0 last_text = None deadline = time.time() + 120 # 2 minutes timeout while time.time() < deadline: # Check if NotebookLM is still thinking (most reliable indicator) try: thinking_element = page.query_selector('div.thinking-message') if thinking_element and thinking_element.is_visible(): time.sleep(1) continue except: pass # Try to find response with MCP selectors for selector in RESPONSE_SELECTORS: try: elements = page.query_selector_all(selector) if elements: # Get last (newest) response latest = elements[-1] text = latest.inner_text().strip() if text: if text == last_text: stable_count += 1 if stable_count >= 3: # Stable for 3 polls answer = text break else: stable_count = 0 last_text = text except: continue if answer: break time.sleep(1) if not answer: print(" ❌ Timeout waiting for answer") return None print(" ✅ Got answer!") # Add follow-up reminder to encourage Claude to ask more questions return answer + FOLLOW_UP_REMINDER except Exception as e: print(f" ❌ Error: {e}") import traceback traceback.print_exc() return None finally: # Always clean up if context: try: context.close() except: pass if playwright: try: playwright.stop() except: pass def main(): parser = argparse.ArgumentParser(description='Ask NotebookLM a question') parser.add_argument('--question', required=True, help='Question to ask') parser.add_argument('--notebook-url', help='NotebookLM notebook URL') parser.add_argument('--notebook-id', help='Notebook ID from library') parser.add_argument('--show-browser', action='store_true', help='Show browser') args = parser.parse_args() # Resolve notebook URL notebook_url = args.notebook_url if not notebook_url and args.notebook_id: library = NotebookLibrary() notebook = library.get_notebook(args.notebook_id) if notebook: notebook_url = notebook['url'] else: print(f"❌ Notebook '{args.notebook_id}' not found") return 1 if not notebook_url: # Check for active notebook first library = NotebookLibrary() active = library.get_active_notebook() if active: notebook_url = active['url'] print(f"📚 Using active notebook: {active['name']}") else: # Show available notebooks notebooks = library.list_notebooks() if notebooks: print("\n📚 Available notebooks:") for nb in notebooks: mark = " [ACTIVE]" if nb.get('id') == library.active_notebook_id else "" print(f" {nb['id']}: {nb['name']}{mark}") print("\nSpecify with --notebook-id or set active:") print("python scripts/run.py notebook_manager.py activate --id ID") else: print("❌ No notebooks in library. Add one first:") print("python scripts/run.py notebook_manager.py add --url URL --name NAME --description DESC --topics TOPICS") return 1 # Ask the question answer = ask_notebooklm( question=args.question, notebook_url=notebook_url, headless=not args.show_browser ) if answer: print("\n" + "=" * 60) print(f"Question: {args.question}") print("=" * 60) print() print(answer) print() print("=" * 60) return 0 else: print("\n❌ Failed to get answer") return 1 if __name__ == "__main__": sys.exit(main())
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/productivity/notebooklm/scripts/ask_question.py", "license": "MIT License", "lines": 208, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/productivity/notebooklm/scripts/auth_manager.py
#!/usr/bin/env python3 """ Authentication Manager for NotebookLM Handles Google login and browser state persistence Based on the MCP server implementation Implements hybrid auth approach: - Persistent browser profile (user_data_dir) for fingerprint consistency - Manual cookie injection from state.json for session cookies (Playwright bug workaround) See: https://github.com/microsoft/playwright/issues/36139 """ import json import time import argparse import shutil import re import sys from pathlib import Path from typing import Optional, Dict, Any from patchright.sync_api import sync_playwright, BrowserContext # Add parent directory to path sys.path.insert(0, str(Path(__file__).parent)) from config import BROWSER_STATE_DIR, STATE_FILE, AUTH_INFO_FILE, DATA_DIR from browser_utils import BrowserFactory class AuthManager: """ Manages authentication and browser state for NotebookLM Features: - Interactive Google login - Browser state persistence - Session restoration - Account switching """ def __init__(self): """Initialize the authentication manager""" # Ensure directories exist DATA_DIR.mkdir(parents=True, exist_ok=True) BROWSER_STATE_DIR.mkdir(parents=True, exist_ok=True) self.state_file = STATE_FILE self.auth_info_file = AUTH_INFO_FILE self.browser_state_dir = BROWSER_STATE_DIR def is_authenticated(self) -> bool: """Check if valid authentication exists""" if not self.state_file.exists(): return False # Check if state file is not too old (7 days) age_days = (time.time() - self.state_file.stat().st_mtime) / 86400 if age_days > 7: print(f"⚠️ Browser state is {age_days:.1f} days old, may need re-authentication") return True def get_auth_info(self) -> Dict[str, Any]: """Get authentication information""" info = { 'authenticated': self.is_authenticated(), 'state_file': str(self.state_file), 'state_exists': self.state_file.exists() } if self.auth_info_file.exists(): try: with open(self.auth_info_file, 'r') as f: saved_info = json.load(f) info.update(saved_info) except Exception: pass if info['state_exists']: age_hours = (time.time() - self.state_file.stat().st_mtime) / 3600 info['state_age_hours'] = age_hours return info def setup_auth(self, headless: bool = False, timeout_minutes: int = 10) -> bool: """ Perform interactive authentication setup Args: headless: Run browser in headless mode (False for login) timeout_minutes: Maximum time to wait for login Returns: True if authentication successful """ print("🔐 Starting authentication setup...") print(f" Timeout: {timeout_minutes} minutes") playwright = None context = None try: playwright = sync_playwright().start() # Launch using factory context = BrowserFactory.launch_persistent_context( playwright, headless=headless ) # Navigate to NotebookLM page = context.new_page() page.goto("https://notebooklm.google.com", wait_until="domcontentloaded") # Check if already authenticated if "notebooklm.google.com" in page.url and "accounts.google.com" not in page.url: print(" ✅ Already authenticated!") self._save_browser_state(context) return True # Wait for manual login print("\n ⏳ Please log in to your Google account...") print(f" ⏱️ Waiting up to {timeout_minutes} minutes for login...") try: # Wait for URL to change to NotebookLM (regex ensures it's the actual domain, not a parameter) timeout_ms = int(timeout_minutes * 60 * 1000) page.wait_for_url(re.compile(r"^https://notebooklm\.google\.com/"), timeout=timeout_ms) print(f" ✅ Login successful!") # Save authentication state self._save_browser_state(context) self._save_auth_info() return True except Exception as e: print(f" ❌ Authentication timeout: {e}") return False except Exception as e: print(f" ❌ Error: {e}") return False finally: # Clean up browser resources if context: try: context.close() except Exception: pass if playwright: try: playwright.stop() except Exception: pass def _save_browser_state(self, context: BrowserContext): """Save browser state to disk""" try: # Save storage state (cookies, localStorage) context.storage_state(path=str(self.state_file)) print(f" 💾 Saved browser state to: {self.state_file}") except Exception as e: print(f" ❌ Failed to save browser state: {e}") raise def _save_auth_info(self): """Save authentication metadata""" try: info = { 'authenticated_at': time.time(), 'authenticated_at_iso': time.strftime('%Y-%m-%d %H:%M:%S') } with open(self.auth_info_file, 'w') as f: json.dump(info, f, indent=2) except Exception: pass # Non-critical def clear_auth(self) -> bool: """ Clear all authentication data Returns: True if cleared successfully """ print("🗑️ Clearing authentication data...") try: # Remove browser state if self.state_file.exists(): self.state_file.unlink() print(" ✅ Removed browser state") # Remove auth info if self.auth_info_file.exists(): self.auth_info_file.unlink() print(" ✅ Removed auth info") # Clear entire browser state directory if self.browser_state_dir.exists(): shutil.rmtree(self.browser_state_dir) self.browser_state_dir.mkdir(parents=True, exist_ok=True) print(" ✅ Cleared browser data") return True except Exception as e: print(f" ❌ Error clearing auth: {e}") return False def re_auth(self, headless: bool = False, timeout_minutes: int = 10) -> bool: """ Perform re-authentication (clear and setup) Args: headless: Run browser in headless mode timeout_minutes: Login timeout in minutes Returns: True if successful """ print("🔄 Starting re-authentication...") # Clear existing auth self.clear_auth() # Setup new auth return self.setup_auth(headless, timeout_minutes) def validate_auth(self) -> bool: """ Validate that stored authentication works Uses persistent context to match actual usage pattern Returns: True if authentication is valid """ if not self.is_authenticated(): return False print("🔍 Validating authentication...") playwright = None context = None try: playwright = sync_playwright().start() # Launch using factory context = BrowserFactory.launch_persistent_context( playwright, headless=True ) # Try to access NotebookLM page = context.new_page() page.goto("https://notebooklm.google.com", wait_until="domcontentloaded", timeout=30000) # Check if we can access NotebookLM if "notebooklm.google.com" in page.url and "accounts.google.com" not in page.url: print(" ✅ Authentication is valid") return True else: print(" ❌ Authentication is invalid (redirected to login)") return False except Exception as e: print(f" ❌ Validation failed: {e}") return False finally: if context: try: context.close() except Exception: pass if playwright: try: playwright.stop() except Exception: pass def main(): """Command-line interface for authentication management""" parser = argparse.ArgumentParser(description='Manage NotebookLM authentication') subparsers = parser.add_subparsers(dest='command', help='Commands') # Setup command setup_parser = subparsers.add_parser('setup', help='Setup authentication') setup_parser.add_argument('--headless', action='store_true', help='Run in headless mode') setup_parser.add_argument('--timeout', type=float, default=10, help='Login timeout in minutes (default: 10)') # Status command subparsers.add_parser('status', help='Check authentication status') # Validate command subparsers.add_parser('validate', help='Validate authentication') # Clear command subparsers.add_parser('clear', help='Clear authentication') # Re-auth command reauth_parser = subparsers.add_parser('reauth', help='Re-authenticate (clear + setup)') reauth_parser.add_argument('--timeout', type=float, default=10, help='Login timeout in minutes (default: 10)') args = parser.parse_args() # Initialize manager auth = AuthManager() # Execute command if args.command == 'setup': if auth.setup_auth(headless=args.headless, timeout_minutes=args.timeout): print("\n✅ Authentication setup complete!") print("You can now use ask_question.py to query NotebookLM") else: print("\n❌ Authentication setup failed") exit(1) elif args.command == 'status': info = auth.get_auth_info() print("\n🔐 Authentication Status:") print(f" Authenticated: {'Yes' if info['authenticated'] else 'No'}") if info.get('state_age_hours'): print(f" State age: {info['state_age_hours']:.1f} hours") if info.get('authenticated_at_iso'): print(f" Last auth: {info['authenticated_at_iso']}") print(f" State file: {info['state_file']}") elif args.command == 'validate': if auth.validate_auth(): print("Authentication is valid and working") else: print("Authentication is invalid or expired") print("Run: auth_manager.py setup") elif args.command == 'clear': if auth.clear_auth(): print("Authentication cleared") elif args.command == 'reauth': if auth.re_auth(timeout_minutes=args.timeout): print("\n✅ Re-authentication complete!") else: print("\n❌ Re-authentication failed") exit(1) else: parser.print_help() if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/productivity/notebooklm/scripts/auth_manager.py", "license": "MIT License", "lines": 283, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/productivity/notebooklm/scripts/browser_session.py
#!/usr/bin/env python3 """ Browser Session Management for NotebookLM Individual browser session for persistent NotebookLM conversations Based on the original NotebookLM API implementation """ import time import sys from typing import Any, Dict, Optional from pathlib import Path from patchright.sync_api import BrowserContext, Page # Add parent directory to path sys.path.insert(0, str(Path(__file__).parent)) from browser_utils import StealthUtils class BrowserSession: """ Represents a single persistent browser session for NotebookLM Each session gets its own Page (tab) within a shared BrowserContext, allowing for contextual conversations where NotebookLM remembers previous messages. """ def __init__(self, session_id: str, context: BrowserContext, notebook_url: str): """ Initialize a new browser session Args: session_id: Unique identifier for this session context: Browser context (shared or dedicated) notebook_url: Target NotebookLM URL for this session """ self.id = session_id self.created_at = time.time() self.last_activity = time.time() self.message_count = 0 self.notebook_url = notebook_url self.context = context self.page = None self.stealth = StealthUtils() # Initialize the session self._initialize() def _initialize(self): """Initialize the browser session and navigate to NotebookLM""" print(f"🚀 Creating session {self.id}...") # Create new page (tab) in context self.page = self.context.new_page() print(f" 🌐 Navigating to NotebookLM...") try: # Navigate to notebook self.page.goto(self.notebook_url, wait_until="domcontentloaded", timeout=30000) # Check if login is needed if "accounts.google.com" in self.page.url: raise RuntimeError("Authentication required. Please run auth_manager.py setup first.") # Wait for page to be ready self._wait_for_ready() # Simulate human inspection self.stealth.random_mouse_movement(self.page) self.stealth.random_delay(300, 600) print(f"✅ Session {self.id} ready!") except Exception as e: print(f"❌ Failed to initialize session: {e}") if self.page: self.page.close() raise def _wait_for_ready(self): """Wait for NotebookLM page to be ready""" try: # Wait for chat input self.page.wait_for_selector("textarea.query-box-input", timeout=10000, state="visible") except Exception: # Try alternative selector self.page.wait_for_selector('textarea[aria-label="Feld für Anfragen"]', timeout=5000, state="visible") def ask(self, question: str) -> Dict[str, Any]: """ Ask a question in this session Args: question: The question to ask Returns: Dict with status, question, answer, session_id """ try: self.last_activity = time.time() self.message_count += 1 print(f"💬 [{self.id}] Asking: {question}") # Snapshot current answer to detect new response previous_answer = self._snapshot_latest_response() # Find chat input chat_input_selector = "textarea.query-box-input" try: self.page.wait_for_selector(chat_input_selector, timeout=5000, state="visible") except Exception: chat_input_selector = 'textarea[aria-label="Feld für Anfragen"]' self.page.wait_for_selector(chat_input_selector, timeout=5000, state="visible") # Click and type with human-like behavior self.stealth.realistic_click(self.page, chat_input_selector) self.stealth.human_type(self.page, chat_input_selector, question) # Small pause before submit self.stealth.random_delay(300, 800) # Submit self.page.keyboard.press("Enter") # Wait for response print(" ⏳ Waiting for response...") self.stealth.random_delay(1500, 3000) # Get new answer answer = self._wait_for_latest_answer(previous_answer) if not answer: raise Exception("Empty response from NotebookLM") print(f" ✅ Got response ({len(answer)} chars)") return { "status": "success", "question": question, "answer": answer, "session_id": self.id, "notebook_url": self.notebook_url } except Exception as e: print(f" ❌ Error: {e}") return { "status": "error", "question": question, "error": str(e), "session_id": self.id } def _snapshot_latest_response(self) -> Optional[str]: """Get the current latest response text""" try: # Use correct NotebookLM selector responses = self.page.query_selector_all(".to-user-container .message-text-content") if responses: return responses[-1].inner_text() except Exception: pass return None def _wait_for_latest_answer(self, previous_answer: Optional[str], timeout: int = 120) -> str: """Wait for and extract the new answer""" start_time = time.time() last_candidate = None stable_count = 0 while time.time() - start_time < timeout: # Check if NotebookLM is still thinking (most reliable indicator) try: thinking_element = self.page.query_selector('div.thinking-message') if thinking_element and thinking_element.is_visible(): time.sleep(0.5) continue except Exception: pass try: # Use correct NotebookLM selector responses = self.page.query_selector_all(".to-user-container .message-text-content") if responses: latest_text = responses[-1].inner_text().strip() # Check if it's a new response if latest_text and latest_text != previous_answer: # Check if text is stable (3 consecutive polls) if latest_text == last_candidate: stable_count += 1 if stable_count >= 3: return latest_text else: stable_count = 1 last_candidate = latest_text except Exception: pass time.sleep(0.5) raise TimeoutError(f"No response received within {timeout} seconds") def reset(self): """Reset the chat by reloading the page""" print(f"🔄 Resetting session {self.id}...") self.page.reload(wait_until="domcontentloaded") self._wait_for_ready() previous_count = self.message_count self.message_count = 0 self.last_activity = time.time() print(f"✅ Session reset (cleared {previous_count} messages)") return previous_count def close(self): """Close this session and clean up resources""" print(f"🛑 Closing session {self.id}...") if self.page: try: self.page.close() except Exception as e: print(f" ⚠️ Error closing page: {e}") print(f"✅ Session {self.id} closed") def get_info(self) -> Dict[str, Any]: """Get information about this session""" return { "id": self.id, "created_at": self.created_at, "last_activity": self.last_activity, "age_seconds": time.time() - self.created_at, "inactive_seconds": time.time() - self.last_activity, "message_count": self.message_count, "notebook_url": self.notebook_url } def is_expired(self, timeout_seconds: int = 900) -> bool: """Check if session has expired (default: 15 minutes)""" return (time.time() - self.last_activity) > timeout_seconds if __name__ == "__main__": # Example usage print("Browser Session Module - Use ask_question.py for main interface") print("This module provides low-level browser session management.")
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/productivity/notebooklm/scripts/browser_session.py", "license": "MIT License", "lines": 201, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/productivity/notebooklm/scripts/browser_utils.py
""" Browser Utilities for NotebookLM Skill Handles browser launching, stealth features, and common interactions """ import json import time import random from typing import Optional, List from patchright.sync_api import Playwright, BrowserContext, Page from config import BROWSER_PROFILE_DIR, STATE_FILE, BROWSER_ARGS, USER_AGENT class BrowserFactory: """Factory for creating configured browser contexts""" @staticmethod def launch_persistent_context( playwright: Playwright, headless: bool = True, user_data_dir: str = str(BROWSER_PROFILE_DIR) ) -> BrowserContext: """ Launch a persistent browser context with anti-detection features and cookie workaround. """ # Launch persistent context context = playwright.chromium.launch_persistent_context( user_data_dir=user_data_dir, channel="chrome", # Use real Chrome headless=headless, no_viewport=True, ignore_default_args=["--enable-automation"], user_agent=USER_AGENT, args=BROWSER_ARGS ) # Cookie Workaround for Playwright bug #36139 # Session cookies (expires=-1) don't persist in user_data_dir automatically BrowserFactory._inject_cookies(context) return context @staticmethod def _inject_cookies(context: BrowserContext): """Inject cookies from state.json if available""" if STATE_FILE.exists(): try: with open(STATE_FILE, 'r') as f: state = json.load(f) if 'cookies' in state and len(state['cookies']) > 0: context.add_cookies(state['cookies']) # print(f" 🔧 Injected {len(state['cookies'])} cookies from state.json") except Exception as e: print(f" ⚠️ Could not load state.json: {e}") class StealthUtils: """Human-like interaction utilities""" @staticmethod def random_delay(min_ms: int = 100, max_ms: int = 500): """Add random delay""" time.sleep(random.uniform(min_ms / 1000, max_ms / 1000)) @staticmethod def human_type(page: Page, selector: str, text: str, wpm_min: int = 320, wpm_max: int = 480): """Type with human-like speed""" element = page.query_selector(selector) if not element: # Try waiting if not immediately found try: element = page.wait_for_selector(selector, timeout=2000) except: pass if not element: print(f"⚠️ Element not found for typing: {selector}") return # Click to focus element.click() # Type for char in text: element.type(char, delay=random.uniform(25, 75)) if random.random() < 0.05: time.sleep(random.uniform(0.15, 0.4)) @staticmethod def realistic_click(page: Page, selector: str): """Click with realistic movement""" element = page.query_selector(selector) if not element: return # Optional: Move mouse to element (simplified) box = element.bounding_box() if box: x = box['x'] + box['width'] / 2 y = box['y'] + box['height'] / 2 page.mouse.move(x, y, steps=5) StealthUtils.random_delay(100, 300) element.click() StealthUtils.random_delay(100, 300)
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/productivity/notebooklm/scripts/browser_utils.py", "license": "MIT License", "lines": 89, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/productivity/notebooklm/scripts/cleanup_manager.py
#!/usr/bin/env python3 """ Cleanup Manager for NotebookLM Skill Manages cleanup of skill data and browser state """ import shutil import argparse from pathlib import Path from typing import Dict, List, Any class CleanupManager: """ Manages cleanup of NotebookLM skill data Features: - Preview what will be deleted - Selective cleanup options - Library preservation - Safe deletion with confirmation """ def __init__(self): """Initialize the cleanup manager""" # Skill directory paths self.skill_dir = Path(__file__).parent.parent self.data_dir = self.skill_dir / "data" def get_cleanup_paths(self, preserve_library: bool = False) -> Dict[str, Any]: """ Get paths that would be cleaned up Args: preserve_library: Keep library.json if True Returns: Dict with paths and sizes Note: .venv is NEVER deleted - it's part of the skill infrastructure """ paths = { 'browser_state': [], 'sessions': [], 'library': [], 'auth': [], 'other': [] } total_size = 0 if self.data_dir.exists(): # Browser state browser_state_dir = self.data_dir / "browser_state" if browser_state_dir.exists(): for item in browser_state_dir.iterdir(): size = self._get_size(item) paths['browser_state'].append({ 'path': str(item), 'size': size, 'type': 'dir' if item.is_dir() else 'file' }) total_size += size # Sessions sessions_file = self.data_dir / "sessions.json" if sessions_file.exists(): size = sessions_file.stat().st_size paths['sessions'].append({ 'path': str(sessions_file), 'size': size, 'type': 'file' }) total_size += size # Library (unless preserved) if not preserve_library: library_file = self.data_dir / "library.json" if library_file.exists(): size = library_file.stat().st_size paths['library'].append({ 'path': str(library_file), 'size': size, 'type': 'file' }) total_size += size # Auth info auth_info = self.data_dir / "auth_info.json" if auth_info.exists(): size = auth_info.stat().st_size paths['auth'].append({ 'path': str(auth_info), 'size': size, 'type': 'file' }) total_size += size # Other files in data dir (but NEVER .venv!) for item in self.data_dir.iterdir(): if item.name not in ['browser_state', 'sessions.json', 'library.json', 'auth_info.json']: size = self._get_size(item) paths['other'].append({ 'path': str(item), 'size': size, 'type': 'dir' if item.is_dir() else 'file' }) total_size += size return { 'categories': paths, 'total_size': total_size, 'total_items': sum(len(items) for items in paths.values()) } def _get_size(self, path: Path) -> int: """Get size of file or directory in bytes""" if path.is_file(): return path.stat().st_size elif path.is_dir(): total = 0 try: for item in path.rglob('*'): if item.is_file(): total += item.stat().st_size except Exception: pass return total return 0 def _format_size(self, size: int) -> str: """Format size in human-readable form""" for unit in ['B', 'KB', 'MB', 'GB']: if size < 1024: return f"{size:.1f} {unit}" size /= 1024 return f"{size:.1f} TB" def perform_cleanup( self, preserve_library: bool = False, dry_run: bool = False ) -> Dict[str, Any]: """ Perform the actual cleanup Args: preserve_library: Keep library.json if True dry_run: Preview only, don't delete Returns: Dict with cleanup results """ cleanup_data = self.get_cleanup_paths(preserve_library) deleted_items = [] failed_items = [] deleted_size = 0 if dry_run: return { 'dry_run': True, 'would_delete': cleanup_data['total_items'], 'would_free': cleanup_data['total_size'] } # Perform deletion for category, items in cleanup_data['categories'].items(): for item_info in items: path = Path(item_info['path']) try: if path.exists(): if path.is_dir(): shutil.rmtree(path) else: path.unlink() deleted_items.append(str(path)) deleted_size += item_info['size'] print(f" ✅ Deleted: {path.name}") except Exception as e: failed_items.append({ 'path': str(path), 'error': str(e) }) print(f" ❌ Failed: {path.name} ({e})") # Recreate browser_state dir if everything was deleted if not preserve_library and not failed_items: browser_state_dir = self.data_dir / "browser_state" browser_state_dir.mkdir(parents=True, exist_ok=True) return { 'deleted_items': deleted_items, 'failed_items': failed_items, 'deleted_size': deleted_size, 'deleted_count': len(deleted_items), 'failed_count': len(failed_items) } def print_cleanup_preview(self, preserve_library: bool = False): """Print a preview of what will be cleaned""" data = self.get_cleanup_paths(preserve_library) print("\n🔍 Cleanup Preview") print("=" * 60) for category, items in data['categories'].items(): if items: print(f"\n📁 {category.replace('_', ' ').title()}:") for item in items: path = Path(item['path']) size_str = self._format_size(item['size']) type_icon = "📂" if item['type'] == 'dir' else "📄" print(f" {type_icon} {path.name:<30} {size_str:>10}") print("\n" + "=" * 60) print(f"Total items: {data['total_items']}") print(f"Total size: {self._format_size(data['total_size'])}") if preserve_library: print("\n📚 Library will be preserved") print("\nThis preview shows what would be deleted.") print("Use --confirm to actually perform the cleanup.") def main(): """Command-line interface for cleanup management""" parser = argparse.ArgumentParser( description='Clean up NotebookLM skill data', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: # Preview what will be deleted python cleanup_manager.py # Perform cleanup (delete everything) python cleanup_manager.py --confirm # Cleanup but keep library python cleanup_manager.py --confirm --preserve-library # Force cleanup without preview python cleanup_manager.py --confirm --force """ ) parser.add_argument( '--confirm', action='store_true', help='Actually perform the cleanup (without this, only preview)' ) parser.add_argument( '--preserve-library', action='store_true', help='Keep the notebook library (library.json)' ) parser.add_argument( '--force', action='store_true', help='Skip confirmation prompt' ) args = parser.parse_args() # Initialize manager manager = CleanupManager() if args.confirm: # Show preview first unless forced if not args.force: manager.print_cleanup_preview(args.preserve_library) print("\n⚠️ WARNING: This will delete the files shown above!") print(" Note: .venv is preserved (part of skill infrastructure)") response = input("Are you sure? (yes/no): ") if response.lower() != 'yes': print("Cleanup cancelled.") return # Perform cleanup print("\n🗑️ Performing cleanup...") result = manager.perform_cleanup(args.preserve_library, dry_run=False) print(f"\n✅ Cleanup complete!") print(f" Deleted: {result['deleted_count']} items") print(f" Freed: {manager._format_size(result['deleted_size'])}") if result['failed_count'] > 0: print(f" ⚠️ Failed: {result['failed_count']} items") else: # Just show preview manager.print_cleanup_preview(args.preserve_library) print("\n💡 Note: Virtual environment (.venv) is never deleted") print(" It's part of the skill infrastructure, not user data") if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/productivity/notebooklm/scripts/cleanup_manager.py", "license": "MIT License", "lines": 252, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/productivity/notebooklm/scripts/config.py
""" Configuration for NotebookLM Skill Centralizes constants, selectors, and paths """ from pathlib import Path # Paths SKILL_DIR = Path(__file__).parent.parent DATA_DIR = SKILL_DIR / "data" BROWSER_STATE_DIR = DATA_DIR / "browser_state" BROWSER_PROFILE_DIR = BROWSER_STATE_DIR / "browser_profile" STATE_FILE = BROWSER_STATE_DIR / "state.json" AUTH_INFO_FILE = DATA_DIR / "auth_info.json" LIBRARY_FILE = DATA_DIR / "library.json" # NotebookLM Selectors QUERY_INPUT_SELECTORS = [ "textarea.query-box-input", # Primary 'textarea[aria-label="Feld für Anfragen"]', # Fallback German 'textarea[aria-label="Input for queries"]', # Fallback English ] RESPONSE_SELECTORS = [ ".to-user-container .message-text-content", # Primary "[data-message-author='bot']", "[data-message-author='assistant']", ] # Browser Configuration BROWSER_ARGS = [ '--disable-blink-features=AutomationControlled', # Patches navigator.webdriver '--disable-dev-shm-usage', '--no-sandbox', '--no-first-run', '--no-default-browser-check' ] USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' # Timeouts LOGIN_TIMEOUT_MINUTES = 10 QUERY_TIMEOUT_SECONDS = 120 PAGE_LOAD_TIMEOUT = 30000
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/productivity/notebooklm/scripts/config.py", "license": "MIT License", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
davila7/claude-code-templates:cli-tool/components/skills/productivity/notebooklm/scripts/notebook_manager.py
#!/usr/bin/env python3 """ Notebook Library Management for NotebookLM Manages a library of NotebookLM notebooks with metadata Based on the MCP server implementation """ import json import argparse import uuid import os from pathlib import Path from typing import Dict, List, Optional, Any from datetime import datetime class NotebookLibrary: """Manages a collection of NotebookLM notebooks with metadata""" def __init__(self): """Initialize the notebook library""" # Store data within the skill directory skill_dir = Path(__file__).parent.parent self.data_dir = skill_dir / "data" self.data_dir.mkdir(parents=True, exist_ok=True) self.library_file = self.data_dir / "library.json" self.notebooks: Dict[str, Dict[str, Any]] = {} self.active_notebook_id: Optional[str] = None # Load existing library self._load_library() def _load_library(self): """Load library from disk""" if self.library_file.exists(): try: with open(self.library_file, 'r') as f: data = json.load(f) self.notebooks = data.get('notebooks', {}) self.active_notebook_id = data.get('active_notebook_id') print(f"📚 Loaded library with {len(self.notebooks)} notebooks") except Exception as e: print(f"⚠️ Error loading library: {e}") self.notebooks = {} self.active_notebook_id = None else: self._save_library() def _save_library(self): """Save library to disk""" try: data = { 'notebooks': self.notebooks, 'active_notebook_id': self.active_notebook_id, 'updated_at': datetime.now().isoformat() } with open(self.library_file, 'w') as f: json.dump(data, f, indent=2) except Exception as e: print(f"❌ Error saving library: {e}") def add_notebook( self, url: str, name: str, description: str, topics: List[str], content_types: Optional[List[str]] = None, use_cases: Optional[List[str]] = None, tags: Optional[List[str]] = None ) -> Dict[str, Any]: """ Add a new notebook to the library Args: url: NotebookLM notebook URL name: Display name for the notebook description: What's in this notebook topics: Topics covered content_types: Types of content (optional) use_cases: When to use this notebook (optional) tags: Additional tags for organization (optional) Returns: The created notebook object """ # Generate ID from name notebook_id = name.lower().replace(' ', '-').replace('_', '-') # Check for duplicates if notebook_id in self.notebooks: raise ValueError(f"Notebook with ID '{notebook_id}' already exists") # Create notebook object notebook = { 'id': notebook_id, 'url': url, 'name': name, 'description': description, 'topics': topics, 'content_types': content_types or [], 'use_cases': use_cases or [], 'tags': tags or [], 'created_at': datetime.now().isoformat(), 'updated_at': datetime.now().isoformat(), 'use_count': 0, 'last_used': None } # Add to library self.notebooks[notebook_id] = notebook # Set as active if it's the first notebook if len(self.notebooks) == 1: self.active_notebook_id = notebook_id self._save_library() print(f"✅ Added notebook: {name} ({notebook_id})") return notebook def remove_notebook(self, notebook_id: str) -> bool: """ Remove a notebook from the library Args: notebook_id: ID of notebook to remove Returns: True if removed, False if not found """ if notebook_id in self.notebooks: del self.notebooks[notebook_id] # Clear active if it was removed if self.active_notebook_id == notebook_id: self.active_notebook_id = None # Set new active if there are other notebooks if self.notebooks: self.active_notebook_id = list(self.notebooks.keys())[0] self._save_library() print(f"✅ Removed notebook: {notebook_id}") return True print(f"⚠️ Notebook not found: {notebook_id}") return False def update_notebook( self, notebook_id: str, name: Optional[str] = None, description: Optional[str] = None, topics: Optional[List[str]] = None, content_types: Optional[List[str]] = None, use_cases: Optional[List[str]] = None, tags: Optional[List[str]] = None, url: Optional[str] = None ) -> Dict[str, Any]: """ Update notebook metadata Args: notebook_id: ID of notebook to update Other args: Fields to update (None = keep existing) Returns: Updated notebook object """ if notebook_id not in self.notebooks: raise ValueError(f"Notebook not found: {notebook_id}") notebook = self.notebooks[notebook_id] # Update fields if provided if name is not None: notebook['name'] = name if description is not None: notebook['description'] = description if topics is not None: notebook['topics'] = topics if content_types is not None: notebook['content_types'] = content_types if use_cases is not None: notebook['use_cases'] = use_cases if tags is not None: notebook['tags'] = tags if url is not None: notebook['url'] = url notebook['updated_at'] = datetime.now().isoformat() self._save_library() print(f"✅ Updated notebook: {notebook['name']}") return notebook def get_notebook(self, notebook_id: str) -> Optional[Dict[str, Any]]: """Get a specific notebook by ID""" return self.notebooks.get(notebook_id) def list_notebooks(self) -> List[Dict[str, Any]]: """List all notebooks in the library""" return list(self.notebooks.values()) def search_notebooks(self, query: str) -> List[Dict[str, Any]]: """ Search notebooks by query Args: query: Search query (searches name, description, topics, tags) Returns: List of matching notebooks """ query_lower = query.lower() results = [] for notebook in self.notebooks.values(): # Search in various fields searchable = [ notebook['name'].lower(), notebook['description'].lower(), ' '.join(notebook['topics']).lower(), ' '.join(notebook['tags']).lower(), ' '.join(notebook.get('use_cases', [])).lower() ] if any(query_lower in field for field in searchable): results.append(notebook) return results def select_notebook(self, notebook_id: str) -> Dict[str, Any]: """ Set a notebook as active Args: notebook_id: ID of notebook to activate Returns: The activated notebook """ if notebook_id not in self.notebooks: raise ValueError(f"Notebook not found: {notebook_id}") self.active_notebook_id = notebook_id self._save_library() notebook = self.notebooks[notebook_id] print(f"✅ Activated notebook: {notebook['name']}") return notebook def get_active_notebook(self) -> Optional[Dict[str, Any]]: """Get the currently active notebook""" if self.active_notebook_id: return self.notebooks.get(self.active_notebook_id) return None def increment_use_count(self, notebook_id: str) -> Dict[str, Any]: """ Increment usage counter for a notebook Args: notebook_id: ID of notebook that was used Returns: Updated notebook """ if notebook_id not in self.notebooks: raise ValueError(f"Notebook not found: {notebook_id}") notebook = self.notebooks[notebook_id] notebook['use_count'] += 1 notebook['last_used'] = datetime.now().isoformat() self._save_library() return notebook def get_stats(self) -> Dict[str, Any]: """Get library statistics""" total_notebooks = len(self.notebooks) total_topics = set() total_use_count = 0 for notebook in self.notebooks.values(): total_topics.update(notebook['topics']) total_use_count += notebook['use_count'] # Find most used most_used = None if self.notebooks: most_used = max( self.notebooks.values(), key=lambda n: n['use_count'] ) return { 'total_notebooks': total_notebooks, 'total_topics': len(total_topics), 'total_use_count': total_use_count, 'active_notebook': self.get_active_notebook(), 'most_used_notebook': most_used, 'library_path': str(self.library_file) } def main(): """Command-line interface for notebook management""" parser = argparse.ArgumentParser(description='Manage NotebookLM library') subparsers = parser.add_subparsers(dest='command', help='Commands') # Add command add_parser = subparsers.add_parser('add', help='Add a notebook') add_parser.add_argument('--url', required=True, help='NotebookLM URL') add_parser.add_argument('--name', required=True, help='Display name') add_parser.add_argument('--description', required=True, help='Description') add_parser.add_argument('--topics', required=True, help='Comma-separated topics') add_parser.add_argument('--use-cases', help='Comma-separated use cases') add_parser.add_argument('--tags', help='Comma-separated tags') # List command subparsers.add_parser('list', help='List all notebooks') # Search command search_parser = subparsers.add_parser('search', help='Search notebooks') search_parser.add_argument('--query', required=True, help='Search query') # Activate command activate_parser = subparsers.add_parser('activate', help='Set active notebook') activate_parser.add_argument('--id', required=True, help='Notebook ID') # Remove command remove_parser = subparsers.add_parser('remove', help='Remove a notebook') remove_parser.add_argument('--id', required=True, help='Notebook ID') # Stats command subparsers.add_parser('stats', help='Show library statistics') args = parser.parse_args() # Initialize library library = NotebookLibrary() # Execute command if args.command == 'add': topics = [t.strip() for t in args.topics.split(',')] use_cases = [u.strip() for u in args.use_cases.split(',')] if args.use_cases else None tags = [t.strip() for t in args.tags.split(',')] if args.tags else None notebook = library.add_notebook( url=args.url, name=args.name, description=args.description, topics=topics, use_cases=use_cases, tags=tags ) print(json.dumps(notebook, indent=2)) elif args.command == 'list': notebooks = library.list_notebooks() if notebooks: print("\n📚 Notebook Library:") for notebook in notebooks: active = " [ACTIVE]" if notebook['id'] == library.active_notebook_id else "" print(f"\n 📓 {notebook['name']}{active}") print(f" ID: {notebook['id']}") print(f" Topics: {', '.join(notebook['topics'])}") print(f" Uses: {notebook['use_count']}") else: print("📚 Library is empty. Add notebooks with: notebook_manager.py add") elif args.command == 'search': results = library.search_notebooks(args.query) if results: print(f"\n🔍 Found {len(results)} notebooks:") for notebook in results: print(f"\n 📓 {notebook['name']} ({notebook['id']})") print(f" {notebook['description']}") else: print(f"🔍 No notebooks found for: {args.query}") elif args.command == 'activate': notebook = library.select_notebook(args.id) print(f"Now using: {notebook['name']}") elif args.command == 'remove': if library.remove_notebook(args.id): print("Notebook removed from library") elif args.command == 'stats': stats = library.get_stats() print("\n📊 Library Statistics:") print(f" Total notebooks: {stats['total_notebooks']}") print(f" Total topics: {stats['total_topics']}") print(f" Total uses: {stats['total_use_count']}") if stats['active_notebook']: print(f" Active: {stats['active_notebook']['name']}") if stats['most_used_notebook']: print(f" Most used: {stats['most_used_notebook']['name']} ({stats['most_used_notebook']['use_count']} uses)") print(f" Library path: {stats['library_path']}") else: parser.print_help() if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/productivity/notebooklm/scripts/notebook_manager.py", "license": "MIT License", "lines": 336, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/productivity/notebooklm/scripts/run.py
#!/usr/bin/env python3 """ Universal runner for NotebookLM skill scripts Ensures all scripts run with the correct virtual environment """ import os import sys import subprocess from pathlib import Path def get_venv_python(): """Get the virtual environment Python executable""" skill_dir = Path(__file__).parent.parent venv_dir = skill_dir / ".venv" if os.name == 'nt': # Windows venv_python = venv_dir / "Scripts" / "python.exe" else: # Unix/Linux/Mac venv_python = venv_dir / "bin" / "python" return venv_python def ensure_venv(): """Ensure virtual environment exists""" skill_dir = Path(__file__).parent.parent venv_dir = skill_dir / ".venv" setup_script = skill_dir / "scripts" / "setup_environment.py" # Check if venv exists if not venv_dir.exists(): print("🔧 First-time setup: Creating virtual environment...") print(" This may take a minute...") # Run setup with system Python result = subprocess.run([sys.executable, str(setup_script)]) if result.returncode != 0: print("❌ Failed to set up environment") sys.exit(1) print("✅ Environment ready!") return get_venv_python() def main(): """Main runner""" if len(sys.argv) < 2: print("Usage: python run.py <script_name> [args...]") print("\nAvailable scripts:") print(" ask_question.py - Query NotebookLM") print(" notebook_manager.py - Manage notebook library") print(" session_manager.py - Manage sessions") print(" auth_manager.py - Handle authentication") print(" cleanup_manager.py - Clean up skill data") sys.exit(1) script_name = sys.argv[1] script_args = sys.argv[2:] # Handle both "scripts/script.py" and "script.py" formats if script_name.startswith('scripts/'): # Remove the scripts/ prefix if provided script_name = script_name[8:] # len('scripts/') = 8 # Ensure .py extension if not script_name.endswith('.py'): script_name += '.py' # Get script path skill_dir = Path(__file__).parent.parent script_path = skill_dir / "scripts" / script_name if not script_path.exists(): print(f"❌ Script not found: {script_name}") print(f" Working directory: {Path.cwd()}") print(f" Skill directory: {skill_dir}") print(f" Looked for: {script_path}") sys.exit(1) # Ensure venv exists and get Python executable venv_python = ensure_venv() # Build command cmd = [str(venv_python), str(script_path)] + script_args # Run the script try: result = subprocess.run(cmd) sys.exit(result.returncode) except KeyboardInterrupt: print("\n⚠️ Interrupted by user") sys.exit(130) except Exception as e: print(f"❌ Error: {e}") sys.exit(1) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/productivity/notebooklm/scripts/run.py", "license": "MIT License", "lines": 79, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/productivity/notebooklm/scripts/setup_environment.py
#!/usr/bin/env python3 """ Environment Setup for NotebookLM Skill Manages virtual environment and dependencies automatically """ import os import sys import subprocess import venv from pathlib import Path class SkillEnvironment: """Manages skill-specific virtual environment""" def __init__(self): # Skill directory paths self.skill_dir = Path(__file__).parent.parent self.venv_dir = self.skill_dir / ".venv" self.requirements_file = self.skill_dir / "requirements.txt" # Python executable in venv if os.name == 'nt': # Windows self.venv_python = self.venv_dir / "Scripts" / "python.exe" self.venv_pip = self.venv_dir / "Scripts" / "pip.exe" else: # Unix/Linux/Mac self.venv_python = self.venv_dir / "bin" / "python" self.venv_pip = self.venv_dir / "bin" / "pip" def ensure_venv(self) -> bool: """Ensure virtual environment exists and is set up""" # Check if we're already in the correct venv if self.is_in_skill_venv(): print("✅ Already running in skill virtual environment") return True # Create venv if it doesn't exist if not self.venv_dir.exists(): print(f"🔧 Creating virtual environment in {self.venv_dir.name}/") try: venv.create(self.venv_dir, with_pip=True) print("✅ Virtual environment created") except Exception as e: print(f"❌ Failed to create venv: {e}") return False # Install/update dependencies if self.requirements_file.exists(): print("📦 Installing dependencies...") try: # Upgrade pip first subprocess.run( [str(self.venv_pip), "install", "--upgrade", "pip"], check=True, capture_output=True, text=True ) # Install requirements result = subprocess.run( [str(self.venv_pip), "install", "-r", str(self.requirements_file)], check=True, capture_output=True, text=True ) print("✅ Dependencies installed") # Install Chrome for Patchright (not Chromium!) # Using real Chrome ensures cross-platform reliability and consistent browser fingerprinting # See: https://github.com/Kaliiiiiiiiii-Vinyzu/patchright-python#anti-detection print("🌐 Installing Google Chrome for Patchright...") try: subprocess.run( [str(self.venv_python), "-m", "patchright", "install", "chrome"], check=True, capture_output=True, text=True ) print("✅ Chrome installed") except subprocess.CalledProcessError as e: print(f"⚠️ Warning: Failed to install Chrome: {e}") print(" You may need to run manually: python -m patchright install chrome") print(" Chrome is required (not Chromium) for reliability!") return True except subprocess.CalledProcessError as e: print(f"❌ Failed to install dependencies: {e}") print(f" Output: {e.output if hasattr(e, 'output') else 'No output'}") return False else: print("⚠️ No requirements.txt found, skipping dependency installation") return True def is_in_skill_venv(self) -> bool: """Check if we're already running in the skill's venv""" if hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix): # We're in a venv, check if it's ours venv_path = Path(sys.prefix) return venv_path == self.venv_dir return False def get_python_executable(self) -> str: """Get the correct Python executable to use""" if self.venv_python.exists(): return str(self.venv_python) return sys.executable def run_script(self, script_name: str, args: list = None) -> int: """Run a script with the virtual environment""" script_path = self.skill_dir / "scripts" / script_name if not script_path.exists(): print(f"❌ Script not found: {script_path}") return 1 # Ensure venv is set up if not self.ensure_venv(): print("❌ Failed to set up environment") return 1 # Build command cmd = [str(self.venv_python), str(script_path)] if args: cmd.extend(args) print(f"🚀 Running: {script_name} with venv Python") try: # Run the script with venv Python result = subprocess.run(cmd) return result.returncode except Exception as e: print(f"❌ Failed to run script: {e}") return 1 def activate_instructions(self) -> str: """Get instructions for manual activation""" if os.name == 'nt': activate = self.venv_dir / "Scripts" / "activate.bat" return f"Run: {activate}" else: activate = self.venv_dir / "bin" / "activate" return f"Run: source {activate}" def main(): """Main entry point for environment setup""" import argparse parser = argparse.ArgumentParser( description='Setup NotebookLM skill environment' ) parser.add_argument( '--check', action='store_true', help='Check if environment is set up' ) parser.add_argument( '--run', help='Run a script with the venv (e.g., --run ask_question.py)' ) parser.add_argument( 'args', nargs='*', help='Arguments to pass to the script' ) args = parser.parse_args() env = SkillEnvironment() if args.check: if env.venv_dir.exists(): print(f"✅ Virtual environment exists: {env.venv_dir}") print(f" Python: {env.get_python_executable()}") print(f" To activate manually: {env.activate_instructions()}") else: print(f"❌ No virtual environment found") print(f" Run setup_environment.py to create it") return if args.run: # Run a script with venv return env.run_script(args.run, args.args) # Default: ensure environment is set up if env.ensure_venv(): print("\n✅ Environment ready!") print(f" Virtual env: {env.venv_dir}") print(f" Python: {env.get_python_executable()}") print(f"\nTo activate manually: {env.activate_instructions()}") print(f"Or run scripts directly: python setup_environment.py --run script_name.py") else: print("\n❌ Environment setup failed") return 1 if __name__ == "__main__": sys.exit(main() or 0)
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/productivity/notebooklm/scripts/setup_environment.py", "license": "MIT License", "lines": 170, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/security/vulnerability-scanner/scripts/security_scan.py
#!/usr/bin/env python3 """ Skill: vulnerability-scanner Script: security_scan.py Purpose: Validate that security principles from SKILL.md are applied correctly Usage: python security_scan.py <project_path> [--scan-type all|deps|secrets|patterns|config] Output: JSON with validation findings This script verifies: 1. Dependencies - Supply chain security (OWASP A03) 2. Secrets - No hardcoded credentials (OWASP A04) 3. Code Patterns - Dangerous patterns identified (OWASP A05) 4. Configuration - Security settings validated (OWASP A02) """ import subprocess import json import os import sys import re import argparse from pathlib import Path from typing import Dict, List, Any from datetime import datetime # Fix Windows console encoding for Unicode output try: sys.stdout.reconfigure(encoding='utf-8', errors='replace') sys.stderr.reconfigure(encoding='utf-8', errors='replace') except AttributeError: pass # Python < 3.7 # ============================================================================ # CONFIGURATION # ============================================================================ SECRET_PATTERNS = [ # API Keys & Tokens (r'api[_-]?key\s*[=:]\s*["\'][^"\']{10,}["\']', "API Key", "high"), (r'token\s*[=:]\s*["\'][^"\']{10,}["\']', "Token", "high"), (r'bearer\s+[a-zA-Z0-9\-_.]+', "Bearer Token", "critical"), # Cloud Credentials (r'AKIA[0-9A-Z]{16}', "AWS Access Key", "critical"), (r'aws[_-]?secret[_-]?access[_-]?key\s*[=:]\s*["\'][^"\']+["\']', "AWS Secret", "critical"), (r'AZURE[_-]?[A-Z_]+\s*[=:]\s*["\'][^"\']+["\']', "Azure Credential", "critical"), (r'GOOGLE[_-]?[A-Z_]+\s*[=:]\s*["\'][^"\']+["\']', "GCP Credential", "critical"), # Database & Connections (r'password\s*[=:]\s*["\'][^"\']{4,}["\']', "Password", "high"), (r'(mongodb|postgres|mysql|redis):\/\/[^\s"\']+', "Database Connection String", "critical"), # Private Keys (r'-----BEGIN\s+(RSA|PRIVATE|EC)\s+KEY-----', "Private Key", "critical"), (r'ssh-rsa\s+[A-Za-z0-9+/]+', "SSH Key", "critical"), # JWT (r'eyJ[A-Za-z0-9-_]+\.eyJ[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+', "JWT Token", "high"), ] DANGEROUS_PATTERNS = [ # Injection risks (r'eval\s*\(', "eval() usage", "critical", "Code Injection risk"), (r'exec\s*\(', "exec() usage", "critical", "Code Injection risk"), (r'new\s+Function\s*\(', "Function constructor", "high", "Code Injection risk"), (r'child_process\.exec\s*\(', "child_process.exec", "high", "Command Injection risk"), (r'subprocess\.call\s*\([^)]*shell\s*=\s*True', "subprocess with shell=True", "high", "Command Injection risk"), # XSS risks (r'dangerouslySetInnerHTML', "dangerouslySetInnerHTML", "high", "XSS risk"), (r'\.innerHTML\s*=', "innerHTML assignment", "medium", "XSS risk"), (r'document\.write\s*\(', "document.write", "medium", "XSS risk"), # SQL Injection indicators (r'["\'][^"\']*\+\s*[a-zA-Z_]+\s*\+\s*["\'].*(?:SELECT|INSERT|UPDATE|DELETE)', "SQL String Concat", "critical", "SQL Injection risk"), (r'f"[^"]*(?:SELECT|INSERT|UPDATE|DELETE)[^"]*\{', "SQL f-string", "critical", "SQL Injection risk"), # Insecure configurations (r'verify\s*=\s*False', "SSL Verify Disabled", "high", "MITM risk"), (r'--insecure', "Insecure flag", "medium", "Security disabled"), (r'disable[_-]?ssl', "SSL Disabled", "high", "MITM risk"), # Unsafe deserialization (r'pickle\.loads?\s*\(', "pickle usage", "high", "Deserialization risk"), (r'yaml\.load\s*\([^)]*\)(?!\s*,\s*Loader)', "Unsafe YAML load", "high", "Deserialization risk"), ] SKIP_DIRS = {'node_modules', '.git', 'dist', 'build', '__pycache__', '.venv', 'venv', '.next'} CODE_EXTENSIONS = {'.js', '.ts', '.jsx', '.tsx', '.py', '.go', '.java', '.rb', '.php'} CONFIG_EXTENSIONS = {'.json', '.yaml', '.yml', '.toml', '.env', '.env.local', '.env.development'} # ============================================================================ # SCANNING FUNCTIONS # ============================================================================ def scan_dependencies(project_path: str) -> Dict[str, Any]: """ Validate supply chain security (OWASP A03). Checks: npm audit, lock file presence, dependency age. """ results = {"tool": "dependency_scanner", "findings": [], "status": "[OK] Secure"} # Check for lock files lock_files = { "npm": ["package-lock.json", "npm-shrinkwrap.json"], "yarn": ["yarn.lock"], "pnpm": ["pnpm-lock.yaml"], "pip": ["requirements.txt", "Pipfile.lock", "poetry.lock"], } found_locks = [] missing_locks = [] for manager, files in lock_files.items(): pkg_file = "package.json" if manager in ["npm", "yarn", "pnpm"] else "setup.py" pkg_path = Path(project_path) / pkg_file if pkg_path.exists() or (manager == "pip" and (Path(project_path) / "requirements.txt").exists()): has_lock = any((Path(project_path) / f).exists() for f in files) if has_lock: found_locks.append(manager) else: missing_locks.append(manager) results["findings"].append({ "type": "Missing Lock File", "severity": "high", "message": f"{manager}: No lock file found. Supply chain integrity at risk." }) # Run npm audit if applicable if (Path(project_path) / "package.json").exists(): try: result = subprocess.run( ["npm", "audit", "--json"], cwd=project_path, capture_output=True, text=True, timeout=60 ) try: audit_data = json.loads(result.stdout) vulnerabilities = audit_data.get("vulnerabilities", {}) severity_count = {"critical": 0, "high": 0, "moderate": 0, "low": 0} for vuln in vulnerabilities.values(): sev = vuln.get("severity", "low").lower() if sev in severity_count: severity_count[sev] += 1 if severity_count["critical"] > 0: results["status"] = "[!!] Critical vulnerabilities" results["findings"].append({ "type": "npm audit", "severity": "critical", "message": f"{severity_count['critical']} critical vulnerabilities in dependencies" }) elif severity_count["high"] > 0: results["status"] = "[!] High vulnerabilities" results["findings"].append({ "type": "npm audit", "severity": "high", "message": f"{severity_count['high']} high severity vulnerabilities" }) results["npm_audit"] = severity_count except json.JSONDecodeError: pass except (FileNotFoundError, subprocess.TimeoutExpired): pass if not results["findings"]: results["status"] = "[OK] Supply chain checks passed" return results def scan_secrets(project_path: str) -> Dict[str, Any]: """ Validate no hardcoded secrets (OWASP A04). Checks: API keys, tokens, passwords, cloud credentials. """ results = { "tool": "secret_scanner", "findings": [], "status": "[OK] No secrets detected", "scanned_files": 0, "by_severity": {"critical": 0, "high": 0, "medium": 0} } for root, dirs, files in os.walk(project_path): dirs[:] = [d for d in dirs if d not in SKIP_DIRS] for file in files: ext = Path(file).suffix.lower() if ext not in CODE_EXTENSIONS and ext not in CONFIG_EXTENSIONS: continue filepath = Path(root) / file results["scanned_files"] += 1 try: with open(filepath, 'r', encoding='utf-8', errors='ignore') as f: content = f.read() for pattern, secret_type, severity in SECRET_PATTERNS: matches = re.findall(pattern, content, re.IGNORECASE) if matches: results["findings"].append({ "file": str(filepath.relative_to(project_path)), "type": secret_type, "severity": severity, "count": len(matches) }) results["by_severity"][severity] += len(matches) except Exception: pass if results["by_severity"]["critical"] > 0: results["status"] = "[!!] CRITICAL: Secrets exposed!" elif results["by_severity"]["high"] > 0: results["status"] = "[!] HIGH: Secrets found" elif sum(results["by_severity"].values()) > 0: results["status"] = "[?] Potential secrets detected" # Limit findings for output results["findings"] = results["findings"][:15] return results def scan_code_patterns(project_path: str) -> Dict[str, Any]: """ Validate dangerous code patterns (OWASP A05). Checks: Injection risks, XSS, unsafe deserialization. """ results = { "tool": "pattern_scanner", "findings": [], "status": "[OK] No dangerous patterns", "scanned_files": 0, "by_category": {} } for root, dirs, files in os.walk(project_path): dirs[:] = [d for d in dirs if d not in SKIP_DIRS] for file in files: ext = Path(file).suffix.lower() if ext not in CODE_EXTENSIONS: continue filepath = Path(root) / file results["scanned_files"] += 1 try: with open(filepath, 'r', encoding='utf-8', errors='ignore') as f: lines = f.readlines() for line_num, line in enumerate(lines, 1): for pattern, name, severity, category in DANGEROUS_PATTERNS: if re.search(pattern, line, re.IGNORECASE): results["findings"].append({ "file": str(filepath.relative_to(project_path)), "line": line_num, "pattern": name, "severity": severity, "category": category, "snippet": line.strip()[:80] }) results["by_category"][category] = results["by_category"].get(category, 0) + 1 except Exception: pass critical_count = sum(1 for f in results["findings"] if f["severity"] == "critical") high_count = sum(1 for f in results["findings"] if f["severity"] == "high") if critical_count > 0: results["status"] = f"[!!] CRITICAL: {critical_count} dangerous patterns" elif high_count > 0: results["status"] = f"[!] HIGH: {high_count} risky patterns" elif results["findings"]: results["status"] = "[?] Some patterns need review" # Limit findings results["findings"] = results["findings"][:20] return results def scan_configuration(project_path: str) -> Dict[str, Any]: """ Validate security configuration (OWASP A02). Checks: Security headers, CORS, debug modes. """ results = { "tool": "config_scanner", "findings": [], "status": "[OK] Configuration secure", "checks": {} } # Check common config files for issues config_issues = [ (r'"DEBUG"\s*:\s*true', "Debug mode enabled", "high"), (r'debug\s*=\s*True', "Debug mode enabled", "high"), (r'NODE_ENV.*development', "Development mode in config", "medium"), (r'"CORS_ALLOW_ALL".*true', "CORS allow all origins", "high"), (r'"Access-Control-Allow-Origin".*\*', "CORS wildcard", "high"), (r'allowCredentials.*true.*origin.*\*', "Dangerous CORS combo", "critical"), ] for root, dirs, files in os.walk(project_path): dirs[:] = [d for d in dirs if d not in SKIP_DIRS] for file in files: ext = Path(file).suffix.lower() if ext not in CONFIG_EXTENSIONS and file not in ['next.config.js', 'webpack.config.js', '.eslintrc.js']: continue filepath = Path(root) / file try: with open(filepath, 'r', encoding='utf-8', errors='ignore') as f: content = f.read() for pattern, issue, severity in config_issues: if re.search(pattern, content, re.IGNORECASE): results["findings"].append({ "file": str(filepath.relative_to(project_path)), "issue": issue, "severity": severity }) except Exception: pass # Check for security header configurations header_files = ["next.config.js", "next.config.mjs", "middleware.ts", "nginx.conf"] for hf in header_files: hf_path = Path(project_path) / hf if hf_path.exists(): results["checks"]["security_headers_config"] = True break else: results["checks"]["security_headers_config"] = False results["findings"].append({ "issue": "No security headers configuration found", "severity": "medium", "recommendation": "Configure CSP, HSTS, X-Frame-Options headers" }) if any(f["severity"] == "critical" for f in results["findings"]): results["status"] = "[!!] CRITICAL: Configuration issues" elif any(f["severity"] == "high" for f in results["findings"]): results["status"] = "[!] HIGH: Configuration review needed" elif results["findings"]: results["status"] = "[?] Minor configuration issues" return results # ============================================================================ # MAIN # ============================================================================ def run_full_scan(project_path: str, scan_type: str = "all") -> Dict[str, Any]: """Execute security validation scans.""" report = { "project": project_path, "timestamp": datetime.now().isoformat(), "scan_type": scan_type, "scans": {}, "summary": { "total_findings": 0, "critical": 0, "high": 0, "overall_status": "[OK] SECURE" } } scanners = { "deps": ("dependencies", scan_dependencies), "secrets": ("secrets", scan_secrets), "patterns": ("code_patterns", scan_code_patterns), "config": ("configuration", scan_configuration), } for key, (name, scanner) in scanners.items(): if scan_type == "all" or scan_type == key: result = scanner(project_path) report["scans"][name] = result findings_count = len(result.get("findings", [])) report["summary"]["total_findings"] += findings_count for finding in result.get("findings", []): sev = finding.get("severity", "low") if sev == "critical": report["summary"]["critical"] += 1 elif sev == "high": report["summary"]["high"] += 1 # Determine overall status if report["summary"]["critical"] > 0: report["summary"]["overall_status"] = "[!!] CRITICAL ISSUES FOUND" elif report["summary"]["high"] > 0: report["summary"]["overall_status"] = "[!] HIGH RISK ISSUES" elif report["summary"]["total_findings"] > 0: report["summary"]["overall_status"] = "[?] REVIEW RECOMMENDED" return report def main(): parser = argparse.ArgumentParser( description="Validate security principles from vulnerability-scanner skill" ) parser.add_argument("project_path", nargs="?", default=".", help="Project directory to scan") parser.add_argument("--scan-type", choices=["all", "deps", "secrets", "patterns", "config"], default="all", help="Type of scan to run") parser.add_argument("--output", choices=["json", "summary"], default="json", help="Output format") args = parser.parse_args() if not os.path.isdir(args.project_path): print(json.dumps({"error": f"Directory not found: {args.project_path}"})) sys.exit(1) result = run_full_scan(args.project_path, args.scan_type) if args.output == "summary": print(f"\n{'='*60}") print(f"Security Scan: {result['project']}") print(f"{'='*60}") print(f"Status: {result['summary']['overall_status']}") print(f"Total Findings: {result['summary']['total_findings']}") print(f" Critical: {result['summary']['critical']}") print(f" High: {result['summary']['high']}") print(f"{'='*60}\n") for scan_name, scan_result in result['scans'].items(): print(f"\n{scan_name.upper()}: {scan_result['status']}") for finding in scan_result.get('findings', [])[:5]: print(f" - {finding}") else: print(json.dumps(result, indent=2)) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/security/vulnerability-scanner/scripts/security_scan.py", "license": "MIT License", "lines": 373, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/security/webapp-testing/scripts/with_server.py
#!/usr/bin/env python3 """ Start one or more servers, wait for them to be ready, run a command, then clean up. Usage: # Single server python scripts/with_server.py --server "npm run dev" --port 5173 -- python automation.py python scripts/with_server.py --server "npm start" --port 3000 -- python test.py # Multiple servers python scripts/with_server.py \ --server "cd backend && python server.py" --port 3000 \ --server "cd frontend && npm run dev" --port 5173 \ -- python test.py """ import subprocess import socket import time import sys import argparse def is_server_ready(port, timeout=30): """Wait for server to be ready by polling the port.""" start_time = time.time() while time.time() - start_time < timeout: try: with socket.create_connection(('localhost', port), timeout=1): return True except (socket.error, ConnectionRefusedError): time.sleep(0.5) return False def main(): parser = argparse.ArgumentParser(description='Run command with one or more servers') parser.add_argument('--server', action='append', dest='servers', required=True, help='Server command (can be repeated)') parser.add_argument('--port', action='append', dest='ports', type=int, required=True, help='Port for each server (must match --server count)') parser.add_argument('--timeout', type=int, default=30, help='Timeout in seconds per server (default: 30)') parser.add_argument('command', nargs=argparse.REMAINDER, help='Command to run after server(s) ready') args = parser.parse_args() # Remove the '--' separator if present if args.command and args.command[0] == '--': args.command = args.command[1:] if not args.command: print("Error: No command specified to run") sys.exit(1) # Parse server configurations if len(args.servers) != len(args.ports): print("Error: Number of --server and --port arguments must match") sys.exit(1) servers = [] for cmd, port in zip(args.servers, args.ports): servers.append({'cmd': cmd, 'port': port}) server_processes = [] try: # Start all servers for i, server in enumerate(servers): print(f"Starting server {i+1}/{len(servers)}: {server['cmd']}") # Use shell=True to support commands with cd and && process = subprocess.Popen( server['cmd'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) server_processes.append(process) # Wait for this server to be ready print(f"Waiting for server on port {server['port']}...") if not is_server_ready(server['port'], timeout=args.timeout): raise RuntimeError(f"Server failed to start on port {server['port']} within {args.timeout}s") print(f"Server ready on port {server['port']}") print(f"\nAll {len(servers)} server(s) ready") # Run the command print(f"Running: {' '.join(args.command)}\n") result = subprocess.run(args.command) sys.exit(result.returncode) finally: # Clean up all servers print(f"\nStopping {len(server_processes)} server(s)...") for i, process in enumerate(server_processes): try: process.terminate() process.wait(timeout=5) except subprocess.TimeoutExpired: process.kill() process.wait() print(f"Server {i+1} stopped") print("All servers stopped") if __name__ == '__main__': main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/security/webapp-testing/scripts/with_server.py", "license": "MIT License", "lines": 85, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/utilities/geo-fundamentals/scripts/geo_checker.py
#!/usr/bin/env python3 """ GEO Checker - Generative Engine Optimization Audit Checks PUBLIC WEB CONTENT for AI citation readiness. PURPOSE: - Analyze pages that will be INDEXED by AI engines (ChatGPT, Perplexity, etc.) - Check for structured data, author info, dates, FAQ sections - Help content rank in AI-generated answers WHAT IT CHECKS: - HTML files (actual web pages) - JSX/TSX files (React page components) - NOT markdown files (those are developer docs, not public content) Usage: python geo_checker.py <project_path> """ import sys import re import json from pathlib import Path # Fix Windows console encoding try: sys.stdout.reconfigure(encoding='utf-8', errors='replace') sys.stderr.reconfigure(encoding='utf-8', errors='replace') except AttributeError: pass # Directories to skip (not public content) SKIP_DIRS = { 'node_modules', '.next', 'dist', 'build', '.git', '.github', '__pycache__', '.vscode', '.idea', 'coverage', 'test', 'tests', '__tests__', 'spec', 'docs', 'documentation' } # Files to skip (not public pages) SKIP_FILES = { 'jest.config', 'webpack.config', 'vite.config', 'tsconfig', 'package.json', 'package-lock', 'yarn.lock', '.eslintrc', 'tailwind.config', 'postcss.config', 'next.config' } def is_page_file(file_path: Path) -> bool: """Check if this file is likely a public-facing page.""" name = file_path.stem.lower() # Skip config/utility files if any(skip in name for skip in SKIP_FILES): return False # Skip test files if name.endswith('.test') or name.endswith('.spec'): return False if name.startswith('test_') or name.startswith('spec_'): return False # Likely page indicators page_indicators = ['page', 'index', 'home', 'about', 'contact', 'blog', 'post', 'article', 'product', 'service', 'landing'] # Check if it's in a pages/app directory (Next.js, etc.) parts = [p.lower() for p in file_path.parts] if 'pages' in parts or 'app' in parts or 'routes' in parts: return True # Check filename indicators if any(ind in name for ind in page_indicators): return True # HTML files are usually pages if file_path.suffix.lower() == '.html': return True return False def find_web_pages(project_path: Path) -> list: """Find public-facing web pages only.""" patterns = ['**/*.html', '**/*.htm', '**/*.jsx', '**/*.tsx'] files = [] for pattern in patterns: for f in project_path.glob(pattern): # Skip excluded directories if any(skip in f.parts for skip in SKIP_DIRS): continue # Check if it's likely a page if is_page_file(f): files.append(f) return files[:30] # Limit to 30 pages def check_page(file_path: Path) -> dict: """Check a single web page for GEO elements.""" try: content = file_path.read_text(encoding='utf-8', errors='ignore') except Exception as e: return {'file': str(file_path.name), 'passed': [], 'issues': [f"Error: {e}"], 'score': 0} issues = [] passed = [] # 1. JSON-LD Structured Data (Critical for AI) if 'application/ld+json' in content: passed.append("JSON-LD structured data found") if '"@type"' in content: if 'Article' in content: passed.append("Article schema present") if 'FAQPage' in content: passed.append("FAQ schema present") if 'Organization' in content or 'Person' in content: passed.append("Entity schema present") else: issues.append("No JSON-LD structured data (AI engines prefer structured content)") # 2. Heading Structure h1_count = len(re.findall(r'<h1[^>]*>', content, re.I)) h2_count = len(re.findall(r'<h2[^>]*>', content, re.I)) if h1_count == 1: passed.append("Single H1 heading (clear topic)") elif h1_count == 0: issues.append("No H1 heading - page topic unclear") else: issues.append(f"Multiple H1 headings ({h1_count}) - confusing for AI") if h2_count >= 2: passed.append(f"{h2_count} H2 subheadings (good structure)") else: issues.append("Add more H2 subheadings for scannable content") # 3. Author Attribution (E-E-A-T signal) author_patterns = ['author', 'byline', 'written-by', 'contributor', 'rel="author"'] has_author = any(p in content.lower() for p in author_patterns) if has_author: passed.append("Author attribution found") else: issues.append("No author info (AI prefers attributed content)") # 4. Publication Date (Freshness signal) date_patterns = ['datePublished', 'dateModified', 'datetime=', 'pubdate', 'article:published'] has_date = any(re.search(p, content, re.I) for p in date_patterns) if has_date: passed.append("Publication date found") else: issues.append("No publication date (freshness matters for AI)") # 5. FAQ Section (Highly citable) faq_patterns = [r'<details', r'faq', r'frequently.?asked', r'"FAQPage"'] has_faq = any(re.search(p, content, re.I) for p in faq_patterns) if has_faq: passed.append("FAQ section detected (highly citable)") # 6. Lists (Structured content) list_count = len(re.findall(r'<(ul|ol)[^>]*>', content, re.I)) if list_count >= 2: passed.append(f"{list_count} lists (structured content)") # 7. Tables (Comparison data) table_count = len(re.findall(r'<table[^>]*>', content, re.I)) if table_count >= 1: passed.append(f"{table_count} table(s) (comparison data)") # 8. Entity Recognition (E-E-A-T signal) - NEW 2025 entity_patterns = [ r'"@type"\s*:\s*"Organization"', r'"@type"\s*:\s*"LocalBusiness"', r'"@type"\s*:\s*"Brand"', r'itemtype.*schema\.org/(Organization|Person|Brand)', r'rel="author"' ] has_entity = any(re.search(p, content, re.I) for p in entity_patterns) if has_entity: passed.append("Entity/Brand recognition (E-E-A-T)") # 9. Original Statistics/Data (AI citation magnet) - NEW 2025 stat_patterns = [ r'\d+%', # Percentages r'\$[\d,]+', # Dollar amounts r'study\s+(shows|found)', # Research citations r'according to', # Source attribution r'data\s+(shows|reveals)', # Data-backed claims r'\d+x\s+(faster|better|more)', # Comparison stats r'(million|billion|trillion)', # Large numbers ] stat_matches = sum(1 for p in stat_patterns if re.search(p, content, re.I)) if stat_matches >= 2: passed.append("Original statistics/data (citation magnet)") # 10. Conversational/Direct answers - NEW 2025 direct_answer_patterns = [ r'is defined as', r'refers to', r'means that', r'the answer is', r'in short,', r'simply put,', r'<dfn' ] has_direct = any(re.search(p, content, re.I) for p in direct_answer_patterns) if has_direct: passed.append("Direct answer patterns (LLM-friendly)") # Calculate score total = len(passed) + len(issues) score = (len(passed) / total * 100) if total > 0 else 0 return { 'file': str(file_path.name), 'passed': passed, 'issues': issues, 'score': round(score) } def main(): target = sys.argv[1] if len(sys.argv) > 1 else "." target_path = Path(target).resolve() print("\n" + "=" * 60) print(" GEO CHECKER - AI Citation Readiness Audit") print("=" * 60) print(f"Project: {target_path}") print("-" * 60) # Find web pages only pages = find_web_pages(target_path) if not pages: print("\n[!] No public web pages found.") print(" Looking for: HTML, JSX, TSX files in pages/app directories") print(" Skipping: docs, tests, config files, node_modules") output = {"script": "geo_checker", "pages_found": 0, "passed": True} print("\n" + json.dumps(output, indent=2)) sys.exit(0) print(f"Found {len(pages)} public pages to analyze\n") # Check each page results = [] for page in pages: result = check_page(page) results.append(result) # Print results for result in results: status = "[OK]" if result['score'] >= 60 else "[!]" print(f"{status} {result['file']}: {result['score']}%") if result['issues'] and result['score'] < 60: for issue in result['issues'][:2]: # Show max 2 issues print(f" - {issue}") # Average score avg_score = sum(r['score'] for r in results) / len(results) if results else 0 print("\n" + "=" * 60) print(f"AVERAGE GEO SCORE: {avg_score:.0f}%") print("=" * 60) if avg_score >= 80: print("[OK] Excellent - Content well-optimized for AI citations") elif avg_score >= 60: print("[OK] Good - Some improvements recommended") elif avg_score >= 40: print("[!] Needs work - Add structured elements") else: print("[X] Poor - Content needs GEO optimization") # JSON output output = { "script": "geo_checker", "project": str(target_path), "pages_checked": len(results), "average_score": round(avg_score), "passed": avg_score >= 60 } print("\n" + json.dumps(output, indent=2)) sys.exit(0 if avg_score >= 60 else 1) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/utilities/geo-fundamentals/scripts/geo_checker.py", "license": "MIT License", "lines": 236, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/web-development/shopify-development/scripts/shopify_graphql.py
#!/usr/bin/env python3 """ Shopify GraphQL Utilities Helper functions for common Shopify GraphQL operations. Provides query templates, pagination helpers, and rate limit handling. Usage: from shopify_graphql import ShopifyGraphQL client = ShopifyGraphQL(shop_domain, access_token) products = client.get_products(first=10) """ import os import time import json from typing import Dict, List, Optional, Any, Generator from dataclasses import dataclass from urllib.request import Request, urlopen from urllib.error import HTTPError # API Configuration API_VERSION = "2026-01" MAX_RETRIES = 3 RETRY_DELAY = 1.0 # seconds @dataclass class GraphQLResponse: """Container for GraphQL response data.""" data: Optional[Dict[str, Any]] = None errors: Optional[List[Dict[str, Any]]] = None extensions: Optional[Dict[str, Any]] = None @property def is_success(self) -> bool: return self.errors is None or len(self.errors) == 0 @property def query_cost(self) -> Optional[int]: """Get the actual query cost from extensions.""" if self.extensions and 'cost' in self.extensions: return self.extensions['cost'].get('actualQueryCost') return None class ShopifyGraphQL: """ Shopify GraphQL API client with built-in utilities. Features: - Query templates for common operations - Automatic pagination - Rate limit handling with exponential backoff - Response parsing helpers """ def __init__(self, shop_domain: str, access_token: str): """ Initialize the GraphQL client. Args: shop_domain: Store domain (e.g., 'my-store.myshopify.com') access_token: Admin API access token """ self.shop_domain = shop_domain.replace('https://', '').replace('http://', '') self.access_token = access_token self.base_url = f"https://{self.shop_domain}/admin/api/{API_VERSION}/graphql.json" def execute(self, query: str, variables: Optional[Dict] = None) -> GraphQLResponse: """ Execute a GraphQL query/mutation. Args: query: GraphQL query string variables: Query variables Returns: GraphQLResponse object """ payload = {"query": query} if variables: payload["variables"] = variables headers = { "Content-Type": "application/json", "X-Shopify-Access-Token": self.access_token } for attempt in range(MAX_RETRIES): try: request = Request( self.base_url, data=json.dumps(payload).encode('utf-8'), headers=headers, method='POST' ) with urlopen(request, timeout=30) as response: result = json.loads(response.read().decode('utf-8')) return GraphQLResponse( data=result.get('data'), errors=result.get('errors'), extensions=result.get('extensions') ) except HTTPError as e: if e.code == 429: # Rate limited delay = RETRY_DELAY * (2 ** attempt) print(f"Rate limited. Retrying in {delay}s...") time.sleep(delay) continue raise except Exception as e: if attempt == MAX_RETRIES - 1: raise time.sleep(RETRY_DELAY) return GraphQLResponse(errors=[{"message": "Max retries exceeded"}]) # ==================== Query Templates ==================== def get_products( self, first: int = 10, query: Optional[str] = None, after: Optional[str] = None ) -> GraphQLResponse: """ Query products with pagination. Args: first: Number of products to fetch (max 250) query: Optional search query after: Cursor for pagination """ gql = """ query GetProducts($first: Int!, $query: String, $after: String) { products(first: $first, query: $query, after: $after) { edges { node { id title handle status totalInventory variants(first: 5) { edges { node { id title price inventoryQuantity sku } } } } cursor } pageInfo { hasNextPage endCursor } } } """ return self.execute(gql, {"first": first, "query": query, "after": after}) def get_orders( self, first: int = 10, query: Optional[str] = None, after: Optional[str] = None ) -> GraphQLResponse: """ Query orders with pagination. Args: first: Number of orders to fetch (max 250) query: Optional search query (e.g., "financial_status:paid") after: Cursor for pagination """ gql = """ query GetOrders($first: Int!, $query: String, $after: String) { orders(first: $first, query: $query, after: $after) { edges { node { id name createdAt displayFinancialStatus displayFulfillmentStatus totalPriceSet { shopMoney { amount currencyCode } } customer { id firstName lastName } lineItems(first: 5) { edges { node { title quantity } } } } cursor } pageInfo { hasNextPage endCursor } } } """ return self.execute(gql, {"first": first, "query": query, "after": after}) def get_customers( self, first: int = 10, query: Optional[str] = None, after: Optional[str] = None ) -> GraphQLResponse: """ Query customers with pagination. Args: first: Number of customers to fetch (max 250) query: Optional search query after: Cursor for pagination """ gql = """ query GetCustomers($first: Int!, $query: String, $after: String) { customers(first: $first, query: $query, after: $after) { edges { node { id firstName lastName displayName defaultEmailAddress { emailAddress } numberOfOrders amountSpent { amount currencyCode } } cursor } pageInfo { hasNextPage endCursor } } } """ return self.execute(gql, {"first": first, "query": query, "after": after}) def set_metafields(self, metafields: List[Dict]) -> GraphQLResponse: """ Set metafields on resources. Args: metafields: List of metafield inputs, each containing: - ownerId: Resource GID - namespace: Metafield namespace - key: Metafield key - value: Metafield value - type: Metafield type """ gql = """ mutation SetMetafields($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { metafields { id namespace key value } userErrors { field message } } } """ return self.execute(gql, {"metafields": metafields}) # ==================== Pagination Helpers ==================== def paginate_products( self, batch_size: int = 50, query: Optional[str] = None ) -> Generator[Dict, None, None]: """ Generator that yields all products with automatic pagination. Args: batch_size: Products per request (max 250) query: Optional search query Yields: Product dictionaries """ cursor = None while True: response = self.get_products(first=batch_size, query=query, after=cursor) if not response.is_success or not response.data: break products = response.data.get('products', {}) edges = products.get('edges', []) for edge in edges: yield edge['node'] page_info = products.get('pageInfo', {}) if not page_info.get('hasNextPage'): break cursor = page_info.get('endCursor') def paginate_orders( self, batch_size: int = 50, query: Optional[str] = None ) -> Generator[Dict, None, None]: """ Generator that yields all orders with automatic pagination. Args: batch_size: Orders per request (max 250) query: Optional search query Yields: Order dictionaries """ cursor = None while True: response = self.get_orders(first=batch_size, query=query, after=cursor) if not response.is_success or not response.data: break orders = response.data.get('orders', {}) edges = orders.get('edges', []) for edge in edges: yield edge['node'] page_info = orders.get('pageInfo', {}) if not page_info.get('hasNextPage'): break cursor = page_info.get('endCursor') # ==================== Utility Functions ==================== def extract_id(gid: str) -> str: """ Extract numeric ID from Shopify GID. Args: gid: Global ID (e.g., 'gid://shopify/Product/123') Returns: Numeric ID string (e.g., '123') """ return gid.split('/')[-1] if gid else '' def build_gid(resource_type: str, id: str) -> str: """ Build Shopify GID from resource type and ID. Args: resource_type: Resource type (e.g., 'Product', 'Order') id: Numeric ID Returns: Global ID (e.g., 'gid://shopify/Product/123') """ return f"gid://shopify/{resource_type}/{id}" # ==================== Example Usage ==================== def main(): """Example usage of ShopifyGraphQL client.""" import os # Load from environment shop = os.environ.get('SHOP_DOMAIN', 'your-store.myshopify.com') token = os.environ.get('SHOPIFY_ACCESS_TOKEN', '') if not token: print("Set SHOPIFY_ACCESS_TOKEN environment variable") return client = ShopifyGraphQL(shop, token) # Example: Get first 5 products print("Fetching products...") response = client.get_products(first=5) if response.is_success: products = response.data['products']['edges'] for edge in products: product = edge['node'] print(f" - {product['title']} ({product['status']})") print(f"\nQuery cost: {response.query_cost}") else: print(f"Errors: {response.errors}") if __name__ == '__main__': main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/web-development/shopify-development/scripts/shopify_graphql.py", "license": "MIT License", "lines": 360, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
davila7/claude-code-templates:cli-tool/components/skills/web-development/shopify-development/scripts/shopify_init.py
#!/usr/bin/env python3 """ Shopify Project Initialization Script Interactive script to scaffold Shopify apps, extensions, or themes. Supports environment variable loading from multiple locations. """ import os import sys import json import subprocess from pathlib import Path from typing import Dict, Optional, List from dataclasses import dataclass @dataclass class EnvConfig: """Environment configuration container.""" shopify_api_key: Optional[str] = None shopify_api_secret: Optional[str] = None shop_domain: Optional[str] = None scopes: Optional[str] = None class EnvLoader: """Load environment variables from multiple sources in priority order.""" @staticmethod def load_env_file(filepath: Path) -> Dict[str, str]: """ Load environment variables from .env file. Args: filepath: Path to .env file Returns: Dictionary of environment variables """ env_vars = {} if not filepath.exists(): return env_vars try: with open(filepath, 'r') as f: for line in f: line = line.strip() if line and not line.startswith('#') and '=' in line: key, value = line.split('=', 1) env_vars[key.strip()] = value.strip().strip('"').strip("'") except Exception as e: print(f"Warning: Failed to load {filepath}: {e}") return env_vars @staticmethod def get_env_paths(skill_dir: Path) -> List[Path]: """ Get list of .env file paths in priority order. Works with any AI tool directory structure: - .agent/skills/ (universal) - .claude/skills/ (Claude Code) - .gemini/skills/ (Gemini CLI) - .cursor/skills/ (Cursor) Priority: process.env > skill/.env > skills/.env > agent_dir/.env Args: skill_dir: Path to skill directory Returns: List of .env file paths """ paths = [] # skill/.env skill_env = skill_dir / '.env' if skill_env.exists(): paths.append(skill_env) # skills/.env skills_env = skill_dir.parent / '.env' if skills_env.exists(): paths.append(skills_env) # agent_dir/.env (e.g., .agent, .claude, .gemini, .cursor) agent_env = skill_dir.parent.parent / '.env' if agent_env.exists(): paths.append(agent_env) return paths @staticmethod def load_config(skill_dir: Path) -> EnvConfig: """ Load configuration from environment variables. Works with any AI tool directory structure. Priority: process.env > skill/.env > skills/.env > agent_dir/.env Args: skill_dir: Path to skill directory Returns: EnvConfig object """ config = EnvConfig() # Load from .env files (reverse priority order) for env_path in reversed(EnvLoader.get_env_paths(skill_dir)): env_vars = EnvLoader.load_env_file(env_path) if 'SHOPIFY_API_KEY' in env_vars: config.shopify_api_key = env_vars['SHOPIFY_API_KEY'] if 'SHOPIFY_API_SECRET' in env_vars: config.shopify_api_secret = env_vars['SHOPIFY_API_SECRET'] if 'SHOP_DOMAIN' in env_vars: config.shop_domain = env_vars['SHOP_DOMAIN'] if 'SCOPES' in env_vars: config.scopes = env_vars['SCOPES'] # Override with process environment (highest priority) if 'SHOPIFY_API_KEY' in os.environ: config.shopify_api_key = os.environ['SHOPIFY_API_KEY'] if 'SHOPIFY_API_SECRET' in os.environ: config.shopify_api_secret = os.environ['SHOPIFY_API_SECRET'] if 'SHOP_DOMAIN' in os.environ: config.shop_domain = os.environ['SHOP_DOMAIN'] if 'SCOPES' in os.environ: config.scopes = os.environ['SCOPES'] return config class ShopifyInitializer: """Initialize Shopify projects.""" def __init__(self, config: EnvConfig): """ Initialize ShopifyInitializer. Args: config: Environment configuration """ self.config = config def prompt(self, message: str, default: Optional[str] = None) -> str: """ Prompt user for input. Args: message: Prompt message default: Default value Returns: User input or default """ if default: message = f"{message} [{default}]" user_input = input(f"{message}: ").strip() return user_input if user_input else (default or '') def select_option(self, message: str, options: List[str]) -> str: """ Prompt user to select from options. Args: message: Prompt message options: List of options Returns: Selected option """ print(f"\n{message}") for i, option in enumerate(options, 1): print(f"{i}. {option}") while True: try: choice = int(input("Select option: ").strip()) if 1 <= choice <= len(options): return options[choice - 1] print(f"Please select 1-{len(options)}") except (ValueError, KeyboardInterrupt): print("Invalid input") def check_cli_installed(self) -> bool: """ Check if Shopify CLI is installed. Returns: True if installed, False otherwise """ try: result = subprocess.run( ['shopify', 'version'], capture_output=True, text=True, timeout=5 ) return result.returncode == 0 except (subprocess.SubprocessError, FileNotFoundError): return False def create_app_config(self, project_dir: Path, app_name: str, scopes: str) -> None: """ Create shopify.app.toml configuration file. Args: project_dir: Project directory app_name: Application name scopes: Access scopes """ config_content = f"""# Shopify App Configuration name = "{app_name}" client_id = "{self.config.shopify_api_key or 'YOUR_API_KEY'}" application_url = "https://your-app.com" embedded = true [build] automatically_update_urls_on_dev = true dev_store_url = "{self.config.shop_domain or 'your-store.myshopify.com'}" [access_scopes] scopes = "{scopes}" [webhooks] api_version = "2026-01" [[webhooks.subscriptions]] topics = ["app/uninstalled"] uri = "/webhooks/app/uninstalled" [webhooks.privacy_compliance] customer_data_request_url = "/webhooks/gdpr/data-request" customer_deletion_url = "/webhooks/gdpr/customer-deletion" shop_deletion_url = "/webhooks/gdpr/shop-deletion" """ config_path = project_dir / 'shopify.app.toml' config_path.write_text(config_content) print(f"✓ Created {config_path}") def create_extension_config(self, project_dir: Path, extension_name: str, extension_type: str) -> None: """ Create shopify.extension.toml configuration file. Args: project_dir: Project directory extension_name: Extension name extension_type: Extension type """ target_map = { 'checkout': 'purchase.checkout.block.render', 'admin_action': 'admin.product-details.action.render', 'admin_block': 'admin.product-details.block.render', 'pos': 'pos.home.tile.render', 'function': 'function', 'customer_account': 'customer-account.order-status.block.render', 'theme_app': 'theme-app-extension' } config_content = f"""name = "{extension_name}" type = "ui_extension" handle = "{extension_name.lower().replace(' ', '-')}" [extension_points] api_version = "2026-01" [[extension_points.targets]] target = "{target_map.get(extension_type, 'purchase.checkout.block.render')}" [capabilities] network_access = true api_access = true """ config_path = project_dir / 'shopify.extension.toml' config_path.write_text(config_content) print(f"✓ Created {config_path}") def create_readme(self, project_dir: Path, project_type: str, project_name: str) -> None: """ Create README.md file. Args: project_dir: Project directory project_type: Project type (app/extension/theme) project_name: Project name """ content = f"""# {project_name} Shopify {project_type.capitalize()} project. ## Setup ```bash # Install dependencies npm install # Start development shopify {project_type} dev ``` ## Deployment ```bash # Deploy to Shopify shopify {project_type} deploy ``` ## Resources - [Shopify Documentation](https://shopify.dev/docs) - [Shopify CLI](https://shopify.dev/docs/api/shopify-cli) """ readme_path = project_dir / 'README.md' readme_path.write_text(content) print(f"✓ Created {readme_path}") def init_app(self) -> None: """Initialize Shopify app project.""" print("\n=== Shopify App Initialization ===\n") app_name = self.prompt("App name", "my-shopify-app") scopes = self.prompt("Access scopes", self.config.scopes or "read_products,write_products") project_dir = Path.cwd() / app_name project_dir.mkdir(exist_ok=True) print(f"\nCreating app in {project_dir}...") self.create_app_config(project_dir, app_name, scopes) self.create_readme(project_dir, "app", app_name) # Create basic package.json package_json = { "name": app_name.lower().replace(' ', '-'), "version": "1.0.0", "scripts": { "dev": "shopify app dev", "deploy": "shopify app deploy" } } (project_dir / 'package.json').write_text(json.dumps(package_json, indent=2)) print(f"✓ Created package.json") print(f"\n✓ App '{app_name}' initialized successfully!") print(f"\nNext steps:") print(f" cd {app_name}") print(f" npm install") print(f" shopify app dev") def init_extension(self) -> None: """Initialize Shopify extension project.""" print("\n=== Shopify Extension Initialization ===\n") extension_types = [ 'checkout', 'admin_action', 'admin_block', 'pos', 'function', 'customer_account', 'theme_app' ] extension_type = self.select_option("Select extension type", extension_types) extension_name = self.prompt("Extension name", "my-extension") project_dir = Path.cwd() / extension_name project_dir.mkdir(exist_ok=True) print(f"\nCreating extension in {project_dir}...") self.create_extension_config(project_dir, extension_name, extension_type) self.create_readme(project_dir, "extension", extension_name) print(f"\n✓ Extension '{extension_name}' initialized successfully!") print(f"\nNext steps:") print(f" cd {extension_name}") print(f" shopify app dev") def init_theme(self) -> None: """Initialize Shopify theme project.""" print("\n=== Shopify Theme Initialization ===\n") theme_name = self.prompt("Theme name", "my-theme") print(f"\nInitializing theme '{theme_name}'...") print("\nRecommended: Use 'shopify theme init' for full theme scaffolding") print(f"\nRun: shopify theme init {theme_name}") def run(self) -> None: """Run interactive initialization.""" print("=" * 60) print("Shopify Project Initializer") print("=" * 60) # Check CLI if not self.check_cli_installed(): print("\n⚠ Shopify CLI not found!") print("Install: npm install -g @shopify/cli@latest") sys.exit(1) # Select project type project_types = ['app', 'extension', 'theme'] project_type = self.select_option("Select project type", project_types) # Initialize based on type if project_type == 'app': self.init_app() elif project_type == 'extension': self.init_extension() elif project_type == 'theme': self.init_theme() def main() -> None: """Main entry point.""" try: # Get skill directory script_dir = Path(__file__).parent skill_dir = script_dir.parent # Load configuration config = EnvLoader.load_config(skill_dir) # Initialize project initializer = ShopifyInitializer(config) initializer.run() except KeyboardInterrupt: print("\n\nAborted.") sys.exit(0) except Exception as e: print(f"\n✗ Error: {e}", file=sys.stderr) sys.exit(1) if __name__ == '__main__': main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/web-development/shopify-development/scripts/shopify_init.py", "license": "MIT License", "lines": 350, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/web-development/shopify-development/scripts/tests/test_shopify_init.py
""" Tests for shopify_init.py Run with: pytest test_shopify_init.py -v --cov=shopify_init --cov-report=term-missing """ import os import sys import json import pytest import subprocess from pathlib import Path from unittest.mock import Mock, patch, mock_open, MagicMock sys.path.insert(0, str(Path(__file__).parent.parent)) from shopify_init import EnvLoader, EnvConfig, ShopifyInitializer class TestEnvLoader: """Test EnvLoader class.""" def test_load_env_file_success(self, tmp_path): """Test loading valid .env file.""" env_file = tmp_path / ".env" env_file.write_text(""" SHOPIFY_API_KEY=test_key SHOPIFY_API_SECRET=test_secret SHOP_DOMAIN=test.myshopify.com # Comment line SCOPES=read_products,write_products """) result = EnvLoader.load_env_file(env_file) assert result['SHOPIFY_API_KEY'] == 'test_key' assert result['SHOPIFY_API_SECRET'] == 'test_secret' assert result['SHOP_DOMAIN'] == 'test.myshopify.com' assert result['SCOPES'] == 'read_products,write_products' def test_load_env_file_with_quotes(self, tmp_path): """Test loading .env file with quoted values.""" env_file = tmp_path / ".env" env_file.write_text(""" SHOPIFY_API_KEY="test_key" SHOPIFY_API_SECRET='test_secret' """) result = EnvLoader.load_env_file(env_file) assert result['SHOPIFY_API_KEY'] == 'test_key' assert result['SHOPIFY_API_SECRET'] == 'test_secret' def test_load_env_file_nonexistent(self, tmp_path): """Test loading non-existent .env file.""" result = EnvLoader.load_env_file(tmp_path / "nonexistent.env") assert result == {} def test_load_env_file_invalid_format(self, tmp_path): """Test loading .env file with invalid lines.""" env_file = tmp_path / ".env" env_file.write_text(""" VALID_KEY=value INVALID_LINE_NO_EQUALS ANOTHER_VALID=test """) result = EnvLoader.load_env_file(env_file) assert result['VALID_KEY'] == 'value' assert result['ANOTHER_VALID'] == 'test' assert 'INVALID_LINE_NO_EQUALS' not in result def test_get_env_paths(self, tmp_path): """Test getting .env file paths from universal directory structure.""" # Create directory structure (works with .agent, .claude, .gemini, .cursor) agent_dir = tmp_path / ".agent" skills_dir = agent_dir / "skills" skill_dir = skills_dir / "shopify" skill_dir.mkdir(parents=True) # Create .env files at each level (skill_dir / ".env").write_text("SKILL=1") (skills_dir / ".env").write_text("SKILLS=1") (agent_dir / ".env").write_text("AGENT=1") paths = EnvLoader.get_env_paths(skill_dir) assert len(paths) == 3 assert skill_dir / ".env" in paths assert skills_dir / ".env" in paths assert agent_dir / ".env" in paths def test_load_config_priority(self, tmp_path, monkeypatch): """Test configuration loading priority across different AI tool directories.""" skill_dir = tmp_path / "skill" skills_dir = tmp_path agent_dir = tmp_path.parent # Could be .agent, .claude, .gemini, .cursor skill_dir.mkdir(parents=True) (skill_dir / ".env").write_text("SHOPIFY_API_KEY=skill_key") (skills_dir / ".env").write_text("SHOPIFY_API_KEY=skills_key\nSHOP_DOMAIN=skills.myshopify.com") monkeypatch.setenv("SHOPIFY_API_KEY", "process_key") config = EnvLoader.load_config(skill_dir) assert config.shopify_api_key == "process_key" # Shop domain from skills/.env assert config.shop_domain == "skills.myshopify.com" def test_load_config_no_files(self, tmp_path): """Test configuration loading with no .env files.""" config = EnvLoader.load_config(tmp_path) assert config.shopify_api_key is None assert config.shopify_api_secret is None assert config.shop_domain is None assert config.scopes is None class TestShopifyInitializer: """Test ShopifyInitializer class.""" @pytest.fixture def config(self): """Create test config.""" return EnvConfig( shopify_api_key="test_key", shopify_api_secret="test_secret", shop_domain="test.myshopify.com", scopes="read_products,write_products" ) @pytest.fixture def initializer(self, config): """Create initializer instance.""" return ShopifyInitializer(config) def test_prompt_with_default(self, initializer): """Test prompt with default value.""" with patch('builtins.input', return_value=''): result = initializer.prompt("Test", "default_value") assert result == "default_value" def test_prompt_with_input(self, initializer): """Test prompt with user input.""" with patch('builtins.input', return_value='user_input'): result = initializer.prompt("Test", "default_value") assert result == "user_input" def test_select_option_valid(self, initializer): """Test select option with valid choice.""" options = ['app', 'extension', 'theme'] with patch('builtins.input', return_value='2'): result = initializer.select_option("Choose", options) assert result == 'extension' def test_select_option_invalid_then_valid(self, initializer): """Test select option with invalid then valid choice.""" options = ['app', 'extension'] with patch('builtins.input', side_effect=['5', 'invalid', '1']): result = initializer.select_option("Choose", options) assert result == 'app' def test_check_cli_installed_success(self, initializer): """Test CLI installed check - success.""" mock_result = Mock() mock_result.returncode = 0 with patch('subprocess.run', return_value=mock_result): assert initializer.check_cli_installed() is True def test_check_cli_installed_failure(self, initializer): """Test CLI installed check - failure.""" with patch('subprocess.run', side_effect=FileNotFoundError): assert initializer.check_cli_installed() is False def test_create_app_config(self, initializer, tmp_path): """Test creating app configuration file.""" initializer.create_app_config(tmp_path, "test-app", "read_products") config_file = tmp_path / "shopify.app.toml" assert config_file.exists() content = config_file.read_text() assert 'name = "test-app"' in content assert 'scopes = "read_products"' in content assert 'client_id = "test_key"' in content def test_create_extension_config(self, initializer, tmp_path): """Test creating extension configuration file.""" initializer.create_extension_config(tmp_path, "test-ext", "checkout") config_file = tmp_path / "shopify.extension.toml" assert config_file.exists() content = config_file.read_text() assert 'name = "test-ext"' in content assert 'purchase.checkout.block.render' in content def test_create_extension_config_admin_action(self, initializer, tmp_path): """Test creating admin action extension config.""" initializer.create_extension_config(tmp_path, "admin-ext", "admin_action") config_file = tmp_path / "shopify.extension.toml" content = config_file.read_text() assert 'admin.product-details.action.render' in content def test_create_readme(self, initializer, tmp_path): """Test creating README file.""" initializer.create_readme(tmp_path, "app", "Test App") readme_file = tmp_path / "README.md" assert readme_file.exists() content = readme_file.read_text() assert '# Test App' in content assert 'shopify app dev' in content @patch('builtins.input') @patch('builtins.print') def test_init_app(self, mock_print, mock_input, initializer, tmp_path, monkeypatch): """Test app initialization.""" monkeypatch.chdir(tmp_path) # Mock user inputs mock_input.side_effect = ['my-app', 'read_products,write_products'] initializer.init_app() # Check directory created app_dir = tmp_path / "my-app" assert app_dir.exists() # Check files created assert (app_dir / "shopify.app.toml").exists() assert (app_dir / "README.md").exists() assert (app_dir / "package.json").exists() # Check package.json content package_json = json.loads((app_dir / "package.json").read_text()) assert package_json['name'] == 'my-app' assert 'dev' in package_json['scripts'] @patch('builtins.input') @patch('builtins.print') def test_init_extension(self, mock_print, mock_input, initializer, tmp_path, monkeypatch): """Test extension initialization.""" monkeypatch.chdir(tmp_path) # Mock user inputs: type selection (1 = checkout), name mock_input.side_effect = ['1', 'my-extension'] initializer.init_extension() # Check directory and files created ext_dir = tmp_path / "my-extension" assert ext_dir.exists() assert (ext_dir / "shopify.extension.toml").exists() assert (ext_dir / "README.md").exists() @patch('builtins.input') @patch('builtins.print') def test_init_theme(self, mock_print, mock_input, initializer): """Test theme initialization.""" mock_input.return_value = 'my-theme' initializer.init_theme() assert mock_print.called @patch('builtins.print') def test_run_no_cli(self, mock_print, initializer): """Test run when CLI not installed.""" with patch.object(initializer, 'check_cli_installed', return_value=False): with pytest.raises(SystemExit) as exc_info: initializer.run() assert exc_info.value.code == 1 @patch.object(ShopifyInitializer, 'check_cli_installed', return_value=True) @patch.object(ShopifyInitializer, 'init_app') @patch('builtins.input') @patch('builtins.print') def test_run_app_selected(self, mock_print, mock_input, mock_init_app, mock_cli_check, initializer): """Test run with app selection.""" mock_input.return_value = '1' # Select app initializer.run() mock_init_app.assert_called_once() @patch.object(ShopifyInitializer, 'check_cli_installed', return_value=True) @patch.object(ShopifyInitializer, 'init_extension') @patch('builtins.input') @patch('builtins.print') def test_run_extension_selected(self, mock_print, mock_input, mock_init_ext, mock_cli_check, initializer): """Test run with extension selection.""" mock_input.return_value = '2' # Select extension initializer.run() mock_init_ext.assert_called_once() class TestMain: """Test main function.""" @patch('shopify_init.ShopifyInitializer') @patch('shopify_init.EnvLoader') def test_main_success(self, mock_loader, mock_initializer): """Test main function success path.""" from shopify_init import main mock_config = Mock() mock_loader.load_config.return_value = mock_config mock_init_instance = Mock() mock_initializer.return_value = mock_init_instance with patch('builtins.print'): main() mock_init_instance.run.assert_called_once() @patch('shopify_init.ShopifyInitializer') @patch('sys.exit') def test_main_keyboard_interrupt(self, mock_exit, mock_initializer): """Test main function with keyboard interrupt.""" from shopify_init import main mock_initializer.return_value.run.side_effect = KeyboardInterrupt with patch('builtins.print'): main() mock_exit.assert_called_with(0) @patch('shopify_init.ShopifyInitializer') @patch('sys.exit') def test_main_exception(self, mock_exit, mock_initializer): """Test main function with exception.""" from shopify_init import main mock_initializer.return_value.run.side_effect = Exception("Test error") with patch('builtins.print'): main() mock_exit.assert_called_with(1) class TestEnvConfig: """Test EnvConfig dataclass.""" def test_env_config_defaults(self): """Test EnvConfig default values.""" config = EnvConfig() assert config.shopify_api_key is None assert config.shopify_api_secret is None assert config.shop_domain is None assert config.scopes is None def test_env_config_with_values(self): """Test EnvConfig with values.""" config = EnvConfig( shopify_api_key="key", shopify_api_secret="secret", shop_domain="test.myshopify.com", scopes="read_products" ) assert config.shopify_api_key == "key" assert config.shopify_api_secret == "secret" assert config.shop_domain == "test.myshopify.com" assert config.scopes == "read_products"
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/web-development/shopify-development/scripts/tests/test_shopify_init.py", "license": "MIT License", "lines": 287, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
davila7/claude-code-templates:cli-tool/components/skills/creative-design/meme-factory/scripts/meme_generator.py
#!/usr/bin/env python3 """Meme Generator Helper. A Python interface for the memegen.link API to generate memes programmatically. Usage: python meme_generator.py generate buzz "memes" "memes everywhere" python meme_generator.py list-templates python meme_generator.py suggest "deployment success" Or import as a module: from meme_generator import MemeGenerator meme = MemeGenerator() url = meme.generate("buzz", "hello", "world") """ import argparse import urllib.parse class MemeGenerator: """Generate memes using the memegen.link API.""" BASE_URL = "https://api.memegen.link" # Popular templates with their use cases TEMPLATES = { "buzz": "X, X everywhere (Buzz Lightyear)", "drake": "Comparing two options (Drake Hotline Bling)", "success": "Celebrating wins (Success Kid)", "fine": "Things going wrong (This is Fine Dog)", "fry": "Uncertainty (Futurama Fry)", "changemind": "Controversial opinions (Change My Mind)", "distracted": "Priorities/distractions (Distracted Boyfriend)", "yodawg": "Yo dawg, I heard you like X (Xzibit)", "interesting": "I don't always X (Most Interesting Man)", "mordor": "One does not simply X (Boromir)", "yuno": "Y U NO (Y U NO Guy)", "doge": "Much X, very Y (Doge)", "wonka": "Condescending statements (Wonka)", "ancient": "Aliens/conspiracy (Ancient Aliens Guy)", "skeptical": "Skeptical reactions (Third World Skeptical Kid)", "awesome": "Good/bad situations (Awesome/Awkward Penguin)", "rollsafe": "Can't X if Y (Roll Safe)", "surprised": "Surprised reactions (Surprised Pikachu)", "thinking": "Thinking/pondering (Thinking Guy)", "boardroom": "Bad suggestions (Boardroom Meeting)", } # Context-based template suggestions CONTEXT_MAP = { "success": ["success", "awesome"], "failure": ["fine", "yuno"], "comparison": ["drake", "awesome", "distracted"], "uncertainty": ["fry", "suspicious"], "statement": ["buzz", "yodawg", "interesting", "mordor", "changemind"], "reaction": ["success", "fine", "surprised", "thinking"], "humor": ["doge", "wonka", "ancient", "rollsafe"], "deployment": ["success", "fine", "interesting"], "testing": ["success", "fry", "interesting"], "debugging": ["fine", "fry", "buzz"], "documentation": ["yodawg", "buzz", "wonka"], } def __init__(self) -> None: """Initialize the meme generator.""" def _format_text(self, text: str) -> str: """Format text for URL inclusion following memegen rules.""" replacements = { " ": "_", "-": "--", "_": "__", "?": "~q", "%": "~p", "#": "~h", "/": "~s", '"': "''", } escaped = "".join(replacements.get(char, char) for char in text) # Percent-encode any remaining reserved characters while preserving # memegen's escape sequences and allowed characters. return urllib.parse.quote(escaped, safe="-_~") def generate( # noqa: PLR0913 self, template: str, top_text: str = "", bottom_text: str = "", extension: str = "png", width: int | None = None, height: int | None = None, layout: str | None = None, style: str | None = None, font: str | None = None, ) -> str: """Generate a meme URL. Args: template: Template name (e.g., 'buzz', 'drake') top_text: Text for the top of the meme bottom_text: Text for the bottom of the meme extension: Image format ('png', 'jpg', 'webp', 'gif') width: Optional width in pixels height: Optional height in pixels layout: Optional layout ('top', 'bottom', 'default') style: Optional style or custom background URL font: Optional font name Returns: URL to the generated meme """ # Format text top = self._format_text(top_text) if top_text else "_" bottom = self._format_text(bottom_text) if bottom_text else "_" # Build base URL url = f"{self.BASE_URL}/images/{template}/{top}/{bottom}.{extension}" # Add query parameters params = {} if width: params["width"] = str(width) if height: params["height"] = str(height) if layout: params["layout"] = layout if style: params["style"] = style if font: params["font"] = font if params: query_string = urllib.parse.urlencode(params) url = f"{url}?{query_string}" return url def suggest_template_for_context(self, context: str) -> str: """Suggest a template based on context. Args: context: Description of the situation (e.g., 'deployment success') Returns: Suggested template name """ context_lower = context.lower() # Check for keyword matches for key, templates in self.CONTEXT_MAP.items(): if key in context_lower: return templates[0] # Default fallback return "buzz" def list_templates(self) -> dict[str, str]: """List all available templates with descriptions. Returns: Dictionary of template names and descriptions """ return self.TEMPLATES def get_markdown_image(self, url: str, alt_text: str = "Meme", width: int | None = None) -> str: """Generate markdown for embedding the meme image. Args: url: The meme URL alt_text: Alternative text for the image width: Optional width specification Returns: Markdown image syntax """ if width: return f'<img src="{url}" alt="{alt_text}" width="{width}"/>' return f"![{alt_text}]({url})" def main() -> None: """CLI interface for the meme generator.""" parser = argparse.ArgumentParser(description="Generate memes using memegen.link") subparsers = parser.add_subparsers(dest="command", help="Command to run") # Generate command generate_parser = subparsers.add_parser("generate", help="Generate a meme") generate_parser.add_argument("template", help="Template name (e.g., buzz, drake)") generate_parser.add_argument("top", help="Top text") generate_parser.add_argument("bottom", nargs="?", default="", help="Bottom text") generate_parser.add_argument( "--extension", "-e", default="png", help="Image format (png, jpg, webp, gif)" ) generate_parser.add_argument("--width", "-w", type=int, help="Image width") generate_parser.add_argument("--height", type=int, help="Image height") generate_parser.add_argument("--layout", "-l", help="Layout (top, bottom, default)") generate_parser.add_argument("--markdown", "-m", action="store_true", help="Output as markdown") # List templates command subparsers.add_parser("list-templates", help="List all available templates") # Suggest template command suggest_parser = subparsers.add_parser("suggest", help="Suggest template for context") suggest_parser.add_argument("context", help="Context description") args = parser.parse_args() generator = MemeGenerator() if args.command == "generate": generator.generate( template=args.template, top_text=args.top, bottom_text=args.bottom, extension=args.extension, width=args.width, height=getattr(args, "height", None), layout=args.layout, ) if args.markdown: pass else: pass elif args.command == "list-templates": templates = generator.list_templates() for _name, _description in sorted(templates.items()): pass elif args.command == "suggest": generator.suggest_template_for_context(args.context) else: parser.print_help() if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/creative-design/meme-factory/scripts/meme_generator.py", "license": "MIT License", "lines": 198, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/development/plugin-forge/scripts/bump_version.py
#!/usr/bin/env python3 """ Bump plugin version in both plugin.json and marketplace.json. """ import argparse import json import sys from pathlib import Path from typing import Literal VersionPart = Literal["major", "minor", "patch"] def parse_version(version: str) -> tuple[int, int, int]: """Parse semantic version string into tuple.""" try: parts = version.split(".") return int(parts[0]), int(parts[1]), int(parts[2]) except (ValueError, IndexError): print(f"❌ Invalid version format: {version}") sys.exit(1) def bump_version(version: str, part: VersionPart) -> str: """Bump semantic version.""" major, minor, patch = parse_version(version) if part == "major": return f"{major + 1}.0.0" elif part == "minor": return f"{major}.{minor + 1}.0" elif part == "patch": return f"{major}.{minor}.{patch + 1}" else: print(f"❌ Invalid version part: {part}") sys.exit(1) def update_plugin_version(plugin_name: str, marketplace_root: Path, part: VersionPart) -> None: """Update version in both plugin.json and marketplace.json.""" # Update plugin.json plugin_json_path = marketplace_root / "plugins" / plugin_name / ".claude-plugin" / "plugin.json" if not plugin_json_path.exists(): print(f"❌ Plugin manifest not found: {plugin_json_path}") sys.exit(1) with open(plugin_json_path, "r") as f: plugin_data = json.load(f) old_version = plugin_data.get("version", "0.0.0") new_version = bump_version(old_version, part) plugin_data["version"] = new_version with open(plugin_json_path, "w") as f: json.dump(plugin_data, f, indent=2) print(f"✅ Updated plugin.json: {old_version} → {new_version}") # Update marketplace.json marketplace_json_path = marketplace_root / ".claude-plugin" / "marketplace.json" if not marketplace_json_path.exists(): print(f"❌ Marketplace manifest not found: {marketplace_json_path}") sys.exit(1) with open(marketplace_json_path, "r") as f: marketplace_data = json.load(f) plugin_found = False for plugin in marketplace_data.get("plugins", []): if plugin.get("name") == plugin_name: plugin["version"] = new_version plugin_found = True break if not plugin_found: print(f"❌ Plugin '{plugin_name}' not found in marketplace manifest") sys.exit(1) with open(marketplace_json_path, "w") as f: json.dump(marketplace_data, f, indent=2) print(f"✅ Updated marketplace.json: {old_version} → {new_version}") print(f"\n🎉 Version bumped successfully: {old_version} → {new_version}") def main(): parser = argparse.ArgumentParser(description="Bump plugin version") parser.add_argument("plugin_name", help="Plugin name") parser.add_argument("part", choices=["major", "minor", "patch"], help="Version part to bump") parser.add_argument("--marketplace-root", default=".", help="Path to marketplace root directory") args = parser.parse_args() marketplace_root = Path(args.marketplace_root).resolve() update_plugin_version( plugin_name=args.plugin_name, marketplace_root=marketplace_root, part=args.part ) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/development/plugin-forge/scripts/bump_version.py", "license": "MIT License", "lines": 79, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/development/plugin-forge/scripts/create_plugin.py
#!/usr/bin/env python3 """ Create a new Claude Code plugin with proper directory structure and manifests. """ import argparse import json import os import sys from pathlib import Path def create_plugin_structure(plugin_name: str, marketplace_root: Path, author_name: str, author_email: str, description: str, keywords: list[str], category: str = "productivity") -> None: """Create complete plugin directory structure with manifests.""" # Create plugin directory plugin_dir = marketplace_root / "plugins" / plugin_name if plugin_dir.exists(): print(f"❌ Plugin directory already exists: {plugin_dir}") sys.exit(1) # Create directory structure plugin_config_dir = plugin_dir / ".claude-plugin" commands_dir = plugin_dir / "commands" skills_dir = plugin_dir / "skills" plugin_config_dir.mkdir(parents=True, exist_ok=True) commands_dir.mkdir(parents=True, exist_ok=True) skills_dir.mkdir(parents=True, exist_ok=True) # Create plugin.json plugin_manifest = { "name": plugin_name, "version": "0.1.0", "description": description, "author": { "name": author_name, "email": author_email }, "keywords": keywords } plugin_json_path = plugin_config_dir / "plugin.json" with open(plugin_json_path, "w") as f: json.dump(plugin_manifest, f, indent=2) print(f"✅ Created plugin manifest: {plugin_json_path}") # Create README.md readme_content = f"""# {plugin_name} {description} ## Installation ```bash /plugin marketplace add <marketplace-source> /plugin install {plugin_name}@<marketplace-name> ``` ## Features - TODO: List features here ## Usage TODO: Add usage examples ## Development See [workflows.md](../../CLAUDE.md) for development guidelines. """ readme_path = plugin_dir / "README.md" with open(readme_path, "w") as f: f.write(readme_content) print(f"✅ Created README: {readme_path}") # Update marketplace.json marketplace_json_path = marketplace_root / ".claude-plugin" / "marketplace.json" if not marketplace_json_path.exists(): print(f"❌ Marketplace manifest not found: {marketplace_json_path}") sys.exit(1) with open(marketplace_json_path, "r") as f: marketplace_data = json.load(f) # Check if plugin already exists in marketplace for plugin in marketplace_data.get("plugins", []): if plugin.get("name") == plugin_name: print(f"❌ Plugin '{plugin_name}' already exists in marketplace manifest") sys.exit(1) # Add plugin entry plugin_entry = { "name": plugin_name, "source": f"./plugins/{plugin_name}", "description": description, "version": "0.1.0", "keywords": keywords, "category": category } if "plugins" not in marketplace_data: marketplace_data["plugins"] = [] marketplace_data["plugins"].append(plugin_entry) with open(marketplace_json_path, "w") as f: json.dump(marketplace_data, f, indent=2) print(f"✅ Updated marketplace manifest: {marketplace_json_path}") print(f"\n🎉 Plugin '{plugin_name}' created successfully!") print(f"\nNext steps:") print(f"1. Add commands to: {commands_dir}") print(f"2. Add skills to: {skills_dir}") print(f"3. Test with: /plugin install {plugin_name}@marketplace-name") def main(): parser = argparse.ArgumentParser(description="Create a new Claude Code plugin") parser.add_argument("plugin_name", help="Plugin name (kebab-case)") parser.add_argument("--marketplace-root", default=".", help="Path to marketplace root directory") parser.add_argument("--author-name", required=True, help="Plugin author name") parser.add_argument("--author-email", required=True, help="Plugin author email") parser.add_argument("--description", required=True, help="Plugin description") parser.add_argument("--keywords", required=True, help="Comma-separated keywords") parser.add_argument("--category", default="productivity", help="Plugin category (default: productivity)") args = parser.parse_args() marketplace_root = Path(args.marketplace_root).resolve() keywords = [k.strip() for k in args.keywords.split(",")] create_plugin_structure( plugin_name=args.plugin_name, marketplace_root=marketplace_root, author_name=args.author_name, author_email=args.author_email, description=args.description, keywords=keywords, category=args.category ) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/development/plugin-forge/scripts/create_plugin.py", "license": "MIT License", "lines": 112, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/enterprise-communication/daily-meeting-update/scripts/claude_digest.py
#!/usr/bin/env python3 """ Get Claude Code conversation digest for daily standup integration. Usage: claude_digest.py [--date DATE] [--project PATH] [--format json|text] Examples: claude_digest.py # Yesterday's digest (default) claude_digest.py --date today # Today's digest claude_digest.py --date 2026-01-20 # Specific date claude_digest.py --format json # JSON output for parsing Output (JSON format): { "date": "2026-01-21", "session_count": 5, "sessions": [ { "id": "abc123", "title": "Fix authentication bug", "project": "/home/user/my-app", "branch": "main", "files": ["auth.ts", "login.vue"], "commands_count": 3 } ] } """ import argparse import json import re import sys from dataclasses import dataclass from datetime import datetime, timedelta from pathlib import Path from typing import Optional @dataclass class Session: """Represents a Claude Code session.""" id: str title: str project: str branch: Optional[str] files: list commands_count: int timestamp: str def get_claude_projects_dir() -> Path: """Get the Claude projects directory.""" return Path.home() / '.claude' / 'projects' def decode_project_path(encoded: str) -> str: """Decode encoded project path from directory name.""" if encoded.startswith('-'): return '/' + encoded[1:].replace('-', '/') return encoded.replace('-', '/') def parse_timestamp(timestamp: str) -> Optional[datetime]: """Parse ISO timestamp string to datetime.""" if not timestamp: return None try: if 'T' in timestamp: timestamp = timestamp.split('+')[0].split('Z')[0] if '.' in timestamp: return datetime.strptime(timestamp[:26], '%Y-%m-%dT%H:%M:%S.%f') return datetime.strptime(timestamp[:19], '%Y-%m-%dT%H:%M:%S') return datetime.strptime(timestamp[:10], '%Y-%m-%d') except (ValueError, IndexError): return None def extract_text_content(content) -> str: """Extract plain text from message content.""" if isinstance(content, str): return content if isinstance(content, list): texts = [] for block in content: if isinstance(block, dict): if block.get('type') == 'text': texts.append(block.get('text', '')) return '\n'.join(texts) return '' def extract_tool_uses(content) -> list: """Extract tool_use blocks from message content.""" if not isinstance(content, list): return [] return [ {'name': block.get('name'), 'input': block.get('input', {})} for block in content if isinstance(block, dict) and block.get('type') == 'tool_use' ] def parse_session_file(file_path: Path) -> Optional[dict]: """Parse a JSONL session file.""" messages = [] summary = None session_id = file_path.stem project_path = decode_project_path(file_path.parent.name) git_branch = None first_timestamp = None first_user_message = None try: with open(file_path, 'r', encoding='utf-8') as f: for line in f: if not line.strip(): continue try: entry = json.loads(line) except json.JSONDecodeError: continue entry_type = entry.get('type') if entry_type == 'summary': summary = entry.get('summary') continue if entry_type not in ('user', 'assistant'): continue if git_branch is None: git_branch = entry.get('gitBranch') timestamp = entry.get('timestamp', '') if first_timestamp is None: first_timestamp = timestamp msg_data = entry.get('message', {}) content = msg_data.get('content', '') text_content = extract_text_content(content) tool_uses = extract_tool_uses(content) if entry_type == 'user' and first_user_message is None and text_content: # Skip tool results if not text_content.startswith('[') and not text_content.startswith('{'): first_user_message = text_content messages.append({ 'role': entry_type, 'content': text_content, 'tool_uses': tool_uses }) except Exception as e: print(f"Error parsing {file_path.name}: {e}", file=sys.stderr) return None if not messages: return None return { 'session_id': session_id, 'summary': summary, 'messages': messages, 'project_path': project_path, 'git_branch': git_branch, 'timestamp': first_timestamp or '', 'first_user_message': first_user_message } def extract_title(session_data: dict) -> str: """Extract a title from session data.""" if session_data.get('summary'): return session_data['summary'][:80] if session_data.get('first_user_message'): msg = session_data['first_user_message'].strip() # Clean up and truncate msg = re.sub(r'\s+', ' ', msg) if len(msg) > 80: return msg[:77] + '...' return msg return 'Untitled session' def extract_files(messages: list) -> list: """Extract files touched during session.""" files = set() for msg in messages: for tool in msg.get('tool_uses', []): name = tool.get('name', '') inp = tool.get('input', {}) if name in ('Read', 'Write', 'Edit'): path = inp.get('file_path', '') if path: files.add(Path(path).name) return sorted(files)[:10] def count_commands(messages: list) -> int: """Count bash commands executed.""" count = 0 for msg in messages: for tool in msg.get('tool_uses', []): if tool.get('name') == 'Bash': count += 1 return count def get_sessions_for_date( target_date: datetime, project_path: Optional[str] = None ) -> list: """Get all sessions for a specific date.""" sessions = [] projects_dir = get_claude_projects_dir() if not projects_dir.exists(): return [] start = target_date.replace(hour=0, minute=0, second=0, microsecond=0) end = start + timedelta(days=1) # Get project directories if project_path: project_path = str(Path(project_path).expanduser().resolve()) encoded = '-' + project_path[1:].replace('/', '-') project_dirs = [projects_dir / encoded] if (projects_dir / encoded).exists() else [] else: project_dirs = [d for d in projects_dir.iterdir() if d.is_dir()] for project_dir in project_dirs: for jsonl_file in project_dir.glob('*.jsonl'): if jsonl_file.name.startswith('agent-'): continue session_data = parse_session_file(jsonl_file) if session_data is None: continue # Check date range session_date = parse_timestamp(session_data['timestamp']) if session_date is None: continue if not (start <= session_date < end): continue session = Session( id=session_data['session_id'][:8], title=extract_title(session_data), project=session_data['project_path'], branch=session_data['git_branch'], files=extract_files(session_data['messages']), commands_count=count_commands(session_data['messages']), timestamp=session_data['timestamp'] ) sessions.append(session) # Sort by timestamp sessions.sort(key=lambda s: s.timestamp) return sessions def parse_date_arg(date_arg: str) -> datetime: """Parse date argument.""" today = datetime.now() if date_arg == 'today': return today elif date_arg == 'yesterday': return today - timedelta(days=1) else: try: return datetime.strptime(date_arg, '%Y-%m-%d') except ValueError: print(f"Invalid date: {date_arg}. Use 'today', 'yesterday', or YYYY-MM-DD", file=sys.stderr) sys.exit(1) def format_text(sessions: list, target_date: datetime) -> str: """Format sessions as text.""" date_str = target_date.strftime('%B %d, %Y') if not sessions: return f"No sessions found for {date_str}" lines = [f"## {date_str} - {len(sessions)} session{'s' if len(sessions) != 1 else ''}", ""] for i, s in enumerate(sessions, 1): lines.append(f"### {i}. {s.title}") lines.append(f" Session: `{s.id}`") if s.branch: lines.append(f" Branch: `{s.branch}`") if s.files: lines.append(f" Files: {', '.join(s.files[:5])}") if s.commands_count: lines.append(f" Commands: {s.commands_count} executed") lines.append("") return '\n'.join(lines) def format_json(sessions: list, target_date: datetime) -> dict: """Format sessions as JSON.""" return { 'date': target_date.strftime('%Y-%m-%d'), 'session_count': len(sessions), 'sessions': [ { 'id': s.id, 'title': s.title, 'project': s.project, 'branch': s.branch, 'files': s.files, 'commands_count': s.commands_count } for s in sessions ] } def main(): parser = argparse.ArgumentParser( description='Get Claude Code conversation digest for daily standup' ) parser.add_argument('--date', '-d', default='yesterday', help='Date to get digest for (today, yesterday, or YYYY-MM-DD). Default: yesterday') parser.add_argument('--project', '-p', help='Filter to specific project path') parser.add_argument('--format', '-f', choices=['text', 'json'], default='text', help='Output format (default: text)') args = parser.parse_args() target_date = parse_date_arg(args.date) sessions = get_sessions_for_date(target_date, args.project) if args.format == 'json': print(json.dumps(format_json(sessions, target_date), indent=2)) else: print(format_text(sessions, target_date)) if __name__ == '__main__': main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/enterprise-communication/daily-meeting-update/scripts/claude_digest.py", "license": "MIT License", "lines": 283, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/enterprise-communication/session-handoff/evals/setup_test_env.py
#!/usr/bin/env python3 """ Set up a test environment for evaluating the session-handoff skill. Creates a mock project with: - Git repository with commit history - Sample source files - Sample handoffs (fresh and stale) Usage: python setup_test_env.py [--path /tmp/handoff-test] python setup_test_env.py --clean # Remove test environment """ import argparse import os import shutil import subprocess from datetime import datetime, timedelta from pathlib import Path DEFAULT_TEST_PATH = "/tmp/handoff-eval-project" def run_cmd(cmd: list[str], cwd: str = None) -> bool: """Run a command and return success status.""" try: subprocess.run(cmd, cwd=cwd, capture_output=True, check=True) return True except subprocess.CalledProcessError: return False def create_test_project(base_path: str): """Create a mock project structure.""" path = Path(base_path) # Clean if exists if path.exists(): shutil.rmtree(path) # Create directories (path / "src").mkdir(parents=True) (path / "tests").mkdir() (path / "config").mkdir() # Create sample files (path / "README.md").write_text("""# Test Project A sample project for testing the session-handoff skill. ## Features - User authentication - API endpoints - Database integration """) (path / "src" / "index.js").write_text("""// Main entry point const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World'); }); module.exports = app; """) (path / "src" / "auth.js").write_text("""// Authentication module const jwt = require('jsonwebtoken'); function validateToken(token) { // TODO: Implement token validation return true; } function generateToken(user) { return jwt.sign({ id: user.id }, process.env.JWT_SECRET); } module.exports = { validateToken, generateToken }; """) (path / "src" / "database.js").write_text("""// Database connection const mongoose = require('mongoose'); async function connect() { await mongoose.connect(process.env.DATABASE_URL); } module.exports = { connect }; """) (path / "tests" / "auth.test.js").write_text("""// Auth tests describe('Authentication', () => { test('validates tokens', () => { expect(true).toBe(true); }); }); """) (path / "config" / "default.json").write_text("""{ "port": 3000, "database": { "host": "localhost", "name": "testdb" } } """) (path / "package.json").write_text("""{ "name": "test-project", "version": "1.0.0", "main": "src/index.js", "scripts": { "start": "node src/index.js", "test": "jest" } } """) print(f"Created project structure at {path}") return path def init_git_repo(path: Path): """Initialize git repo with commit history.""" # Initialize run_cmd(["git", "init"], cwd=str(path)) run_cmd(["git", "config", "user.email", "test@example.com"], cwd=str(path)) run_cmd(["git", "config", "user.name", "Test User"], cwd=str(path)) # Initial commit run_cmd(["git", "add", "."], cwd=str(path)) run_cmd(["git", "commit", "-m", "Initial commit: project setup"], cwd=str(path)) # Add more commits to simulate history commits = [ ("src/auth.js", "// Added validation logic\n", "Add token validation"), ("src/database.js", "// Added connection pooling\n", "Implement connection pooling"), ("tests/auth.test.js", "// More tests\n", "Add authentication tests"), ("src/index.js", "// Added middleware\n", "Add auth middleware"), ("README.md", "\n## API Docs\n", "Update documentation"), ] for file, content, message in commits: file_path = path / file with open(file_path, "a") as f: f.write(content) run_cmd(["git", "add", file], cwd=str(path)) run_cmd(["git", "commit", "-m", message], cwd=str(path)) print(f"Initialized git repo with {len(commits) + 1} commits") def create_sample_handoffs(path: Path): """Create sample handoff documents for testing.""" handoffs_dir = path / ".claude" / "handoffs" handoffs_dir.mkdir(parents=True) # Fresh handoff (today) now = datetime.now() fresh_name = now.strftime("%Y-%m-%d-%H%M%S") + "-auth-implementation.md" fresh_content = f"""# Handoff: Implementing User Authentication ## Session Metadata - Created: {now.strftime("%Y-%m-%d %H:%M:%S")} - Project: {path} - Branch: main - Session duration: 2 hours ## Handoff Chain - **Continues from**: None (fresh start) - **Supersedes**: None ## Current State Summary Working on implementing JWT-based authentication for the API. Successfully added token generation and basic validation. The middleware integration is partially complete. ## Codebase Understanding ### Architecture Overview Express.js application with modular structure. Auth logic separated into src/auth.js, database connection in src/database.js. ### Critical Files | File | Purpose | Relevance | |------|---------|-----------| | src/auth.js | Authentication logic | Main file being modified | | src/index.js | App entry point | Needs middleware integration | ### Key Patterns Discovered - Using environment variables for secrets (JWT_SECRET, DATABASE_URL) - Jest for testing ## Work Completed ### Tasks Finished - [x] Set up JWT token generation - [x] Create basic validation function - [ ] Integrate middleware (in progress) ### Files Modified | File | Changes | Rationale | |------|---------|-----------| | src/auth.js | Added validateToken, generateToken | Core auth functionality | ### Decisions Made | Decision | Options Considered | Rationale | |----------|-------------------|-----------| | Use JWT over sessions | JWT, Sessions, OAuth | Stateless, scales better for API | ## Pending Work ### Immediate Next Steps 1. Complete middleware integration in src/index.js 2. Add refresh token logic 3. Write comprehensive tests ### Blockers/Open Questions - [ ] Need to decide on token expiry time (1h vs 24h) ### Deferred Items - OAuth integration (future sprint) ## Context for Resuming Agent ### Important Context The validateToken function in src/auth.js currently returns true always - this is a placeholder that needs real implementation. The JWT_SECRET env var must be set. ### Assumptions Made - Using HS256 algorithm for JWT - Tokens should be passed in Authorization header ### Potential Gotchas - Don't forget to set JWT_SECRET environment variable - Database connection must be established before auth checks ## Environment State ### Tools/Services Used - Node.js with Express - JWT library (jsonwebtoken) ### Active Processes - None currently running ### Environment Variables - JWT_SECRET - DATABASE_URL ## Related Resources - JWT documentation: https://jwt.io - Express middleware guide """ (handoffs_dir / fresh_name).write_text(fresh_content) # Stale handoff (2 weeks ago) old_date = now - timedelta(days=14) stale_name = old_date.strftime("%Y-%m-%d-%H%M%S") + "-database-setup.md" stale_content = f"""# Handoff: Database Setup ## Session Metadata - Created: {old_date.strftime("%Y-%m-%d %H:%M:%S")} - Project: {path} - Branch: main - Session duration: 1 hour ## Handoff Chain - **Continues from**: None (fresh start) - **Supersedes**: None ## Current State Summary Set up initial database connection with MongoDB. Basic schema defined but not fully implemented. ## Codebase Understanding ### Architecture Overview MongoDB database with Mongoose ODM. ### Critical Files | File | Purpose | Relevance | |------|---------|-----------| | src/database.js | DB connection | Main database file | | src/old-file.js | Legacy code | Was being refactored | ## Pending Work ### Immediate Next Steps 1. Define user schema 2. Add connection pooling 3. Implement error handling ## Context for Resuming Agent ### Important Context Using MongoDB Atlas for hosting. Connection string in DATABASE_URL. ### Assumptions Made - MongoDB version 5.x - Mongoose 7.x ## Environment State ### Environment Variables - DATABASE_URL """ (handoffs_dir / stale_name).write_text(stale_content) # Incomplete handoff (with TODOs) incomplete_name = now.strftime("%Y-%m-%d-%H%M%S") + "-incomplete-test.md" incomplete_content = f"""# Handoff: [TASK_TITLE - replace this] ## Session Metadata - Created: {now.strftime("%Y-%m-%d %H:%M:%S")} - Project: {path} - Branch: main - Session duration: [estimate how long you worked] ## Current State Summary [TODO: Write one paragraph describing what was being worked on] ## Codebase Understanding ### Architecture Overview [TODO: Document key architectural insights] ## Pending Work ### Immediate Next Steps 1. [TODO: Most critical next action] 2. [TODO: Second priority] ## Context for Resuming Agent ### Important Context [TODO: This is the MOST IMPORTANT section] """ (handoffs_dir / incomplete_name).write_text(incomplete_content) print(f"Created 3 sample handoffs:") print(f" - {fresh_name} (fresh)") print(f" - {stale_name} (stale, 14 days old)") print(f" - {incomplete_name} (incomplete, has TODOs)") def clean_test_env(path: str): """Remove test environment.""" if Path(path).exists(): shutil.rmtree(path) print(f"Cleaned up test environment at {path}") else: print(f"No test environment found at {path}") def main(): parser = argparse.ArgumentParser( description="Set up test environment for session-handoff skill" ) parser.add_argument( "--path", default=DEFAULT_TEST_PATH, help=f"Path for test project (default: {DEFAULT_TEST_PATH})" ) parser.add_argument( "--clean", action="store_true", help="Remove test environment instead of creating" ) args = parser.parse_args() if args.clean: clean_test_env(args.path) else: path = create_test_project(args.path) init_git_repo(path) create_sample_handoffs(path) print(f"\nTest environment ready at: {args.path}") print(f"\nTo test, run:") print(f" cd {args.path}") print(f" # Then use Claude Code with the session-handoff skill") if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/enterprise-communication/session-handoff/evals/setup_test_env.py", "license": "MIT License", "lines": 292, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
davila7/claude-code-templates:cli-tool/components/skills/enterprise-communication/session-handoff/scripts/check_staleness.py
#!/usr/bin/env python3 """ Check staleness of a handoff document compared to current project state. Analyzes: - Time since handoff was created - Git commits since handoff - Files that changed since handoff - Branch divergence - Modified files status Usage: python check_staleness.py <handoff-file> python check_staleness.py .claude/handoffs/2024-01-15-143022-auth.md """ import os import re import subprocess import sys from datetime import datetime from pathlib import Path def run_cmd(cmd: list[str], cwd: str = None) -> tuple[bool, str]: """Run a command and return (success, output).""" try: result = subprocess.run( cmd, capture_output=True, text=True, cwd=cwd, timeout=10 ) return result.returncode == 0, result.stdout.strip() except (subprocess.TimeoutExpired, FileNotFoundError): return False, "" def parse_handoff_metadata(filepath: str) -> dict: """Extract metadata from a handoff file.""" content = Path(filepath).read_text() metadata = { "created": None, "branch": None, "project_path": None, "modified_files": [], } # Parse Created timestamp match = re.search(r'Created:\s*(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})', content) if match: try: metadata["created"] = datetime.strptime(match.group(1), "%Y-%m-%d %H:%M:%S") except ValueError: pass # Parse Branch match = re.search(r'Branch:\s*(\S+)', content) if match: branch = match.group(1) if branch and not branch.startswith('['): metadata["branch"] = branch # Parse Project path match = re.search(r'Project:\s*(.+?)(?:\n|$)', content) if match: metadata["project_path"] = match.group(1).strip() # Parse modified files from table table_matches = re.findall(r'\|\s*([a-zA-Z0-9_\-./]+\.[a-zA-Z]+)\s*\|', content) for f in table_matches: if '/' in f and not f.startswith('['): metadata["modified_files"].append(f) return metadata def get_commits_since(timestamp: datetime, project_path: str) -> list[str]: """Get list of commits since a given timestamp.""" if not timestamp: return [] iso_time = timestamp.strftime("%Y-%m-%dT%H:%M:%S") success, output = run_cmd( ["git", "log", f"--since={iso_time}", "--oneline", "--no-decorate"], cwd=project_path ) if success and output: return output.split("\n") return [] def get_current_branch(project_path: str) -> str | None: """Get current git branch.""" success, branch = run_cmd( ["git", "branch", "--show-current"], cwd=project_path ) return branch if success else None def get_changed_files_since(timestamp: datetime, project_path: str) -> list[str]: """Get files that changed since timestamp.""" if not timestamp: return [] iso_time = timestamp.strftime("%Y-%m-%dT%H:%M:%S") success, output = run_cmd( ["git", "diff", "--name-only", f"--since={iso_time}", "HEAD"], cwd=project_path ) # Fallback: get files changed in commits since timestamp if not output: success, output = run_cmd( ["git", "log", f"--since={iso_time}", "--name-only", "--pretty=format:"], cwd=project_path ) if success and output: files = [f.strip() for f in output.split("\n") if f.strip()] return list(set(files)) # Deduplicate return [] def check_files_exist(files: list[str], project_path: str) -> tuple[list[str], list[str]]: """Check which files from handoff still exist.""" existing = [] missing = [] for f in files: full_path = Path(project_path) / f if full_path.exists(): existing.append(f) else: missing.append(f) return existing, missing def calculate_staleness_level( days_old: float, commits_since: int, files_changed: int, branch_matches: bool, files_missing: int ) -> tuple[str, str, list[str]]: """Calculate staleness level and provide recommendations. Staleness scoring rationale: - Each factor adds 1-3 points based on severity - Thresholds based on typical development patterns: - Age: 1 day (active work), 7 days (sprint), 30 days (stale) - Commits: 5 (minor changes), 20 (feature work), 50 (major changes) - Files: 5 (localized), 20 (widespread changes) - Final score: 0=FRESH, 1-2=SLIGHTLY_STALE, 3-4=STALE, 5+=VERY_STALE """ issues = [] # Scoring staleness_score = 0 # Age thresholds: 1 day = active, 7 days = sprint boundary, 30 days = likely stale if days_old > 30: staleness_score += 3 # Over a month: high risk of outdated context issues.append(f"Handoff is {int(days_old)} days old") elif days_old > 7: staleness_score += 2 # Over a week: moderate staleness issues.append(f"Handoff is {int(days_old)} days old") elif days_old > 1: staleness_score += 1 # Over a day: minor staleness # Commit thresholds: 5 = routine, 20 = feature work, 50 = major development if commits_since > 50: staleness_score += 3 # Major changes likely invalidate handoff context issues.append(f"{commits_since} commits since handoff - significant changes") elif commits_since > 20: staleness_score += 2 # Substantial work done since handoff issues.append(f"{commits_since} commits since handoff") elif commits_since > 5: staleness_score += 1 # Some changes, worth reviewing # Branch mismatch: likely working on different feature/context if not branch_matches: staleness_score += 2 # Different branch = different context issues.append("Current branch differs from handoff branch") # Missing files: 5+ suggests significant restructuring if files_missing > 5: staleness_score += 2 # Many refs broken = codebase restructured issues.append(f"{files_missing} referenced files no longer exist") elif files_missing > 0: staleness_score += 1 # Some refs broken issues.append(f"{files_missing} referenced file(s) missing") # Changed files: 5 = localized, 20 = widespread if files_changed > 20: staleness_score += 2 # Widespread changes affect handoff relevance issues.append(f"{files_changed} files changed since handoff") elif files_changed > 5: staleness_score += 1 # Some files changed # Staleness levels: 0=fresh, 1-2=slight, 3-4=stale, 5+=very stale if staleness_score == 0: level = "FRESH" recommendation = "Safe to resume - minimal changes since handoff" elif staleness_score <= 2: level = "SLIGHTLY_STALE" recommendation = "Generally safe to resume - review changes before continuing" elif staleness_score <= 4: level = "STALE" recommendation = "Proceed with caution - significant changes may affect context" else: level = "VERY_STALE" recommendation = "Consider creating new handoff - too many changes since original" return level, recommendation, issues def check_staleness(handoff_path: str) -> dict: """Run staleness check on a handoff file.""" path = Path(handoff_path) if not path.exists(): return {"error": f"Handoff file not found: {handoff_path}"} # Parse handoff metadata = parse_handoff_metadata(handoff_path) # Determine project path project_path = metadata.get("project_path") if not project_path or not Path(project_path).exists(): # Fallback: assume handoff is in .claude/handoffs/ within project project_path = str(path.parent.parent.parent) # Check if git repo success, _ = run_cmd(["git", "rev-parse", "--git-dir"], cwd=project_path) is_git_repo = success result = { "handoff_file": str(path), "project_path": project_path, "is_git_repo": is_git_repo, "created": metadata["created"], "handoff_branch": metadata["branch"], } # Calculate age if metadata["created"]: age = datetime.now() - metadata["created"] result["days_old"] = age.total_seconds() / 86400 result["hours_old"] = age.total_seconds() / 3600 else: result["days_old"] = None result["hours_old"] = None if is_git_repo: # Git-based checks result["current_branch"] = get_current_branch(project_path) result["branch_matches"] = ( result["current_branch"] == metadata["branch"] if metadata["branch"] else True ) commits = get_commits_since(metadata["created"], project_path) result["commits_since"] = len(commits) result["recent_commits"] = commits[:5] # Show first 5 changed_files = get_changed_files_since(metadata["created"], project_path) result["files_changed_count"] = len(changed_files) result["files_changed"] = changed_files[:10] # Show first 10 # Check if handoff's modified files still exist existing, missing = check_files_exist(metadata["modified_files"], project_path) result["referenced_files_exist"] = len(existing) result["referenced_files_missing"] = missing # Calculate staleness level, recommendation, issues = calculate_staleness_level( result.get("days_old", 0) or 0, result["commits_since"], result["files_changed_count"], result["branch_matches"], len(missing) ) result["staleness_level"] = level result["recommendation"] = recommendation result["issues"] = issues else: # Non-git checks (limited) result["staleness_level"] = "UNKNOWN" result["recommendation"] = "Not a git repo - unable to detect changes" result["issues"] = ["Project is not a git repository"] return result def print_report(result: dict): """Print staleness report.""" if "error" in result: print(f"Error: {result['error']}") return print(f"\n{'='*60}") print(f"Handoff Staleness Report") print(f"{'='*60}") print(f"File: {result['handoff_file']}") print(f"Project: {result['project_path']}") if result["created"]: print(f"Created: {result['created'].strftime('%Y-%m-%d %H:%M:%S')}") if result["days_old"] is not None: if result["days_old"] < 1: print(f"Age: {result['hours_old']:.1f} hours") else: print(f"Age: {result['days_old']:.1f} days") print(f"\n{'='*60}") print(f"Staleness Level: {result['staleness_level']}") print(f"{'='*60}") print(f"\nRecommendation: {result['recommendation']}") if result.get("issues"): print(f"\nIssues detected:") for issue in result["issues"]: print(f" - {issue}") if result.get("is_git_repo"): print(f"\n--- Git Status ---") print(f"Handoff branch: {result.get('handoff_branch', 'Unknown')}") print(f"Current branch: {result.get('current_branch', 'Unknown')}") print(f"Branch matches: {'Yes' if result.get('branch_matches') else 'No'}") print(f"Commits since handoff: {result.get('commits_since', 0)}") print(f"Files changed: {result.get('files_changed_count', 0)}") if result.get("recent_commits"): print(f"\nRecent commits:") for commit in result["recent_commits"][:5]: print(f" {commit}") if result.get("referenced_files_missing"): print(f"\nMissing referenced files:") for f in result["referenced_files_missing"][:5]: print(f" - {f}") print(f"\n{'='*60}") # Color-coded verdict (using text indicators) level = result.get("staleness_level", "UNKNOWN") if level == "FRESH": print("Verdict: [OK] Safe to resume") elif level == "SLIGHTLY_STALE": print("Verdict: [OK] Review changes, then resume") elif level == "STALE": print("Verdict: [CAUTION] Verify context before resuming") elif level == "VERY_STALE": print("Verdict: [WARNING] Consider creating fresh handoff") else: print("Verdict: [UNKNOWN] Manual verification needed") def main(): if len(sys.argv) < 2: print("Usage: python check_staleness.py <handoff-file>") print("Example: python check_staleness.py .claude/handoffs/2024-01-15-auth.md") sys.exit(1) handoff_path = sys.argv[1] result = check_staleness(handoff_path) print_report(result) # Exit code based on staleness level = result.get("staleness_level", "UNKNOWN") if level in ["FRESH", "SLIGHTLY_STALE"]: sys.exit(0) elif level == "STALE": sys.exit(1) else: sys.exit(2) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/enterprise-communication/session-handoff/scripts/check_staleness.py", "license": "MIT License", "lines": 316, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/enterprise-communication/session-handoff/scripts/create_handoff.py
#!/usr/bin/env python3 """ Smart scaffold generator for handoff documents. Creates a new handoff document with auto-detected metadata: - Current timestamp - Project path - Git branch (if available) - Recent git log - Modified/staged files - Handoff chain linking Usage: python create_handoff.py [task-slug] [--continues-from <previous-handoff>] python create_handoff.py "implementing-auth" python create_handoff.py "auth-part-2" --continues-from 2024-01-15-auth.md python create_handoff.py # auto-generates slug from timestamp """ import argparse import os import re import subprocess import sys from datetime import datetime from pathlib import Path def run_cmd(cmd: list[str], cwd: str = None) -> tuple[bool, str]: """Run a command and return (success, output).""" try: result = subprocess.run( cmd, capture_output=True, text=True, cwd=cwd, timeout=10 ) return result.returncode == 0, result.stdout.strip() except (subprocess.TimeoutExpired, FileNotFoundError): return False, "" def get_git_info(project_path: str) -> dict: """Gather git information from the project.""" info = { "is_git_repo": False, "branch": None, "recent_commits": [], "modified_files": [], "staged_files": [], } # Check if git repo success, _ = run_cmd(["git", "rev-parse", "--git-dir"], cwd=project_path) if not success: return info info["is_git_repo"] = True # Get current branch success, branch = run_cmd(["git", "branch", "--show-current"], cwd=project_path) if success and branch: info["branch"] = branch # Get recent commits (last 5) success, log = run_cmd( ["git", "log", "--oneline", "-5", "--no-decorate"], cwd=project_path ) if success and log: info["recent_commits"] = log.split("\n") # Get modified files (unstaged) success, modified = run_cmd( ["git", "diff", "--name-only"], cwd=project_path ) if success and modified: info["modified_files"] = modified.split("\n") # Get staged files success, staged = run_cmd( ["git", "diff", "--name-only", "--cached"], cwd=project_path ) if success and staged: info["staged_files"] = staged.split("\n") return info def find_previous_handoffs(project_path: str) -> list[dict]: """Find existing handoffs in the project.""" handoffs_dir = Path(project_path) / ".claude" / "handoffs" if not handoffs_dir.exists(): return [] handoffs = [] for filepath in handoffs_dir.glob("*.md"): # Extract title from file try: content = filepath.read_text() match = re.search(r'^#\s+(?:Handoff:\s*)?(.+)$', content, re.MULTILINE) title = match.group(1).strip() if match else filepath.stem except Exception: title = filepath.stem # Parse date from filename date_match = re.match(r'(\d{4}-\d{2}-\d{2})-(\d{6})', filepath.name) if date_match: try: date = datetime.strptime( f"{date_match.group(1)} {date_match.group(2)}", "%Y-%m-%d %H%M%S" ) except ValueError: date = None else: date = None handoffs.append({ "filename": filepath.name, "path": str(filepath), "title": title, "date": date, }) # Sort by date, most recent first handoffs.sort(key=lambda x: x["date"] or datetime.min, reverse=True) return handoffs def get_previous_handoff_info(project_path: str, continues_from: str = None) -> dict: """Get information about the previous handoff for chaining.""" handoffs = find_previous_handoffs(project_path) if continues_from: # Find specific handoff for h in handoffs: if continues_from in h["filename"]: return { "exists": True, "filename": h["filename"], "title": h["title"], } return {"exists": False, "filename": continues_from, "title": "Not found"} elif handoffs: # Suggest most recent most_recent = handoffs[0] return { "exists": True, "filename": most_recent["filename"], "title": most_recent["title"], "suggested": True, } return {"exists": False} def generate_handoff( project_path: str, slug: str = None, continues_from: str = None ) -> str: """Generate a handoff document with pre-filled metadata.""" # Generate timestamp and filename now = datetime.now() timestamp = now.strftime("%Y-%m-%d %H:%M:%S") file_timestamp = now.strftime("%Y-%m-%d-%H%M%S") if not slug: slug = "handoff" # Sanitize slug slug = slug.lower().replace(" ", "-").replace("_", "-") slug = "".join(c for c in slug if c.isalnum() or c == "-") filename = f"{file_timestamp}-{slug}.md" # Create handoffs directory handoffs_dir = Path(project_path) / ".claude" / "handoffs" handoffs_dir.mkdir(parents=True, exist_ok=True) filepath = handoffs_dir / filename # Gather git info git_info = get_git_info(project_path) # Get previous handoff info for chaining prev_handoff = get_previous_handoff_info(project_path, continues_from) # Build pre-filled sections branch_line = git_info["branch"] if git_info["branch"] else "[not a git repo or detached HEAD]" # Recent commits section if git_info["recent_commits"]: commits_section = "\n".join(f" - {c}" for c in git_info["recent_commits"]) else: commits_section = " - [no recent commits or not a git repo]" # Modified files section all_modified = list(set(git_info["modified_files"] + git_info["staged_files"])) if all_modified: modified_section = "\n".join(f"| {f} | [describe changes] | [why changed] |" for f in all_modified[:10]) if len(all_modified) > 10: modified_section += f"\n| ... and {len(all_modified) - 10} more files | | |" else: modified_section = "| [no modified files detected] | | |" # Handoff chain section if prev_handoff.get("exists"): chain_section = f"""## Handoff Chain - **Continues from**: [{prev_handoff['filename']}](./{prev_handoff['filename']}) - Previous title: {prev_handoff.get('title', 'Unknown')} - **Supersedes**: [list any older handoffs this replaces, or "None"] > Review the previous handoff for full context before filling this one.""" else: chain_section = """## Handoff Chain - **Continues from**: None (fresh start) - **Supersedes**: None > This is the first handoff for this task.""" # Generate the document content = f"""# Handoff: [TASK_TITLE - replace this] ## Session Metadata - Created: {timestamp} - Project: {project_path} - Branch: {branch_line} - Session duration: [estimate how long you worked] ### Recent Commits (for context) {commits_section} {chain_section} ## Current State Summary [TODO: Write one paragraph describing what was being worked on, current status, and where things left off] ## Codebase Understanding ### Architecture Overview [TODO: Document key architectural insights discovered during this session] ### Critical Files | File | Purpose | Relevance | |------|---------|-----------| | [TODO: Add critical files] | | | ### Key Patterns Discovered [TODO: Document important patterns, conventions, or idioms found in this codebase] ## Work Completed ### Tasks Finished - [ ] [TODO: List completed tasks] ### Files Modified | File | Changes | Rationale | |------|---------|-----------| {modified_section} ### Decisions Made | Decision | Options Considered | Rationale | |----------|-------------------|-----------| | [TODO: Document key decisions] | | | ## Pending Work ### Immediate Next Steps 1. [TODO: Most critical next action] 2. [TODO: Second priority] 3. [TODO: Third priority] ### Blockers/Open Questions - [ ] [TODO: List any blockers or open questions] ### Deferred Items - [TODO: Items deferred and why] ## Context for Resuming Agent ### Important Context [TODO: This is the MOST IMPORTANT section - write critical information the next agent MUST know] ### Assumptions Made - [TODO: List assumptions made during this session] ### Potential Gotchas - [TODO: Document things that might trip up a new agent] ## Environment State ### Tools/Services Used - [TODO: List relevant tools and their configuration] ### Active Processes - [TODO: Note any running processes, servers, etc.] ### Environment Variables - [TODO: List relevant env var NAMES only - NEVER include actual values/secrets] ## Related Resources - [TODO: Add links to relevant docs and files] --- **Security Reminder**: Before finalizing, run `validate_handoff.py` to check for accidental secret exposure. """ # Write the file filepath.write_text(content) return str(filepath) def main(): parser = argparse.ArgumentParser( description="Create a new handoff document with smart scaffolding" ) parser.add_argument( "slug", nargs="?", default=None, help="Short identifier for the handoff (e.g., 'implementing-auth')" ) parser.add_argument( "--continues-from", dest="continues_from", help="Filename of previous handoff this continues from" ) args = parser.parse_args() # Get project path (current working directory) project_path = os.getcwd() # Check for existing handoffs to suggest chaining if not args.continues_from: prev_handoffs = find_previous_handoffs(project_path) if prev_handoffs: print(f"Found {len(prev_handoffs)} existing handoff(s).") print(f"Most recent: {prev_handoffs[0]['filename']}") print(f"Use --continues-from <filename> to link handoffs.\n") # Generate handoff filepath = generate_handoff(project_path, args.slug, args.continues_from) print(f"Created handoff document: {filepath}") print(f"\nNext steps:") print(f"1. Open {filepath}") print(f"2. Replace [TODO: ...] placeholders with actual content") print(f"3. Focus especially on 'Important Context' and 'Immediate Next Steps'") print(f"4. Run: python validate_handoff.py {filepath}") print(f" (Checks for completeness and accidental secrets)") return filepath if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/enterprise-communication/session-handoff/scripts/create_handoff.py", "license": "MIT License", "lines": 285, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/enterprise-communication/session-handoff/scripts/list_handoffs.py
#!/usr/bin/env python3 """ List available handoff documents in the current project. Searches for handoff documents in .claude/handoffs/ and displays: - Filename with date - Title extracted from document - Status (if marked complete) Usage: python list_handoffs.py # List handoffs in current project python list_handoffs.py /path # List handoffs in specified path """ import os import re import sys from datetime import datetime from pathlib import Path def extract_title(filepath: Path) -> str: """Extract the title from a handoff document.""" try: content = filepath.read_text() # Look for first H1 header match = re.search(r'^#\s+(?:Handoff:\s*)?(.+)$', content, re.MULTILINE) if match: title = match.group(1).strip() # Clean up placeholder text if title.startswith("[") and title.endswith("]"): return "[Untitled - needs completion]" return title[:50] + "..." if len(title) > 50 else title except Exception: pass return "[Unable to read title]" def check_completion_status(filepath: Path) -> str: """Check if handoff appears complete or has TODOs remaining.""" try: content = filepath.read_text() todo_count = content.count("[TODO:") if todo_count == 0: return "Complete" elif todo_count <= 3: return f"In Progress ({todo_count} TODOs)" else: return f"Needs Work ({todo_count} TODOs)" except Exception: return "Unknown" def parse_date_from_filename(filename: str) -> datetime | None: """Extract date from filename like 2024-01-15-143022-slug.md""" match = re.match(r'(\d{4}-\d{2}-\d{2})-(\d{6})', filename) if match: try: date_str = match.group(1) time_str = match.group(2) return datetime.strptime(f"{date_str} {time_str}", "%Y-%m-%d %H%M%S") except ValueError: pass return None def list_handoffs(project_path: str) -> list[dict]: """List all handoff documents in a project.""" handoffs_dir = Path(project_path) / ".claude" / "handoffs" if not handoffs_dir.exists(): return [] handoffs = [] for filepath in handoffs_dir.glob("*.md"): parsed_date = parse_date_from_filename(filepath.name) handoffs.append({ "path": str(filepath), "filename": filepath.name, "title": extract_title(filepath), "status": check_completion_status(filepath), "date": parsed_date, "size": filepath.stat().st_size, }) # Sort by date, most recent first handoffs.sort(key=lambda x: x["date"] or datetime.min, reverse=True) return handoffs def format_date(dt: datetime | None) -> str: """Format datetime for display.""" if dt is None: return "Unknown date" return dt.strftime("%Y-%m-%d %H:%M") def main(): # Get project path project_path = sys.argv[1] if len(sys.argv) > 1 else os.getcwd() handoffs = list_handoffs(project_path) if not handoffs: print(f"No handoffs found in {project_path}/.claude/handoffs/") print("\nTo create a handoff, run: python create_handoff.py [task-slug]") return print(f"Found {len(handoffs)} handoff(s) in {project_path}/.claude/handoffs/\n") print("-" * 80) for h in handoffs: print(f" Date: {format_date(h['date'])}") print(f" Title: {h['title']}") print(f" Status: {h['status']}") print(f" File: {h['filename']}") print("-" * 80) print(f"\nTo resume from a handoff, read the document and follow the resume checklist.") print(f"Most recent: {handoffs[0]['path']}") if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/enterprise-communication/session-handoff/scripts/list_handoffs.py", "license": "MIT License", "lines": 99, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/enterprise-communication/session-handoff/scripts/validate_handoff.py
#!/usr/bin/env python3 """ Validate a handoff document for completeness and quality. Checks: - No TODO placeholders remaining - Required sections present and populated - No potential secrets detected - Referenced files exist - Quality scoring Usage: python validate_handoff.py <handoff-file> python validate_handoff.py .claude/handoffs/2024-01-15-143022-auth.md """ import os import re import sys from pathlib import Path # Secret detection patterns SECRET_PATTERNS = [ (r'["\']?[a-zA-Z_]*api[_-]?key["\']?\s*[:=]\s*["\'][^"\']{10,}["\']', "API key"), (r'["\']?[a-zA-Z_]*password["\']?\s*[:=]\s*["\'][^"\']+["\']', "Password"), (r'["\']?[a-zA-Z_]*secret["\']?\s*[:=]\s*["\'][^"\']{10,}["\']', "Secret"), (r'["\']?[a-zA-Z_]*token["\']?\s*[:=]\s*["\'][^"\']{20,}["\']', "Token"), (r'["\']?[a-zA-Z_]*private[_-]?key["\']?\s*[:=]', "Private key"), (r'-----BEGIN [A-Z]+ PRIVATE KEY-----', "PEM private key"), (r'mongodb(\+srv)?://[^/\s]+:[^@\s]+@', "MongoDB connection string with password"), (r'postgres://[^/\s]+:[^@\s]+@', "PostgreSQL connection string with password"), (r'mysql://[^/\s]+:[^@\s]+@', "MySQL connection string with password"), (r'Bearer\s+[a-zA-Z0-9_\-\.]+', "Bearer token"), (r'ghp_[a-zA-Z0-9]{36}', "GitHub personal access token"), (r'sk-[a-zA-Z0-9]{48}', "OpenAI API key"), (r'xox[baprs]-[a-zA-Z0-9-]+', "Slack token"), ] # Required sections for a complete handoff REQUIRED_SECTIONS = [ "Current State Summary", "Important Context", "Immediate Next Steps", ] # Recommended sections RECOMMENDED_SECTIONS = [ "Architecture Overview", "Critical Files", "Files Modified", "Decisions Made", "Assumptions Made", "Potential Gotchas", ] def check_todos(content: str) -> tuple[bool, list[str]]: """Check for remaining TODO placeholders.""" todos = re.findall(r'\[TODO:[^\]]*\]', content) return len(todos) == 0, todos def check_required_sections(content: str) -> tuple[bool, list[str]]: """Check that required sections exist and have content.""" missing = [] for section in REQUIRED_SECTIONS: # Look for section header pattern = rf'(?:^|\n)##?\s*{re.escape(section)}' match = re.search(pattern, content, re.IGNORECASE) if not match: missing.append(f"{section} (missing)") else: # Check if section has meaningful content (not just placeholder) section_start = match.end() next_section = re.search(r'\n##?\s+', content[section_start:]) section_end = section_start + next_section.start() if next_section else len(content) section_content = content[section_start:section_end].strip() # 50 chars minimum: roughly 1-2 sentences, enough to convey meaningful context if len(section_content) < 50 or '[TODO' in section_content: missing.append(f"{section} (incomplete)") return len(missing) == 0, missing def check_recommended_sections(content: str) -> list[str]: """Check which recommended sections are missing.""" missing = [] for section in RECOMMENDED_SECTIONS: pattern = rf'(?:^|\n)##?\s*{re.escape(section)}' if not re.search(pattern, content, re.IGNORECASE): missing.append(section) return missing def scan_for_secrets(content: str) -> list[tuple[str, str]]: """Scan content for potential secrets.""" findings = [] for pattern, description in SECRET_PATTERNS: matches = re.findall(pattern, content, re.IGNORECASE) if matches: findings.append((description, f"Found {len(matches)} potential match(es)")) return findings def check_file_references(content: str, base_path: str) -> tuple[list[str], list[str]]: """Check if referenced files exist.""" # Extract file paths from content (look for common patterns) # Pattern 1: | path/to/file | in tables # Pattern 2: `path/to/file` in code # Pattern 3: path/to/file:123 with line numbers patterns = [ r'\|\s*([a-zA-Z0-9_\-./]+\.[a-zA-Z]+)\s*\|', # Table cells r'`([a-zA-Z0-9_\-./]+\.[a-zA-Z]+(?::\d+)?)`', # Inline code r'(?:^|\s)([a-zA-Z0-9_\-./]+\.[a-zA-Z]+:\d+)', # With line numbers ] found_files = set() for pattern in patterns: matches = re.findall(pattern, content) for match in matches: # Remove line numbers filepath = match.split(':')[0] # Skip obvious non-files if filepath and not filepath.startswith('http') and '/' in filepath: found_files.add(filepath) existing = [] missing = [] for filepath in found_files: full_path = Path(base_path) / filepath if full_path.exists(): existing.append(filepath) else: missing.append(filepath) return existing, missing def calculate_quality_score( todos_clear: bool, required_complete: bool, missing_required: list, missing_recommended: list, secrets_found: list, files_missing: list ) -> tuple[int, str]: """Calculate overall quality score (0-100). Scoring rationale: - Start at 100, deduct for issues - TODOs remaining (-30): Indicates incomplete work, major blocker - Missing required sections (-10 each): Core context gaps - Secrets detected (-20): Security risk, must be fixed - Missing file refs (-5 each, max -20): Stale references - Missing recommended (-2 each): Nice-to-have completeness """ score = 100 # Deductions with justifications if not todos_clear: # -30: TODOs indicate unfinished work; next agent will lack critical info score -= 30 if not required_complete: # -10 per section: Required sections are essential for handoff continuity score -= 10 * len(missing_required) if secrets_found: # -20: Security risk; handoffs may be shared or stored in repos score -= 20 if files_missing: # -5 per file (max 4): Indicates stale refs; cap at -20 to avoid over-penalizing score -= 5 * min(len(files_missing), 4) # -2 per section: Recommended but not critical; minor impact on handoff quality score -= 2 * len(missing_recommended) score = max(0, score) # Rating thresholds based on handoff usability: # 90+: Comprehensive, ready to use immediately # 70-89: Usable with minor gaps # 50-69: Needs work before reliable handoff # <50: Too incomplete to be useful if score >= 90: rating = "Excellent - Ready for handoff" elif score >= 70: rating = "Good - Minor improvements suggested" elif score >= 50: rating = "Fair - Needs attention before handoff" else: rating = "Poor - Significant work needed" return score, rating def validate_handoff(filepath: str) -> dict: """Run all validations on a handoff file.""" path = Path(filepath) if not path.exists(): return {"error": f"File not found: {filepath}"} content = path.read_text() base_path = path.parent.parent.parent # Go up from .claude/handoffs/ # Run checks todos_clear, remaining_todos = check_todos(content) required_complete, missing_required = check_required_sections(content) missing_recommended = check_recommended_sections(content) secrets_found = scan_for_secrets(content) existing_files, missing_files = check_file_references(content, str(base_path)) # Calculate score score, rating = calculate_quality_score( todos_clear, required_complete, missing_required, missing_recommended, secrets_found, missing_files ) return { "filepath": str(path), "score": score, "rating": rating, "todos_clear": todos_clear, "remaining_todos": remaining_todos[:5], # Limit output "todo_count": len(remaining_todos) if not todos_clear else 0, "required_complete": required_complete, "missing_required": missing_required, "missing_recommended": missing_recommended, "secrets_found": secrets_found, "files_verified": len(existing_files), "files_missing": missing_files[:5], # Limit output } def print_report(result: dict): """Print a formatted validation report.""" if "error" in result: print(f"Error: {result['error']}") return False print(f"\n{'='*60}") print(f"Handoff Validation Report") print(f"{'='*60}") print(f"File: {result['filepath']}") print(f"\nQuality Score: {result['score']}/100 - {result['rating']}") print(f"{'='*60}") # TODOs if result['todos_clear']: print("\n[PASS] No TODO placeholders remaining") else: print(f"\n[FAIL] {result['todo_count']} TODO placeholders found:") for todo in result['remaining_todos']: print(f" - {todo[:50]}...") # Required sections if result['required_complete']: print("\n[PASS] All required sections complete") else: print("\n[FAIL] Missing/incomplete required sections:") for section in result['missing_required']: print(f" - {section}") # Secrets if not result['secrets_found']: print("\n[PASS] No potential secrets detected") else: print("\n[WARN] Potential secrets detected:") for secret_type, detail in result['secrets_found']: print(f" - {secret_type}: {detail}") # File references if result['files_missing']: print(f"\n[WARN] {len(result['files_missing'])} referenced file(s) not found:") for f in result['files_missing']: print(f" - {f}") else: print(f"\n[INFO] {result['files_verified']} file reference(s) verified") # Recommended sections if result['missing_recommended']: print(f"\n[INFO] Consider adding these sections:") for section in result['missing_recommended']: print(f" - {section}") print(f"\n{'='*60}") # Final verdict if result['score'] >= 70 and not result['secrets_found']: print("Verdict: READY for handoff") return True elif result['secrets_found']: print("Verdict: BLOCKED - Remove secrets before handoff") return False else: print("Verdict: NEEDS WORK - Complete required sections") return False def main(): if len(sys.argv) < 2: print("Usage: python validate_handoff.py <handoff-file>") print("Example: python validate_handoff.py .claude/handoffs/2024-01-15-auth.md") sys.exit(1) filepath = sys.argv[1] result = validate_handoff(filepath) success = print_report(result) sys.exit(0 if success else 1) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/enterprise-communication/session-handoff/scripts/validate_handoff.py", "license": "MIT License", "lines": 262, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/hooks/security/secret-scanner.py
#!/usr/bin/env python3 """ Secret Scanner Hook Detects hardcoded secrets before git commits """ import json import sys import re import subprocess import os # Secret detection patterns with descriptions SECRET_PATTERNS = [ # AWS Keys (r'AKIA[0-9A-Z]{16}', 'AWS Access Key ID', 'high'), (r'(?i)aws[_\-\s]*secret[_\-\s]*access[_\-\s]*key[\'"\s]*[=:][\'"\s]*[A-Za-z0-9/+=]{40}', 'AWS Secret Access Key', 'high'), # Anthropic (Claude) API Keys (r'sk-ant-api\d{2}-[A-Za-z0-9\-_]{20,}', 'Anthropic API Key', 'high'), # OpenAI API Keys (r'sk-[a-zA-Z0-9]{48,}', 'OpenAI API Key', 'high'), (r'sk-proj-[a-zA-Z0-9\-_]{32,}', 'OpenAI Project API Key', 'high'), # Google API Keys & Service Accounts (r'AIza[0-9A-Za-z\-_]{35}', 'Google API Key', 'high'), (r'ya29\.[0-9A-Za-z\-_]+', 'Google OAuth Access Token', 'high'), # Stripe API Keys (r'sk_live_[0-9a-zA-Z]{24,}', 'Stripe Live Secret Key', 'critical'), (r'sk_test_[0-9a-zA-Z]{24,}', 'Stripe Test Secret Key', 'medium'), (r'rk_live_[0-9a-zA-Z]{24,}', 'Stripe Live Restricted Key', 'high'), (r'pk_live_[0-9a-zA-Z]{24,}', 'Stripe Live Publishable Key', 'medium'), # GitHub Tokens (r'ghp_[0-9a-zA-Z]{36}', 'GitHub Personal Access Token', 'high'), (r'gho_[0-9a-zA-Z]{36}', 'GitHub OAuth Token', 'high'), (r'ghs_[0-9a-zA-Z]{36}', 'GitHub App Secret', 'high'), (r'ghr_[0-9a-zA-Z]{36}', 'GitHub Refresh Token', 'high'), (r'github_pat_[0-9a-zA-Z_]{22,}', 'GitHub Fine-Grained PAT', 'high'), # GitLab Tokens (r'glpat-[0-9a-zA-Z\-_]{20,}', 'GitLab Personal Access Token', 'high'), # Vercel Tokens (r'vercel_[0-9a-zA-Z_\-]{24,}', 'Vercel Token', 'high'), # Supabase Keys (r'sbp_[0-9a-f]{40}', 'Supabase Service Key', 'high'), (r'sb_publishable_[A-Za-z0-9\-_]{20,}', 'Supabase Publishable Key', 'medium'), (r'sb_secret_[A-Za-z0-9\-_]{20,}', 'Supabase Secret Key', 'high'), # Hugging Face Tokens (r'hf_[a-zA-Z0-9]{34,}', 'Hugging Face Token', 'high'), # Replicate API Tokens (r'r8_[a-zA-Z0-9]{38,}', 'Replicate API Token', 'high'), # Groq API Keys (r'gsk_[a-zA-Z0-9]{48,}', 'Groq API Key', 'high'), # Databricks Personal Access Tokens (r'dapi[0-9a-f]{32}', 'Databricks Access Token', 'high'), # Azure Keys (r'(?i)azure[_\-\s]*(?:key|secret|token)[\'"\s]*[=:][\'"\s]*[A-Za-z0-9+/=]{32,}', 'Azure Key', 'high'), # Cloudflare API Tokens (r'(?:cf|cloudflare)[_\-]?[A-Za-z0-9_\-]{37,}', 'Cloudflare API Token', 'medium'), # DigitalOcean Tokens (r'dop_v1_[0-9a-f]{64}', 'DigitalOcean Personal Access Token', 'high'), (r'doo_v1_[0-9a-f]{64}', 'DigitalOcean OAuth Token', 'high'), # Linear API Keys (r'lin_api_[a-zA-Z0-9]{40,}', 'Linear API Key', 'high'), # Notion API Keys (r'ntn_[0-9a-zA-Z]{40,}', 'Notion Integration Token', 'high'), (r'secret_[0-9a-zA-Z]{43}', 'Notion API Key (legacy)', 'high'), # Figma Access Tokens (r'figd_[0-9a-zA-Z\-_]{40,}', 'Figma Access Token', 'high'), # npm Tokens (r'npm_[0-9a-zA-Z]{36,}', 'npm Access Token', 'high'), # PyPI API Tokens (r'pypi-[A-Za-z0-9\-_]{16,}', 'PyPI API Token', 'high'), # Generic API Keys (r'(?i)(api[_\-\s]*key|apikey)[\'"\s]*[=:][\'"\s]*[\'"][0-9a-zA-Z\-_]{20,}[\'"]', 'Generic API Key', 'medium'), (r'(?i)(secret[_\-\s]*key|secretkey)[\'"\s]*[=:][\'"\s]*[\'"][0-9a-zA-Z\-_]{20,}[\'"]', 'Generic Secret Key', 'medium'), (r'(?i)(access[_\-\s]*token|accesstoken)[\'"\s]*[=:][\'"\s]*[\'"][0-9a-zA-Z\-_]{20,}[\'"]', 'Generic Access Token', 'medium'), # Passwords (r'(?i)password[\'"\s]*[=:][\'"\s]*[\'"][^\'"\s]{8,}[\'"]', 'Hardcoded Password', 'high'), (r'(?i)passwd[\'"\s]*[=:][\'"\s]*[\'"][^\'"\s]{8,}[\'"]', 'Hardcoded Password', 'high'), # Private Keys (r'-----BEGIN (RSA |DSA |EC )?PRIVATE KEY-----', 'Private Key', 'critical'), (r'-----BEGIN OPENSSH PRIVATE KEY-----', 'OpenSSH Private Key', 'critical'), # Database Connection Strings (r'(?i)(mysql|postgresql|postgres|mongodb)://[^\s\'"\)]+:[^\s\'"\)]+@', 'Database Connection String', 'high'), (r'(?i)Server=[^;]+;Database=[^;]+;User Id=[^;]+;Password=[^;]+', 'SQL Server Connection String', 'high'), # JWT Tokens (r'eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}', 'JWT Token', 'medium'), # Slack Tokens (r'xox[baprs]-[0-9a-zA-Z\-]{10,}', 'Slack Token', 'high'), # Telegram Bot Tokens (r'[0-9]{8,10}:[A-Za-z0-9_\-]{35}', 'Telegram Bot Token', 'medium'), # Discord Webhooks (r'https://discord\.com/api/webhooks/[0-9]+/[A-Za-z0-9_\-]+', 'Discord Webhook URL', 'medium'), # Twilio API Keys (r'SK[0-9a-fA-F]{32}', 'Twilio API Key', 'high'), # SendGrid API Keys (r'SG\.[A-Za-z0-9_\-]{22}\.[A-Za-z0-9_\-]{43}', 'SendGrid API Key', 'high'), # Mailgun API Keys (r'key-[0-9a-zA-Z]{32}', 'Mailgun API Key', 'medium'), # Heroku API Keys (r'[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}', 'Potential API Key (UUID format)', 'low'), ] # Files to exclude from scanning EXCLUDED_FILES = [ '.env.example', '.env.sample', '.env.template', 'package-lock.json', 'yarn.lock', 'poetry.lock', 'Pipfile.lock', 'Cargo.lock', 'go.sum', '.gitignore', ] # Directories to exclude EXCLUDED_DIRS = [ 'node_modules/', 'vendor/', '.git/', 'dist/', 'build/', '__pycache__/', '.pytest_cache/', 'venv/', 'env/', ] def should_skip_file(file_path): """Check if file should be skipped""" # Skip if file doesn't exist (might be deleted) if not os.path.exists(file_path): return True # Skip excluded files filename = os.path.basename(file_path) if filename in EXCLUDED_FILES: return True # Skip excluded directories for excluded_dir in EXCLUDED_DIRS: if excluded_dir in file_path: return True # Skip binary files try: with open(file_path, 'rb') as f: chunk = f.read(1024) if b'\0' in chunk: return True except: return True return False def get_staged_files(): """Get list of staged files""" try: result = subprocess.run( ['git', 'diff', '--cached', '--name-only', '--diff-filter=ACM'], capture_output=True, text=True, check=True ) return [f.strip() for f in result.stdout.split('\n') if f.strip()] except subprocess.CalledProcessError: return [] def scan_file(file_path): """Scan a single file for secrets""" findings = [] if should_skip_file(file_path): return findings try: with open(file_path, 'r', encoding='utf-8', errors='ignore') as f: content = f.read() for line_num, line in enumerate(content.split('\n'), 1): for pattern, description, severity in SECRET_PATTERNS: matches = re.finditer(pattern, line) for match in matches: # Skip if it looks like a comment or example line_stripped = line.strip() if line_stripped.startswith('#') or line_stripped.startswith('//'): # Check if it's actually a comment with example if 'example' in line_stripped.lower() or 'placeholder' in line_stripped.lower(): continue findings.append({ 'file': file_path, 'line': line_num, 'description': description, 'severity': severity, 'match': match.group(0)[:50] + '...' if len(match.group(0)) > 50 else match.group(0), 'full_line': line.strip()[:100] }) except Exception as e: # Skip files that can't be read pass return findings def print_findings(findings): """Print findings in a formatted way""" if not findings: return # Sort by severity severity_order = {'critical': 0, 'high': 1, 'medium': 2, 'low': 3} findings.sort(key=lambda x: (severity_order.get(x['severity'], 4), x['file'], x['line'])) print('', file=sys.stderr) print('🚨 SECRET SCANNER: Potential secrets detected!', file=sys.stderr) print('', file=sys.stderr) critical_count = sum(1 for f in findings if f['severity'] == 'critical') high_count = sum(1 for f in findings if f['severity'] == 'high') medium_count = sum(1 for f in findings if f['severity'] == 'medium') low_count = sum(1 for f in findings if f['severity'] == 'low') print(f'Found {len(findings)} potential secret(s):', file=sys.stderr) if critical_count > 0: print(f' 🔴 Critical: {critical_count}', file=sys.stderr) if high_count > 0: print(f' 🟠 High: {high_count}', file=sys.stderr) if medium_count > 0: print(f' 🟡 Medium: {medium_count}', file=sys.stderr) if low_count > 0: print(f' 🔵 Low: {low_count}', file=sys.stderr) print('', file=sys.stderr) for finding in findings: severity_emoji = { 'critical': '🔴', 'high': '🟠', 'medium': '🟡', 'low': '🔵' }.get(finding['severity'], '⚪') print(f'{severity_emoji} {finding["description"]}', file=sys.stderr) print(f' File: {finding["file"]}:{finding["line"]}', file=sys.stderr) print(f' Match: {finding["match"]}', file=sys.stderr) print('', file=sys.stderr) print('❌ COMMIT BLOCKED: Remove secrets before committing', file=sys.stderr) print('', file=sys.stderr) print('How to fix:', file=sys.stderr) print(' 1. Move secrets to environment variables:', file=sys.stderr) print(' • Create/update .env file (ensure it\'s in .gitignore)', file=sys.stderr) print(' • Use process.env.SECRET_NAME (Node.js) or os.environ.get("SECRET_NAME") (Python)', file=sys.stderr) print('', file=sys.stderr) print(' 2. Use a secrets management service:', file=sys.stderr) print(' • AWS Secrets Manager, Google Secret Manager, Azure Key Vault', file=sys.stderr) print(' • HashiCorp Vault, Doppler, 1Password', file=sys.stderr) print('', file=sys.stderr) print(' 3. For false positives:', file=sys.stderr) print(' • Add comments with "example" or "placeholder" to skip detection', file=sys.stderr) print(' • Disable hook temporarily: remove from .claude/hooks.json', file=sys.stderr) print('', file=sys.stderr) def main(): # Read hook input from stdin (Claude Code passes JSON via stdin) try: input_data = json.load(sys.stdin) except (json.JSONDecodeError, ValueError): # If no valid JSON on stdin, allow the action sys.exit(0) # Only act on git commit commands tool_input = input_data.get('tool_input', {}) command = tool_input.get('command', '') if not re.search(r'git\s+commit', command): sys.exit(0) # Get staged files staged_files = get_staged_files() # PreToolUse runs before the command, so files may not be staged yet. # Handle two cases: # 1. git commit -a/-am: scans tracked modified files (what -a would stage) # 2. git add ... && git commit: scans files from the git add part if not staged_files: # Check if commit uses -a flag (auto-stage tracked modified files) commit_match = re.search(r'git\s+commit\s+(.+)', command) if commit_match and re.search(r'-\w*a', commit_match.group(1)): result = subprocess.run( ['git', 'diff', '--name-only'], capture_output=True, text=True ) for f in result.stdout.strip().split('\n'): if f.strip() and os.path.isfile(f.strip()): staged_files.append(f.strip()) # Check for chained git add ... && git commit for part in re.split(r'&&|;', command): part = part.strip() add_match = re.match(r'git\s+add\s+(.+)', part) if add_match: args = add_match.group(1).strip() if args in ('.', '-A', '--all'): result = subprocess.run( ['git', 'status', '--porcelain'], capture_output=True, text=True ) for line in result.stdout.strip().split('\n'): if line and len(line) > 3: f = line[3:].strip() if os.path.isfile(f): staged_files.append(f) else: for token in args.split(): if not token.startswith('-') and os.path.isfile(token): staged_files.append(token) if not staged_files: sys.exit(0) # Scan all staged files all_findings = [] for file_path in staged_files: findings = scan_file(file_path) all_findings.extend(findings) # If we found any secrets, block the commit if all_findings: print_findings(all_findings) sys.exit(2) # No secrets found, allow commit sys.exit(0) if __name__ == '__main__': main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/hooks/security/secret-scanner.py", "license": "MIT License", "lines": 301, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/hooks/security/dangerous-command-blocker.py
#!/usr/bin/env python3 """ Dangerous Command Blocker Hook Multi-level security system for blocking dangerous shell commands """ import json import sys import re # Load command from stdin data = json.load(sys.stdin) cmd = data.get('tool_input', {}).get('command', '') # === LEVEL 1: CATASTROPHIC COMMANDS (ALWAYS BLOCK) === catastrophic_patterns = [ (r'\brm\s+.*\s+/\s*$', 'rm on root directory'), (r'\brm\s+.*\s+~\s*$', 'rm on home directory'), (r'\brm\s+.*\s+\*\s*$', 'rm with star wildcard'), (r'\brm\s+-[rfRF]*[rfRF]+.*\*', 'rm -rf with wildcards'), (r'\b(dd\s+if=|dd\s+of=/dev)', 'dd disk operations'), (r'\b(mkfs\.|mkswap\s|fdisk\s)', 'filesystem formatting'), (r'\b:(\(\))?\s*\{\s*:\s*\|\s*:\s*&\s*\}', 'fork bomb'), (r'>\s*/dev/sd[a-z]', 'direct disk write'), (r'\bchmod\s+(-R\s+)?777\s+/', 'chmod 777 on root'), (r'\bchown\s+(-R\s+)?.*\s+/$', 'chown on root directory'), ] for pattern, desc in catastrophic_patterns: if re.search(pattern, cmd, re.IGNORECASE): print(f'❌ BLOCKED: Catastrophic command detected!', file=sys.stderr) print(f'', file=sys.stderr) print(f'Reason: {desc}', file=sys.stderr) print(f'Command: {cmd[:100]}', file=sys.stderr) print(f'', file=sys.stderr) print(f'This command could cause IRREVERSIBLE system damage or data loss.', file=sys.stderr) print(f'', file=sys.stderr) print(f'Safety tips:', file=sys.stderr) print(f' • Never use rm -rf with /, ~, or * wildcards', file=sys.stderr) print(f' • Avoid recursive operations on system directories', file=sys.stderr) print(f' • Use specific file paths instead of wildcards', file=sys.stderr) print(f' • For cleanup, target specific directories: rm -rf /tmp/myproject', file=sys.stderr) sys.exit(2) # === LEVEL 2: CRITICAL PATH PROTECTION === critical_paths = [ (r'\b(rm|mv)\s+(-[rfRF]+\s+)?\.claude(/|$|\s)', 'Claude Code configuration'), (r'\b(rm|mv)\s+(-[rfRF]+\s+)?\.git(/|$|\s)', 'Git repository'), (r'\b(rm|mv)\s+(-[rfRF]+\s+)?node_modules(/|$|\s)', 'Node.js dependencies'), (r'\b(rm|mv)\s+(-[rfRF]+\s+)?[^\s]*\.env\b', 'Environment variables'), (r'\b(rm|mv)\s+(-[rfRF]+\s+)?[^\s]*package\.json\b', 'Package manifest'), (r'\b(rm|mv)\s+(-[rfRF]+\s+)?[^\s]*package-lock\.json\b', 'Lock file'), (r'\b(rm|mv)\s+(-[rfRF]+\s+)?[^\s]*yarn\.lock\b', 'Yarn lock file'), (r'\b(rm|mv)\s+(-[rfRF]+\s+)?[^\s]*Cargo\.toml\b', 'Rust manifest'), (r'\b(rm|mv)\s+(-[rfRF]+\s+)?[^\s]*go\.mod\b', 'Go module file'), (r'\b(rm|mv)\s+(-[rfRF]+\s+)?[^\s]*requirements\.txt\b', 'Python dependencies'), (r'\b(rm|mv)\s+(-[rfRF]+\s+)?[^\s]*Gemfile(\.lock)?\b', 'Ruby dependencies'), (r'\b(rm|mv)\s+(-[rfRF]+\s+)?[^\s]*composer\.json\b', 'PHP dependencies'), ] for pattern, desc in critical_paths: if re.search(pattern, cmd, re.IGNORECASE): print(f'🛑 BLOCKED: Critical path protection activated!', file=sys.stderr) print(f'', file=sys.stderr) print(f'Protected resource: {desc}', file=sys.stderr) print(f'Command: {cmd[:100]}', file=sys.stderr) print(f'', file=sys.stderr) print(f'This path contains critical project files that should not be deleted accidentally.', file=sys.stderr) print(f'', file=sys.stderr) print(f'If you really need to modify this:', file=sys.stderr) print(f' 1. Disable the hook temporarily in .claude/hooks.json', file=sys.stderr) print(f' 2. Execute the command manually in your terminal', file=sys.stderr) print(f' 3. Or modify specific files instead of using rm/mv on entire directories', file=sys.stderr) sys.exit(2) # === LEVEL 3: SUSPICIOUS PATTERNS (WARNING) === suspicious_patterns = [ (r'\brm\s+.*\s+&&', 'chained rm commands'), (r'\brm\s+[^\s/]*\*', 'rm with wildcards'), (r'\bfind\s+.*-delete', 'find -delete operation'), (r'\bxargs\s+.*\brm', 'xargs with rm'), ] for pattern, desc in suspicious_patterns: if re.search(pattern, cmd, re.IGNORECASE): print(f'⚠️ WARNING: Suspicious command pattern detected!', file=sys.stderr) print(f'', file=sys.stderr) print(f'Pattern: {desc}', file=sys.stderr) print(f'Command: {cmd[:100]}', file=sys.stderr) print(f'', file=sys.stderr) print(f'This command uses patterns that could accidentally delete more than intended.', file=sys.stderr) print(f'Consider reviewing the command carefully before execution.', file=sys.stderr) print(f'', file=sys.stderr) # Exit 0 to allow but with warning sys.exit(0) # Command is safe sys.exit(0)
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/hooks/security/dangerous-command-blocker.py", "license": "MIT License", "lines": 89, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/analytics/google-analytics/scripts/analyze.py
#!/usr/bin/env python3 """ Google Analytics Data Analysis Tool Performs higher-level analysis on Google Analytics data including: - Period comparisons (current vs previous) - Trend detection - Performance insights - Automated recommendations Usage: python analyze.py --period last-30-days --compare previous-period python analyze.py --analysis-type traffic-sources --days 30 python analyze.py --analysis-type funnel --steps "homepage,/products,/cart,/checkout" """ import os import sys import json import argparse from datetime import datetime, timedelta from typing import Dict, List, Optional, Tuple try: from ga_client import GoogleAnalyticsClient except ImportError: print("Error: ga_client.py not found in the same directory", file=sys.stderr) sys.exit(1) class AnalyticsAnalyzer: """Performs analysis on Google Analytics data.""" def __init__(self): """Initialize the analyzer with GA client.""" self.client = GoogleAnalyticsClient() def compare_periods( self, current_days: int = 30, metrics: Optional[List[str]] = None ) -> Dict: """ Compare current period with previous period. Args: current_days: Number of days in current period metrics: List of metrics to compare (default: core metrics) Returns: Dictionary with comparison data and insights """ if metrics is None: metrics = [ "sessions", "activeUsers", "newUsers", "bounceRate", "engagementRate", "averageSessionDuration", ] # Fetch current period current = self.client.run_report( start_date=f"{current_days}daysAgo", end_date="yesterday", metrics=metrics, limit=1, ) # Fetch previous period previous_start = current_days * 2 previous_end = current_days + 1 previous = self.client.run_report( start_date=f"{previous_start}daysAgo", end_date=f"{previous_end}daysAgo", metrics=metrics, limit=1, ) # Calculate changes comparison = { "current_period": f"Last {current_days} days", "previous_period": f"Previous {current_days} days", "metrics": {}, } if current["totals"] and previous["totals"]: for i, metric in enumerate(metrics): current_val = float(current["totals"][i]["value"]) previous_val = float(previous["totals"][i]["value"]) # Calculate percentage change if previous_val != 0: change_pct = ((current_val - previous_val) / previous_val) * 100 else: change_pct = 0 comparison["metrics"][metric] = { "current": current_val, "previous": previous_val, "change": current_val - previous_val, "change_percent": round(change_pct, 2), } # Generate insights comparison["insights"] = self._generate_insights(comparison["metrics"]) return comparison def analyze_traffic_sources(self, days: int = 30, limit: int = 20) -> Dict: """ Analyze traffic sources and their performance. Args: days: Number of days to analyze limit: Number of sources to return Returns: Dictionary with source performance data and recommendations """ result = self.client.run_report( start_date=f"{days}daysAgo", end_date="yesterday", metrics=["sessions", "engagementRate", "bounceRate", "conversions"], dimensions=["sessionSource", "sessionMedium"], limit=limit, order_by="-sessions", ) # Analyze sources sources = [] for row in result["rows"]: source = row["dimensions"]["sessionSource"] medium = row["dimensions"]["sessionMedium"] sessions = int(row["metrics"]["sessions"]) engagement = float(row["metrics"]["engagementRate"]) bounce = float(row["metrics"]["bounceRate"]) conversions = int(row["metrics"].get("conversions", 0)) conv_rate = (conversions / sessions * 100) if sessions > 0 else 0 sources.append( { "source": source, "medium": medium, "sessions": sessions, "engagement_rate": round(engagement * 100, 2), "bounce_rate": round(bounce * 100, 2), "conversions": conversions, "conversion_rate": round(conv_rate, 2), } ) analysis = { "period": f"Last {days} days", "sources": sources, "recommendations": self._recommend_source_optimizations(sources), } return analysis def analyze_content_performance(self, days: int = 30, limit: int = 50) -> Dict: """ Analyze page performance and identify issues. Args: days: Number of days to analyze limit: Number of pages to return Returns: Dictionary with page performance and improvement opportunities """ result = self.client.run_report( start_date=f"{days}daysAgo", end_date="yesterday", metrics=[ "screenPageViews", "bounceRate", "averageSessionDuration", "conversions", ], dimensions=["pagePath", "pageTitle"], limit=limit, order_by="-screenPageViews", ) # Identify high-bounce pages high_bounce_threshold = 0.6 problem_pages = [] for row in result["rows"]: page_path = row["dimensions"]["pagePath"] page_title = row["dimensions"]["pageTitle"] views = int(row["metrics"]["screenPageViews"]) bounce = float(row["metrics"]["bounceRate"]) avg_duration = float(row["metrics"]["averageSessionDuration"]) if bounce > high_bounce_threshold and views > 100: problem_pages.append( { "path": page_path, "title": page_title, "views": views, "bounce_rate": round(bounce * 100, 2), "avg_duration": round(avg_duration, 2), "issue": self._diagnose_page_issue(bounce, avg_duration), } ) analysis = { "period": f"Last {days} days", "total_pages": result["row_count"], "high_bounce_pages": len(problem_pages), "problem_pages": problem_pages[:10], # Top 10 issues "recommendations": self._recommend_content_improvements(problem_pages), } return analysis def analyze_device_performance(self, days: int = 30) -> Dict: """ Compare performance across device types. Args: days: Number of days to analyze Returns: Dictionary with device performance comparison """ result = self.client.run_report( start_date=f"{days}daysAgo", end_date="yesterday", metrics=[ "sessions", "bounceRate", "averageSessionDuration", "conversions", "engagementRate", ], dimensions=["deviceCategory"], limit=10, order_by="-sessions", ) devices = [] for row in result["rows"]: device = row["dimensions"]["deviceCategory"] sessions = int(row["metrics"]["sessions"]) bounce = float(row["metrics"]["bounceRate"]) duration = float(row["metrics"]["averageSessionDuration"]) conversions = int(row["metrics"].get("conversions", 0)) engagement = float(row["metrics"]["engagementRate"]) conv_rate = (conversions / sessions * 100) if sessions > 0 else 0 devices.append( { "device": device, "sessions": sessions, "bounce_rate": round(bounce * 100, 2), "avg_duration": round(duration, 2), "conversion_rate": round(conv_rate, 2), "engagement_rate": round(engagement * 100, 2), } ) analysis = { "period": f"Last {days} days", "devices": devices, "recommendations": self._recommend_device_optimizations(devices), } return analysis def _generate_insights(self, metrics: Dict) -> List[str]: """Generate insights from metric comparisons.""" insights = [] for metric, data in metrics.items(): change_pct = data["change_percent"] if abs(change_pct) < 2: status = "stable" elif change_pct > 0: status = "improving" else: status = "declining" # Add insights for significant changes if abs(change_pct) >= 5: direction = "increased" if change_pct > 0 else "decreased" insights.append( f"{metric.replace('_', ' ').title()}: {direction} by {abs(change_pct):.1f}%" ) return insights def _recommend_source_optimizations(self, sources: List[Dict]) -> List[Dict]: """Generate recommendations for traffic source optimization.""" recommendations = [] if not sources: return recommendations # Find best performing source best_source = max(sources, key=lambda x: x["conversion_rate"]) recommendations.append( { "priority": "HIGH", "action": f"Scale {best_source['source']}/{best_source['medium']}", "reason": f"Highest conversion rate ({best_source['conversion_rate']}%)", "expected_impact": "Increase overall conversions by 20-30%", } ) # Find high-traffic low-conversion sources for source in sources[:5]: # Check top 5 if source["conversion_rate"] < 2.0 and source["sessions"] > 1000: recommendations.append( { "priority": "MEDIUM", "action": f"Optimize {source['source']}/{source['medium']}", "reason": f"High traffic ({source['sessions']} sessions) but low conversion ({source['conversion_rate']}%)", "expected_impact": "Potential conversion rate improvement of 50-100%", } ) return recommendations def _recommend_content_improvements(self, problem_pages: List[Dict]) -> List[Dict]: """Generate recommendations for content improvements.""" recommendations = [] if not problem_pages: recommendations.append( { "priority": "INFO", "action": "Content performing well", "reason": "No pages with critically high bounce rates", "expected_impact": "Continue monitoring", } ) return recommendations # Prioritize by traffic problem_pages.sort(key=lambda x: x["views"], reverse=True) for page in problem_pages[:3]: # Top 3 issues recommendations.append( { "priority": "HIGH", "action": f"Improve {page['path']}", "reason": f"{page['issue']} ({page['bounce_rate']}% bounce rate)", "expected_impact": "Reduce bounce rate by 20-30%", } ) return recommendations def _recommend_device_optimizations(self, devices: List[Dict]) -> List[Dict]: """Generate recommendations for device optimization.""" recommendations = [] if len(devices) < 2: return recommendations # Compare mobile vs desktop mobile = next((d for d in devices if d["device"] == "mobile"), None) desktop = next((d for d in devices if d["device"] == "desktop"), None) if mobile and desktop: conv_diff = ( (desktop["conversion_rate"] - mobile["conversion_rate"]) / desktop["conversion_rate"] * 100 ) if conv_diff > 30: # Desktop significantly better recommendations.append( { "priority": "CRITICAL", "action": "Mobile experience optimization", "reason": f"Mobile conversion rate {mobile['conversion_rate']}% vs desktop {desktop['conversion_rate']}%", "expected_impact": "Improve mobile conversion by 30-50%", } ) return recommendations def _diagnose_page_issue(self, bounce_rate: float, avg_duration: float) -> str: """Diagnose the issue with a high-bounce page.""" if bounce_rate > 0.7 and avg_duration < 30: return "Content mismatch - users leave quickly" elif bounce_rate > 0.6 and avg_duration > 60: return "Missing CTA - users read but don't act" elif bounce_rate > 0.6: return "High bounce - needs investigation" else: return "Performance issue" def main(): parser = argparse.ArgumentParser( description="Analyze Google Analytics data", formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument( "--analysis-type", choices=["overview", "sources", "content", "devices"], default="overview", help="Type of analysis to perform", ) parser.add_argument( "--days", type=int, default=30, help="Number of days to analyze (default: 30)" ) parser.add_argument( "--compare", action="store_true", help="Compare with previous period", ) parser.add_argument( "--output", help="Output file path (default: stdout)" ) args = parser.parse_args() try: analyzer = AnalyticsAnalyzer() # Run analysis if args.analysis_type == "overview" and args.compare: result = analyzer.compare_periods(current_days=args.days) elif args.analysis_type == "sources": result = analyzer.analyze_traffic_sources(days=args.days) elif args.analysis_type == "content": result = analyzer.analyze_content_performance(days=args.days) elif args.analysis_type == "devices": result = analyzer.analyze_device_performance(days=args.days) else: result = analyzer.compare_periods(current_days=args.days) # Format output output = json.dumps(result, indent=2) # Write output if args.output: with open(args.output, "w") as f: f.write(output) print(f"Analysis saved to {args.output}", file=sys.stderr) else: print(output) except Exception as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/analytics/google-analytics/scripts/analyze.py", "license": "MIT License", "lines": 384, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/analytics/google-analytics/scripts/ga_client.py
#!/usr/bin/env python3 """ Google Analytics 4 Data API Client Fetches analytics data from Google Analytics 4 using the Data API. Authentication uses service account credentials from environment variables. Usage: python ga_client.py --days 30 --metrics sessions,users python ga_client.py --start 2026-01-01 --end 2026-01-31 --dimensions country python ga_client.py --days 7 --metrics sessions --dimensions pagePath --limit 10 Environment Variables: GOOGLE_ANALYTICS_PROPERTY_ID: GA4 property ID (required) GOOGLE_APPLICATION_CREDENTIALS: Path to service account JSON (required) """ import os import sys import json import argparse from datetime import datetime, timedelta from typing import List, Dict, Optional try: from google.analytics.data_v1beta import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import ( DateRange, Dimension, Metric, RunReportRequest, OrderBy, FilterExpression, Filter, ) from dotenv import load_dotenv except ImportError as e: print(f"Error: Required package not installed: {e}", file=sys.stderr) print("Install with: pip install google-analytics-data python-dotenv", file=sys.stderr) sys.exit(1) class GoogleAnalyticsClient: """Client for interacting with Google Analytics 4 Data API.""" def __init__(self): """Initialize the client with credentials from environment.""" load_dotenv() # Load from .env file if present self.property_id = os.environ.get("GOOGLE_ANALYTICS_PROPERTY_ID") if not self.property_id: raise ValueError( "GOOGLE_ANALYTICS_PROPERTY_ID environment variable not set. " "Find your property ID in GA4: Admin > Property Settings" ) credentials_path = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS") if not credentials_path: raise ValueError( "GOOGLE_APPLICATION_CREDENTIALS environment variable not set. " "Set it to the path of your service account JSON file." ) if not os.path.exists(credentials_path): raise FileNotFoundError( f"Service account file not found: {credentials_path}" ) try: self.client = BetaAnalyticsDataClient() except Exception as e: raise RuntimeError( f"Failed to initialize Google Analytics client: {e}\n" "Verify your service account has access to the GA4 property." ) def run_report( self, start_date: str, end_date: str, metrics: List[str], dimensions: Optional[List[str]] = None, limit: int = 10, order_by: Optional[str] = None, filter_expression: Optional[str] = None, ) -> Dict: """ Run a report query against Google Analytics. Args: start_date: Start date (YYYY-MM-DD or 'NdaysAgo') end_date: End date (YYYY-MM-DD or 'today'/'yesterday') metrics: List of metric names (e.g., ['sessions', 'users']) dimensions: List of dimension names (e.g., ['country', 'city']) limit: Maximum number of rows to return order_by: Metric or dimension to sort by filter_expression: Filter to apply (dimension_name:value) Returns: Dictionary with report data and metadata """ # Build request request = RunReportRequest( property=f"properties/{self.property_id}", date_ranges=[DateRange(start_date=start_date, end_date=end_date)], metrics=[Metric(name=m) for m in metrics], dimensions=[Dimension(name=d) for d in (dimensions or [])], limit=limit, ) # Add ordering if order_by: desc = True if order_by.startswith("+"): desc = False order_by = order_by[1:] elif order_by.startswith("-"): order_by = order_by[1:] # Check if it's a metric or dimension if order_by in metrics: request.order_bys = [ OrderBy(metric=OrderBy.MetricOrderBy(metric_name=order_by), desc=desc) ] elif dimensions and order_by in dimensions: request.order_bys = [ OrderBy( dimension=OrderBy.DimensionOrderBy(dimension_name=order_by), desc=desc, ) ] # Add filter if filter_expression and ":" in filter_expression: field_name, value = filter_expression.split(":", 1) request.dimension_filter = FilterExpression( filter=Filter( field_name=field_name, string_filter=Filter.StringFilter(value=value), ) ) try: response = self.client.run_report(request) except Exception as e: raise RuntimeError(f"Failed to run report: {e}") # Parse response return self._parse_response(response) def _parse_response(self, response) -> Dict: """Parse API response into a structured dictionary.""" result = { "dimension_headers": [h.name for h in response.dimension_headers], "metric_headers": [ {"name": h.name, "type": h.type_.name} for h in response.metric_headers ], "rows": [], "row_count": response.row_count, "metadata": {}, } # Add totals if present if response.totals: result["totals"] = [ {"value": v.value} for v in response.totals[0].metric_values ] # Parse rows for row in response.rows: parsed_row = { "dimensions": {}, "metrics": {}, } # Dimension values for i, value in enumerate(row.dimension_values): dim_name = result["dimension_headers"][i] parsed_row["dimensions"][dim_name] = value.value # Metric values for i, value in enumerate(row.metric_values): metric_info = result["metric_headers"][i] metric_name = metric_info["name"] parsed_row["metrics"][metric_name] = value.value result["rows"].append(parsed_row) return result def parse_date_range(days: Optional[int], start: Optional[str], end: Optional[str]): """Parse date range arguments into start and end dates.""" if days: return f"{days}daysAgo", "yesterday" elif start and end: return start, end else: # Default to last 7 days return "7daysAgo", "yesterday" def main(): parser = argparse.ArgumentParser( description="Fetch Google Analytics 4 data", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: # Last 30 days of sessions and users python ga_client.py --days 30 --metrics sessions,users # Specific date range with dimensions python ga_client.py --start 2026-01-01 --end 2026-01-31 \\ --metrics sessions,bounceRate --dimensions country,city # Top pages by views python ga_client.py --days 7 --metrics screenPageViews \\ --dimensions pagePath --order-by screenPageViews --limit 20 # Filter by country python ga_client.py --days 30 --metrics sessions \\ --dimensions country --filter "country:United States" """, ) # Date range arguments date_group = parser.add_mutually_exclusive_group() date_group.add_argument( "--days", type=int, help="Number of days to look back (e.g., 30)" ) date_group.add_argument( "--start", help="Start date (YYYY-MM-DD or 'NdaysAgo')" ) parser.add_argument("--end", help="End date (YYYY-MM-DD or 'today'/'yesterday')") # Query arguments parser.add_argument( "--metrics", required=True, help="Comma-separated list of metrics (e.g., sessions,users,bounceRate)", ) parser.add_argument( "--dimensions", help="Comma-separated list of dimensions (e.g., country,city,deviceCategory)", ) parser.add_argument( "--limit", type=int, default=10, help="Maximum rows to return (default: 10)" ) parser.add_argument( "--order-by", help="Metric or dimension to sort by (prefix with - for desc, + for asc)", ) parser.add_argument( "--filter", help="Filter expression (e.g., 'country:United States')" ) # Output arguments parser.add_argument( "--format", choices=["json", "table"], default="json", help="Output format (default: json)", ) parser.add_argument( "--output", help="Output file path (default: stdout)" ) args = parser.parse_args() try: # Initialize client client = GoogleAnalyticsClient() # Parse date range start_date, end_date = parse_date_range(args.days, args.start, args.end) # Parse metrics and dimensions metrics = [m.strip() for m in args.metrics.split(",")] dimensions = ( [d.strip() for d in args.dimensions.split(",")] if args.dimensions else None ) # Run report result = client.run_report( start_date=start_date, end_date=end_date, metrics=metrics, dimensions=dimensions, limit=args.limit, order_by=args.order_by, filter_expression=args.filter, ) # Format output if args.format == "json": output = json.dumps(result, indent=2) else: # table format output = format_as_table(result) # Write output if args.output: with open(args.output, "w") as f: f.write(output) print(f"Report saved to {args.output}", file=sys.stderr) else: print(output) except Exception as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) def format_as_table(result: Dict) -> str: """Format result as a human-readable table.""" lines = [] # Header headers = result["dimension_headers"] + [m["name"] for m in result["metric_headers"]] lines.append(" | ".join(headers)) lines.append("-" * (len(" | ".join(headers)))) # Rows for row in result["rows"]: values = [] for dim in result["dimension_headers"]: values.append(row["dimensions"].get(dim, "")) for metric in result["metric_headers"]: values.append(row["metrics"].get(metric["name"], "")) lines.append(" | ".join(values)) # Totals if "totals" in result: lines.append("-" * (len(" | ".join(headers)))) total_values = ["TOTAL"] + [""] * (len(result["dimension_headers"]) - 1) total_values += [t["value"] for t in result["totals"]] lines.append(" | ".join(total_values)) lines.append("") lines.append(f"Total rows: {result['row_count']}") return "\n".join(lines) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/analytics/google-analytics/scripts/ga_client.py", "license": "MIT License", "lines": 291, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/development/task-execution-engine/scripts/task_manager.py
#!/usr/bin/env python3 """Markdown-based task manager for task-execution-engine. Manages tasks directly in markdown files using checkbox syntax: - [ ] uncompleted task - [x] completed task """ import argparse import json import re import sys from pathlib import Path from dataclasses import dataclass, field, asdict from typing import Optional @dataclass class Task: """Represents a task parsed from markdown.""" title: str status: str # pending, completed, failed priority: int = 5 phase: str = "implementation" dependencies: list = field(default_factory=list) files: list = field(default_factory=list) criteria: list = field(default_factory=list) criteria_status: list = field(default_factory=list) # True/False for each criterion line_number: int = 0 failure_reason: str = "" def parse_task_line(line: str) -> Optional[dict]: """Parse a task line like: - [ ] **Task Title** `priority:1` `phase:model`""" # Match checkbox task match = re.match(r'^- \[([ xX])\] \*\*(.+?)\*\*(.*)$', line.strip()) if not match: return None checkbox, title, rest = match.groups() status = "completed" if checkbox.lower() == 'x' else "pending" # Check for failure marker if "❌" in rest or "FAILED" in rest: status = "failed" # Parse inline attributes priority = 5 phase = "implementation" dependencies = [] # Extract priority priority_match = re.search(r'`priority:(\d+)`', rest) if priority_match: priority = int(priority_match.group(1)) # Extract phase phase_match = re.search(r'`phase:(\w+)`', rest) if phase_match: phase = phase_match.group(1) # Extract dependencies deps_match = re.search(r'`deps:([^`]+)`', rest) if deps_match: dependencies = [d.strip() for d in deps_match.group(1).split(',')] return { "title": title.strip(), "status": status, "priority": priority, "phase": phase, "dependencies": dependencies } def parse_tasks_from_markdown(content: str) -> list[Task]: """Parse all tasks from markdown content.""" lines = content.split('\n') tasks = [] current_task = None in_task_section = False for i, line in enumerate(lines): # Check if we're in the Implementation Tasks section if re.match(r'^##\s+Implementation\s+Tasks', line, re.IGNORECASE): in_task_section = True continue # Exit task section on next ## header if in_task_section and re.match(r'^##\s+[^#]', line) and 'Implementation' not in line: in_task_section = False continue if not in_task_section: continue # Parse main task line task_data = parse_task_line(line) if task_data: if current_task: tasks.append(current_task) current_task = Task( title=task_data["title"], status=task_data["status"], priority=task_data["priority"], phase=task_data["phase"], dependencies=task_data["dependencies"], line_number=i + 1 ) continue # Parse task details (indented lines under a task) if current_task and line.strip().startswith('- '): stripped = line.strip() # Files line if stripped.startswith('- files:'): files_str = stripped.replace('- files:', '').strip() current_task.files = [f.strip() for f in files_str.split(',') if f.strip()] # Criterion line (checkbox) elif re.match(r'^- \[([ xX])\] ', stripped): checkbox_match = re.match(r'^- \[([ xX])\] (.+)$', stripped) if checkbox_match: is_done = checkbox_match.group(1).lower() == 'x' criterion = checkbox_match.group(2).strip() current_task.criteria.append(criterion) current_task.criteria_status.append(is_done) # Failure reason elif stripped.startswith('- reason:') or stripped.startswith('- error:'): current_task.failure_reason = stripped.split(':', 1)[1].strip() # Don't forget the last task if current_task: tasks.append(current_task) return tasks def get_next_task(tasks: list[Task]) -> Optional[Task]: """Get the next task to execute based on priority and dependencies.""" completed_titles = {t.title for t in tasks if t.status == "completed"} # Find pending tasks with satisfied dependencies available = [] for task in tasks: if task.status != "pending": continue # Check dependencies deps_satisfied = all(dep in completed_titles for dep in task.dependencies) if deps_satisfied: available.append(task) if not available: return None # Sort by priority (lower number = higher priority) available.sort(key=lambda t: t.priority) return available[0] def update_task_status(content: str, task_title: str, new_status: str, reason: str = "") -> str: """Update a task's status in the markdown content.""" lines = content.split('\n') result = [] in_target_task = False task_indent = 0 for line in lines: # Check if this is the target task task_data = parse_task_line(line) if task_data and task_data["title"] == task_title: in_target_task = True task_indent = len(line) - len(line.lstrip()) # Update the checkbox if new_status == "completed": line = re.sub(r'^(\s*- )\[[ ]\]', r'\1[x]', line) # Add completion marker if not present if "✅" not in line: line = line.rstrip() + " ✅" elif new_status == "failed": line = re.sub(r'^(\s*- )\[[ ]\]', r'\1[x]', line) # Add failure marker if "❌" not in line: line = line.rstrip() + " ❌" elif new_status == "pending": line = re.sub(r'^(\s*- )\[[xX]\]', r'\1[ ]', line) # Remove markers line = line.replace(" ✅", "").replace(" ❌", "") result.append(line) continue # Check if we've moved to a different task if task_data and task_data["title"] != task_title: in_target_task = False # Update criteria checkboxes within the task if in_target_task and re.match(r'^\s*- \[[ xX]\] ', line): current_indent = len(line) - len(line.lstrip()) if current_indent > task_indent: if new_status == "completed": line = re.sub(r'^(\s*- )\[[ ]\]', r'\1[x]', line) elif new_status == "pending": line = re.sub(r'^(\s*- )\[[xX]\]', r'\1[ ]', line) result.append(line) # Add failure reason after the task line if failed if in_target_task and task_data and new_status == "failed" and reason: indent = " " * (task_indent // 2 + 1) # Check if next line already has a reason result.append(f"{indent}- reason: {reason}") in_target_task = False # Prevent adding reason multiple times return '\n'.join(result) def get_status_summary(tasks: list[Task]) -> dict: """Get a summary of task statuses.""" summary = { "total": len(tasks), "completed": 0, "pending": 0, "failed": 0, "blocked": 0 } completed_titles = {t.title for t in tasks if t.status == "completed"} for task in tasks: if task.status == "completed": summary["completed"] += 1 elif task.status == "failed": summary["failed"] += 1 elif task.status == "pending": # Check if blocked by dependencies deps_satisfied = all(dep in completed_titles for dep in task.dependencies) if deps_satisfied: summary["pending"] += 1 else: summary["blocked"] += 1 return summary def cmd_next(args): """Get the next task to execute.""" content = Path(args.file).read_text() tasks = parse_tasks_from_markdown(content) next_task = get_next_task(tasks) if args.json: if next_task: print(json.dumps({ "status": "found", "task": asdict(next_task) }, indent=2)) else: summary = get_status_summary(tasks) print(json.dumps({ "status": "no_tasks", "summary": summary, "message": "No pending tasks available" }, indent=2)) else: if next_task: print(f"Next task: {next_task.title}") print(f"Priority: {next_task.priority} | Phase: {next_task.phase}") if next_task.files: print(f"Files: {', '.join(next_task.files)}") if next_task.criteria: print("Criteria:") for c in next_task.criteria: print(f" - {c}") else: print("No pending tasks available") def cmd_done(args): """Mark a task as completed.""" file_path = Path(args.file) content = file_path.read_text() updated = update_task_status(content, args.task, "completed") file_path.write_text(updated) if args.json: print(json.dumps({"status": "success", "task": args.task, "new_status": "completed"})) else: print(f"✅ Marked '{args.task}' as completed") def cmd_fail(args): """Mark a task as failed.""" file_path = Path(args.file) content = file_path.read_text() updated = update_task_status(content, args.task, "failed", args.reason or "") file_path.write_text(updated) if args.json: print(json.dumps({"status": "success", "task": args.task, "new_status": "failed", "reason": args.reason})) else: print(f"❌ Marked '{args.task}' as failed") if args.reason: print(f" Reason: {args.reason}") def cmd_status(args): """Show status summary.""" content = Path(args.file).read_text() tasks = parse_tasks_from_markdown(content) summary = get_status_summary(tasks) if args.json: print(json.dumps({ "file": args.file, "summary": summary, "tasks": [asdict(t) for t in tasks] }, indent=2)) else: total = summary["total"] completed = summary["completed"] pct = round(completed / total * 100, 1) if total > 0 else 0 print(f"File: {args.file}") print(f"Progress: {completed}/{total} ({pct}%)") print() print(f" Completed: {summary['completed']}") print(f" Pending: {summary['pending']}") print(f" Blocked: {summary['blocked']}") print(f" Failed: {summary['failed']}") # Show next task next_task = get_next_task(tasks) if next_task: print(f"\nNext: {next_task.title}") def cmd_list(args): """List all tasks.""" content = Path(args.file).read_text() tasks = parse_tasks_from_markdown(content) if args.json: print(json.dumps([asdict(t) for t in tasks], indent=2)) else: for task in tasks: status_icon = {"completed": "✅", "failed": "❌", "pending": "⬜"}.get(task.status, "?") print(f"{status_icon} [{task.priority}] {task.title}") def main(): parser = argparse.ArgumentParser(description="Markdown task manager") subparsers = parser.add_subparsers(dest="command", required=True) # next command next_parser = subparsers.add_parser("next", help="Get next task") next_parser.add_argument("--file", required=True, help="Markdown file path") next_parser.add_argument("--json", action="store_true", help="Output as JSON") next_parser.set_defaults(func=cmd_next) # done command done_parser = subparsers.add_parser("done", help="Mark task as completed") done_parser.add_argument("--file", required=True, help="Markdown file path") done_parser.add_argument("--task", required=True, help="Task title") done_parser.add_argument("--json", action="store_true", help="Output as JSON") done_parser.set_defaults(func=cmd_done) # fail command fail_parser = subparsers.add_parser("fail", help="Mark task as failed") fail_parser.add_argument("--file", required=True, help="Markdown file path") fail_parser.add_argument("--task", required=True, help="Task title") fail_parser.add_argument("--reason", default="", help="Failure reason") fail_parser.add_argument("--json", action="store_true", help="Output as JSON") fail_parser.set_defaults(func=cmd_fail) # status command status_parser = subparsers.add_parser("status", help="Show status summary") status_parser.add_argument("--file", required=True, help="Markdown file path") status_parser.add_argument("--json", action="store_true", help="Output as JSON") status_parser.set_defaults(func=cmd_status) # list command list_parser = subparsers.add_parser("list", help="List all tasks") list_parser.add_argument("--file", required=True, help="Markdown file path") list_parser.add_argument("--json", action="store_true", help="Output as JSON") list_parser.set_defaults(func=cmd_list) args = parser.parse_args() try: args.func(args) except FileNotFoundError: print(f"Error: File not found: {args.file}", file=sys.stderr) sys.exit(1) except Exception as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/development/task-execution-engine/scripts/task_manager.py", "license": "MIT License", "lines": 331, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/ai-research/post-training-grpo-rl-training/examples/reward_functions_library.py
""" GRPO Reward Functions Library =============================== A collection of battle-tested reward functions for common GRPO training scenarios. Copy and adapt these for your specific use case. Categories: - Correctness rewards (verifiable tasks) - Format rewards (structured output) - Length rewards (verbosity control) - Style rewards (quality and tone) - Combined rewards (multi-objective) """ import re from typing import List, Any # ==================== CORRECTNESS REWARDS ==================== def exact_match_reward(prompts, completions, answer, **kwargs) -> List[float]: """ Binary reward for exact answer match. Use for: Math problems, factual Q&A, code output Weight: 2.0 (highest priority) """ responses = [comp[0]['content'] for comp in completions] extracted = [extract_answer(r) for r in responses] return [2.0 if ans.strip() == gt.strip() else 0.0 for ans, gt in zip(extracted, answer)] def fuzzy_match_reward(prompts, completions, answer, **kwargs) -> List[float]: """ Partial credit for similar answers. Use for: Open-ended answers, summaries Weight: 1.0 """ from difflib import SequenceMatcher responses = [comp[0]['content'] for comp in completions] extracted = [extract_answer(r) for r in responses] rewards = [] for ans, gt in zip(extracted, answer): similarity = SequenceMatcher(None, ans.lower(), gt.lower()).ratio() rewards.append(similarity) return rewards def numeric_correctness_reward(prompts, completions, answer, tolerance=0.01, **kwargs) -> List[float]: """ Reward numeric answers within tolerance. Use for: Math, physics, engineering problems Weight: 2.0 """ responses = [comp[0]['content'] for comp in completions] extracted = [extract_answer(r) for r in responses] rewards = [] for ans, gt in zip(extracted, answer): try: ans_num = float(ans.replace(',', '')) gt_num = float(gt.replace(',', '')) if abs(ans_num - gt_num) / max(abs(gt_num), 1e-8) <= tolerance: rewards.append(2.0) else: rewards.append(0.0) except: rewards.append(0.0) return rewards def code_execution_reward(prompts, completions, test_cases, **kwargs) -> List[float]: """ Execute code and verify against test cases. Use for: Code generation tasks Weight: 2.0 """ responses = [comp[0]['content'] for comp in completions] extracted_code = [extract_code_block(r) for r in responses] rewards = [] for code in extracted_code: try: # Execute code (sandboxed!) passed = run_test_cases(code, test_cases) rewards.append(2.0 if passed else 0.0) except: rewards.append(0.0) return rewards # ==================== FORMAT REWARDS ==================== def strict_xml_format_reward(completions, **kwargs) -> List[float]: """ Strict XML format: exact newlines and spacing. Use for: When format must be EXACTLY specified Weight: 0.5 """ pattern = r'^<reasoning>\n.*?\n</reasoning>\n<answer>\n.*?\n</answer>\n$' responses = [comp[0]['content'] for comp in completions] matches = [re.match(pattern, r, re.DOTALL) for r in responses] return [0.5 if match else 0.0 for match in matches] def soft_xml_format_reward(completions, **kwargs) -> List[float]: """ Relaxed XML format: allows whitespace variations. Use for: When structure matters more than exact spacing Weight: 0.5 """ pattern = r'<reasoning>.*?</reasoning>\s*<answer>.*?</answer>' responses = [comp[0]['content'] for comp in completions] matches = [re.search(pattern, r, re.DOTALL) for r in responses] return [0.5 if match else 0.0 for match in matches] def json_format_reward(completions, **kwargs) -> List[float]: """ Reward valid JSON output. Use for: Structured data extraction, API responses Weight: 0.5 """ import json responses = [comp[0]['content'] for comp in completions] rewards = [] for r in responses: try: json.loads(r) rewards.append(0.5) except: rewards.append(0.0) return rewards def incremental_format_reward(completions, tags=['reasoning', 'answer'], **kwargs) -> List[float]: """ Partial credit for each required tag. Use for: Training models to gradually learn format Weight: sum(0.125 * num_tags * 2) = up to 0.5 for 2 tags """ responses = [comp[0]['content'] for comp in completions] rewards = [] for r in responses: score = 0.0 for tag in tags: if f'<{tag}>' in r: score += 0.125 if f'</{tag}>' in r: score += 0.125 # Penalize extra content after final closing tag if f'</{tags[-1]}>' in r: extra = r.split(f'</{tags[-1]}>')[-1].strip() score -= len(extra) * 0.001 rewards.append(score) return rewards # ==================== LENGTH REWARDS ==================== def ideal_length_reward(completions, ideal_tokens=100, **kwargs) -> List[float]: """ Reward responses near ideal length. Use for: Controlling verbosity Weight: 0.3 """ responses = [comp[0]['content'] for comp in completions] rewards = [] for r in responses: length = len(r.split()) distance = abs(length - ideal_tokens) # Gaussian-like reward peaking at ideal length reward = 0.3 * max(0, 1 - distance / ideal_tokens) rewards.append(reward) return rewards def min_length_reward(completions, min_tokens=50, **kwargs) -> List[float]: """ Penalize responses that are too short. Use for: Ensuring detailed explanations Weight: 0.2 """ responses = [comp[0]['content'] for comp in completions] rewards = [] for r in responses: length = len(r.split()) reward = 0.2 if length >= min_tokens else -0.2 rewards.append(reward) return rewards def max_length_penalty(completions, max_tokens=500, **kwargs) -> List[float]: """ Penalize excessively long responses. Use for: Preventing rambling Weight: -0.3 when violated """ responses = [comp[0]['content'] for comp in completions] rewards = [] for r in responses: length = len(r.split()) reward = -0.3 if length > max_tokens else 0.0 rewards.append(reward) return rewards # ==================== STYLE REWARDS ==================== def reasoning_quality_reward(completions, **kwargs) -> List[float]: """ Reward detailed reasoning with logical connectors. Use for: Improving chain-of-thought quality Weight: 0.3 """ logical_words = ['therefore', 'thus', 'because', 'since', 'consequently', 'first', 'second', 'next', 'finally', 'however'] responses = [comp[0]['content'] for comp in completions] rewards = [] for r in responses: reasoning = extract_xml_tag(r, 'reasoning').lower() # Count logical connectors count = sum(1 for word in logical_words if word in reasoning) # Normalize by length score = min(0.3, count * 0.05) rewards.append(score) return rewards def citation_reward(completions, **kwargs) -> List[float]: """ Reward responses with citations or references. Use for: Research tasks, fact-checking Weight: 0.2 """ citation_patterns = [ r'\[\d+\]', # [1], [2] r'\([A-Z][a-z]+,?\s+\d{4}\)', # (Smith, 2020) r'according to', r'as stated in', ] responses = [comp[0]['content'] for comp in completions] rewards = [] for r in responses: has_citation = any(re.search(pattern, r) for pattern in citation_patterns) rewards.append(0.2 if has_citation else 0.0) return rewards def no_repetition_penalty(completions, **kwargs) -> List[float]: """ Penalize repetitive text (same phrase repeated). Use for: Improving output diversity Weight: -0.3 when repetitive """ responses = [comp[0]['content'] for comp in completions] rewards = [] for r in responses: words = r.lower().split() # Check for repeated trigrams trigrams = [' '.join(words[i:i+3]) for i in range(len(words)-2)] unique_ratio = len(set(trigrams)) / max(len(trigrams), 1) reward = -0.3 if unique_ratio < 0.7 else 0.0 rewards.append(reward) return rewards # ==================== COMBINED REWARDS ==================== def math_problem_reward(prompts, completions, answer, **kwargs) -> List[float]: """ Combined reward for math problems: format + correctness. Automatically balances multiple objectives. Weight: 2.5 total """ format_rewards = soft_xml_format_reward(completions) correctness_rewards = exact_match_reward(prompts, completions, answer) return [f + c for f, c in zip(format_rewards, correctness_rewards)] def code_generation_reward(prompts, completions, test_cases, **kwargs) -> List[float]: """ Combined reward for code: format + execution + style. Weight: 2.7 total """ code_format_rewards = code_block_format_reward(completions) execution_rewards = code_execution_reward(prompts, completions, test_cases) no_error_rewards = no_syntax_error_reward(completions) return [f + e + s for f, e, s in zip(code_format_rewards, execution_rewards, no_error_rewards)] # ==================== HELPER FUNCTIONS ==================== def extract_answer(text: str) -> str: """Extract content from <answer> tags.""" return extract_xml_tag(text, 'answer') def extract_xml_tag(text: str, tag: str) -> str: """Generic XML tag extraction.""" pattern = f'<{tag}>(.*?)</{tag}>' match = re.search(pattern, text, re.DOTALL) return match.group(1).strip() if match else "" def extract_code_block(text: str) -> str: """Extract code from markdown code blocks.""" pattern = r'```(?:python)?\n(.*?)\n```' match = re.search(pattern, text, re.DOTALL) return match.group(1) if match else "" def run_test_cases(code: str, test_cases: List[tuple]) -> bool: """ Execute code with test cases (MUST be sandboxed in production!). Args: code: Python code string test_cases: List of (input, expected_output) tuples Returns: True if all tests pass """ # WARNING: This is a simplified example # In production, use proper sandboxing (e.g., docker, pypy sandbox) try: exec_globals = {} exec(code, exec_globals) for input_val, expected in test_cases: result = exec_globals['solution'](input_val) if result != expected: return False return True except: return False # ==================== REWARD FUNCTION PRESETS ==================== # Preset for math/reasoning tasks MATH_REASONING_REWARDS = [ incremental_format_reward, soft_xml_format_reward, exact_match_reward, reasoning_quality_reward, ] # Preset for code generation CODE_GENERATION_REWARDS = [ code_block_format_reward, code_execution_reward, no_syntax_error_reward, ] # Preset for summarization SUMMARIZATION_REWARDS = [ ideal_length_reward, fuzzy_match_reward, no_repetition_penalty, ] # Preset for Q&A QA_REWARDS = [ exact_match_reward, min_length_reward, citation_reward, ]
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/ai-research/post-training-grpo-rl-training/examples/reward_functions_library.py", "license": "MIT License", "lines": 309, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/ai-research/post-training-grpo-rl-training/templates/basic_grpo_training.py
""" Basic GRPO Training Template ============================= A minimal, production-ready template for GRPO training with TRL. Adapt this for your specific task by modifying: 1. Dataset loading (get_dataset function) 2. Reward functions (reward_*_func) 3. System prompt (SYSTEM_PROMPT) 4. Hyperparameters (GRPOConfig) """ import torch import re from datasets import load_dataset, Dataset from transformers import AutoModelForCausalLM, AutoTokenizer from peft import LoraConfig from trl import GRPOTrainer, GRPOConfig # ==================== CONFIGURATION ==================== MODEL_NAME = "Qwen/Qwen2.5-1.5B-Instruct" OUTPUT_DIR = "outputs/grpo-model" MAX_PROMPT_LENGTH = 256 MAX_COMPLETION_LENGTH = 512 SYSTEM_PROMPT = """ Respond in the following format: <reasoning> [Your step-by-step thinking] </reasoning> <answer> [Final answer] </answer> """ # ==================== DATASET ==================== def get_dataset(split="train"): """ Load and prepare your dataset. Returns: Dataset with columns: - 'prompt': List[Dict] with role/content - 'answer': str (ground truth, optional) """ # Example: GSM8K math dataset data = load_dataset('openai/gsm8k', 'main')[split] def process_example(x): # Extract ground truth answer answer = x['answer'].split('####')[1].strip() if '####' in x['answer'] else None return { 'prompt': [ {'role': 'system', 'content': SYSTEM_PROMPT}, {'role': 'user', 'content': x['question']} ], 'answer': answer } return data.map(process_example) # ==================== HELPER FUNCTIONS ==================== def extract_xml_tag(text: str, tag: str) -> str: """Extract content between XML tags.""" pattern = f'<{tag}>(.*?)</{tag}>' match = re.search(pattern, text, re.DOTALL) return match.group(1).strip() if match else "" def extract_answer(text: str) -> str: """Extract the final answer from structured output.""" return extract_xml_tag(text, 'answer') # ==================== REWARD FUNCTIONS ==================== def correctness_reward_func(prompts, completions, answer, **kwargs): """ Reward correct answers. Weight: 2.0 (highest priority) """ responses = [comp[0]['content'] for comp in completions] extracted = [extract_answer(r) for r in responses] return [2.0 if ans == gt else 0.0 for ans, gt in zip(extracted, answer)] def format_reward_func(completions, **kwargs): """ Reward proper XML format. Weight: 0.5 """ pattern = r'<reasoning>.*?</reasoning>\s*<answer>.*?</answer>' responses = [comp[0]['content'] for comp in completions] return [0.5 if re.search(pattern, r, re.DOTALL) else 0.0 for r in responses] def incremental_format_reward_func(completions, **kwargs): """ Incremental reward for partial format compliance. Weight: up to 0.5 """ responses = [comp[0]['content'] for comp in completions] rewards = [] for r in responses: score = 0.0 if '<reasoning>' in r: score += 0.125 if '</reasoning>' in r: score += 0.125 if '<answer>' in r: score += 0.125 if '</answer>' in r: score += 0.125 # Penalize extra content after closing tag if '</answer>' in r: extra = r.split('</answer>')[-1].strip() score -= len(extra) * 0.001 rewards.append(score) return rewards # ==================== MODEL SETUP ==================== def setup_model_and_tokenizer(): """Load model and tokenizer with optimizations.""" model = AutoModelForCausalLM.from_pretrained( MODEL_NAME, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2", device_map="auto" ) tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) tokenizer.pad_token = tokenizer.eos_token return model, tokenizer def get_peft_config(): """LoRA configuration for parameter-efficient training.""" return LoraConfig( r=16, lora_alpha=32, target_modules=[ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj" ], task_type="CAUSAL_LM", lora_dropout=0.05, ) # ==================== TRAINING ==================== def main(): """Main training function.""" # Load data print("Loading dataset...") dataset = get_dataset() print(f"Dataset size: {len(dataset)}") # Setup model print("Loading model...") model, tokenizer = setup_model_and_tokenizer() # Training configuration training_args = GRPOConfig( output_dir=OUTPUT_DIR, run_name="grpo-training", # Learning rate learning_rate=5e-6, adam_beta1=0.9, adam_beta2=0.99, weight_decay=0.1, warmup_ratio=0.1, lr_scheduler_type='cosine', # Batch settings per_device_train_batch_size=1, gradient_accumulation_steps=4, # GRPO specific num_generations=8, max_prompt_length=MAX_PROMPT_LENGTH, max_completion_length=MAX_COMPLETION_LENGTH, # Training duration num_train_epochs=1, # Optimization bf16=True, optim="adamw_8bit", max_grad_norm=0.1, # Logging logging_steps=1, save_steps=100, report_to="wandb", # Change to "none" to disable logging ) # Initialize trainer trainer = GRPOTrainer( model=model, processing_class=tokenizer, reward_funcs=[ incremental_format_reward_func, format_reward_func, correctness_reward_func, ], args=training_args, train_dataset=dataset, peft_config=get_peft_config(), ) # Train print("Starting training...") trainer.train() # Save final model print(f"Saving model to {OUTPUT_DIR}/final") trainer.save_model(f"{OUTPUT_DIR}/final") print("Training complete!") if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/ai-research/post-training-grpo-rl-training/templates/basic_grpo_training.py", "license": "MIT License", "lines": 185, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/productivity/nowait/scripts/nowait_processor.py
#!/usr/bin/env python3 """ NOWAIT Logit Processor Implements the NOWAIT technique for efficient reasoning by suppressing self-reflection tokens during inference. Reference: "Wait, We Don't Need to 'Wait'! Removing Thinking Tokens Improves Reasoning Efficiency" (Wang et al., 2025) Usage: from nowait_processor import NOWAITLogitProcessor processor = NOWAITLogitProcessor(tokenizer) outputs = model.generate(inputs, logits_processor=[processor]) """ import torch from typing import List, Set, Optional, Union from dataclasses import dataclass, field # Default reflection keywords from the paper (empirically derived from QwQ-32B) DEFAULT_KEYWORDS = [ "wait", "alternatively", "hmm", "but", "however", "alternative", "another", "check", "double-check", "oh", "maybe", "verify", "other", "again", "now", "ah", "any" ] # Keywords to exclude from suppression (false positives) EXCLUDED_PATTERNS = [ "ohio", # Contains "oh" "butane", # Contains "but" "button", # Contains "but" "butterfly", # Contains "but" ] @dataclass class NOWAITConfig: """Configuration for NOWAIT processor.""" keywords: List[str] = field(default_factory=lambda: DEFAULT_KEYWORDS.copy()) excluded_patterns: List[str] = field(default_factory=lambda: EXCLUDED_PATTERNS.copy()) negative_value: float = -1e10 case_sensitive: bool = False class NOWAITLogitProcessor: """ A logit processor that suppresses self-reflection tokens during generation. This processor identifies tokens associated with self-reflection keywords (e.g., "Wait", "Hmm", "Alternatively") and sets their logits to a large negative value, effectively preventing their generation. Args: tokenizer: The tokenizer for the target model config: Optional NOWAITConfig for customization keywords: Optional list of keywords to suppress (overrides config) Example: >>> from transformers import AutoTokenizer, AutoModelForCausalLM >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/QwQ-32B") >>> model = AutoModelForCausalLM.from_pretrained("Qwen/QwQ-32B") >>> processor = NOWAITLogitProcessor(tokenizer) >>> outputs = model.generate( ... input_ids, ... logits_processor=[processor], ... max_new_tokens=32768 ... ) """ def __init__( self, tokenizer, config: Optional[NOWAITConfig] = None, keywords: Optional[List[str]] = None ): self.tokenizer = tokenizer self.config = config or NOWAITConfig() if keywords is not None: self.config.keywords = keywords # Build the set of token IDs to suppress self.suppressed_token_ids: Set[int] = self._build_suppressed_tokens() def _is_excluded(self, token_text: str) -> bool: """Check if token text matches any excluded pattern.""" token_lower = token_text.lower() for pattern in self.config.excluded_patterns: if pattern in token_lower: return True return False def _build_suppressed_tokens(self) -> Set[int]: """ Build the set of token IDs to suppress based on keywords. This expands each keyword to all its variants in the vocabulary: - Different cases: "wait", "Wait", "WAIT" - With leading spaces: " wait", " Wait" - With punctuation: ".wait", ",wait" """ suppressed = set() vocab = self.tokenizer.get_vocab() for token_text, token_id in vocab.items(): # Skip excluded patterns if self._is_excluded(token_text): continue # Check if token contains any keyword token_check = token_text if self.config.case_sensitive else token_text.lower() for keyword in self.config.keywords: keyword_check = keyword if self.config.case_sensitive else keyword.lower() if keyword_check in token_check: suppressed.add(token_id) break return suppressed def __call__( self, input_ids: torch.LongTensor, scores: torch.FloatTensor ) -> torch.FloatTensor: """ Process logits by suppressing reflection tokens. Args: input_ids: Input token IDs (batch_size, seq_len) scores: Logit scores (batch_size, vocab_size) Returns: Modified scores with suppressed tokens set to negative infinity """ for token_id in self.suppressed_token_ids: if token_id < scores.shape[-1]: scores[:, token_id] = self.config.negative_value return scores def get_suppressed_count(self) -> int: """Return the number of tokens being suppressed.""" return len(self.suppressed_token_ids) def get_suppressed_tokens(self, limit: int = 50) -> List[str]: """Return sample of suppressed token texts for debugging.""" tokens = [] for token_id in list(self.suppressed_token_ids)[:limit]: try: token_text = self.tokenizer.decode([token_id]) tokens.append(f"{token_id}: '{token_text}'") except: tokens.append(f"{token_id}: <decode error>") return tokens def get_nowait_bad_words_ids( tokenizer, keywords: Optional[List[str]] = None, config: Optional[NOWAITConfig] = None ) -> List[List[int]]: """ Get bad_words_ids for use with vLLM or other frameworks. This returns the suppressed tokens in the format expected by frameworks that use bad_words_ids parameter. Args: tokenizer: The tokenizer for the target model keywords: Optional list of keywords to suppress config: Optional NOWAITConfig for customization Returns: List of token ID lists for bad_words_ids parameter Example: >>> from vllm import LLM, SamplingParams >>> llm = LLM(model="Qwen/QwQ-32B") >>> bad_words = get_nowait_bad_words_ids(llm.get_tokenizer()) >>> params = SamplingParams(bad_words_ids=bad_words) """ processor = NOWAITLogitProcessor(tokenizer, config=config, keywords=keywords) return [[token_id] for token_id in processor.suppressed_token_ids] def create_nowait_stopping_criteria( tokenizer, max_reflections: int = 0 ) -> "NOWAITStoppingCriteria": """ Create a stopping criteria that limits reflection occurrences. Alternative to logit suppression - allows some reflections but stops if too many are detected. Args: tokenizer: The tokenizer for the target model max_reflections: Maximum allowed reflection keywords (0 = none) Returns: StoppingCriteria instance """ return NOWAITStoppingCriteria(tokenizer, max_reflections) class NOWAITStoppingCriteria: """ Stopping criteria that monitors reflection keyword count. This is a softer alternative to complete suppression - it allows the model to use some reflection tokens but stops generation if the count exceeds a threshold. """ def __init__(self, tokenizer, max_reflections: int = 0): self.tokenizer = tokenizer self.max_reflections = max_reflections self.config = NOWAITConfig() self.reflection_count = 0 def __call__( self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs ) -> bool: """Check if generation should stop based on reflection count.""" # Decode latest token if input_ids.shape[1] > 0: latest_token = input_ids[0, -1].item() try: token_text = self.tokenizer.decode([latest_token]).lower() for keyword in self.config.keywords: if keyword.lower() in token_text: self.reflection_count += 1 break except: pass return self.reflection_count > self.max_reflections def reset(self): """Reset the reflection counter.""" self.reflection_count = 0 # Convenience function for quick setup def apply_nowait( model, tokenizer, prompt: str, max_new_tokens: int = 32768, temperature: float = 0.7, **generate_kwargs ) -> str: """ Convenience function to generate with NOWAIT applied. Args: model: The language model tokenizer: The tokenizer prompt: Input prompt max_new_tokens: Maximum tokens to generate temperature: Sampling temperature **generate_kwargs: Additional arguments for model.generate() Returns: Generated text with NOWAIT optimization applied Example: >>> response = apply_nowait(model, tokenizer, "Solve: 2+2=?") """ processor = NOWAITLogitProcessor(tokenizer) inputs = tokenizer(prompt, return_tensors="pt") if hasattr(model, "device"): inputs = {k: v.to(model.device) for k, v in inputs.items()} outputs = model.generate( **inputs, logits_processor=[processor], max_new_tokens=max_new_tokens, temperature=temperature, do_sample=temperature > 0, **generate_kwargs ) # Decode only the new tokens generated_ids = outputs[0][inputs["input_ids"].shape[1]:] return tokenizer.decode(generated_ids, skip_special_tokens=True) if __name__ == "__main__": # Demo/test mode print("NOWAIT Reasoning Optimizer") print("=" * 50) print(f"Default keywords: {DEFAULT_KEYWORDS}") print(f"Excluded patterns: {EXCLUDED_PATTERNS}") print() print("Usage example:") print(" from nowait_processor import NOWAITLogitProcessor") print(" processor = NOWAITLogitProcessor(tokenizer)") print(" model.generate(..., logits_processor=[processor])")
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/productivity/nowait/scripts/nowait_processor.py", "license": "MIT License", "lines": 248, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:scripts/generate_blog_images.py
#!/usr/bin/env python3 """ Generate blog cover images using Google AI (Imagen API). Reads blog articles from ../docs/blog/blog-articles.json and generates cover images for articles that don't have images in ../docs/blog/assets/ """ import os import sys import json import base64 import requests from pathlib import Path def check_google_api_key(): """Check for Google API key in environment.""" api_key = os.getenv('GOOGLE_API_KEY') if not api_key: # Try loading from .env file env_file = Path('.env') if env_file.exists(): with open(env_file, 'r') as f: for line in f: if line.startswith('GOOGLE_API_KEY='): api_key = line.split('=', 1)[1].strip().strip('"').strip("'") break if not api_key: print("❌ Error: GOOGLE_API_KEY not found!") print("\nPlease set the environment variable:") print("export GOOGLE_API_KEY=your-api-key-here") print("\nOr create a .env file with:") print("GOOGLE_API_KEY=your-api-key-here") sys.exit(1) return api_key def generate_blog_image(title, description, component_type, component_name, install_command, output_path, api_key): """ Generate a blog cover image using Google's Imagen API via AI Studio. Args: title: Article title description: Article description component_type: Type of component (Agent, MCP, Skill, etc.) component_name: Name of the component install_command: Installation command output_path: Path to save the generated image api_key: Google API key """ # Split install command into two lines for better readability if "--agent" in install_command: cmd_parts = install_command.split("--agent ") cmd_line1 = cmd_parts[0].strip() cmd_line2 = "--agent " + cmd_parts[1] elif "--mcp" in install_command: cmd_parts = install_command.split("--mcp ") cmd_line1 = cmd_parts[0].strip() cmd_line2 = "--mcp " + cmd_parts[1] elif "--skill" in install_command: cmd_parts = install_command.split("--skill ") cmd_line1 = cmd_parts[0].strip() cmd_line2 = "--skill " + cmd_parts[1] else: cmd_line1 = install_command cmd_line2 = "" # Simplify the command display to avoid text rendering issues # Show just the essential part if cmd_line2: simple_cmd = cmd_line2.strip() # Just show "--agent folder/name" etc else: simple_cmd = cmd_line1 # Create detailed prompt similar to supabase-claude-code-templates-cover.png prompt = f"""Create a professional blog cover image with this EXACT layout and text: LEFT SIDE (40% width): - Black background (#000000) - Text exactly as "CLAUDE CODE TEMPLATES" in pixelated/retro orange font (#F97316) - Font style: Bold, blocky, retro gaming aesthetic similar to arcade game fonts - Stacked vertically with equal spacing between words - Centered vertically on left side CENTER: - Vertical line divider in dark gray (#333333) 2px width - Full height of image from top to bottom RIGHT SIDE (60% width): - Black background (#000000) - At top: Small badge with text "{component_type}" in solid orange rectangle (#F97316) with rounded corners, black text inside - Below badge: Large bold white text saying "{component_name}" - At bottom: Small gray monospace text showing: "{simple_cmd}" CRITICAL TEXT RENDERING REQUIREMENTS: - All text must be perfectly readable and not corrupted - Use clear, legible fonts - Ensure proper spacing so text doesn't overlap or get cut off - The installation command at bottom should be clearly visible Overall specifications: - Exact dimensions: 1200x675 pixels (16:9 aspect ratio) - Background: Pure black (#000000) - Primary accent color: Orange (#F97316) - Text colors: White (#FFFFFF) for component name, Gray (#999999) for command - Minimalist, professional design - No decorative elements, gradients, or patterns - just text and divider - Clean, modern tech aesthetic similar to terminal/CLI interfaces The layout divides the image into two sections with a vertical line: left side shows "CLAUDE CODE TEMPLATES" in retro orange font, right side shows component type, name, and install command.""" print(f"🎨 Generating image for: {title}") print(f"📝 Prompt length: {len(prompt)} chars") # Google AI Nano Banana (gemini-2.5-flash-image) endpoint url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent" payload = { "contents": [ { "parts": [ { "text": prompt } ] } ] } headers = { "x-goog-api-key": api_key, "Content-Type": "application/json" } try: response = requests.post(url, headers=headers, json=payload) if response.status_code != 200: print(f"❌ API Error ({response.status_code}): {response.text}") return False result = response.json() # Extract image from Nano Banana response if "candidates" in result and len(result["candidates"]) > 0: candidate = result["candidates"][0] if "content" in candidate and "parts" in candidate["content"]: parts = candidate["content"]["parts"] # Find the inline data part with the image for part in parts: if "inlineData" in part: inline_data = part["inlineData"] # Extract base64 data if "data" in inline_data: image_data = base64.b64decode(inline_data["data"]) # Save image with open(output_path, 'wb') as f: f.write(image_data) print(f"✅ Image saved to: {output_path}") return True print(f"⚠️ No inline data found in response parts") return False else: print(f"⚠️ Unexpected response structure: {result}") return False else: print(f"❌ No candidates in response: {result}") return False except Exception as e: print(f"❌ Error generating image: {e}") return False def main(): """Main function to generate blog images.""" # Get Google API key api_key = check_google_api_key() # Load blog articles blog_json_path = Path(__file__).parent.parent / "docs" / "blog" / "blog-articles.json" if not blog_json_path.exists(): print(f"❌ Error: Blog articles file not found: {blog_json_path}") sys.exit(1) with open(blog_json_path, 'r') as f: data = json.load(f) articles = data.get("articles", []) assets_dir = blog_json_path.parent / "assets" # Create assets directory if it doesn't exist assets_dir.mkdir(exist_ok=True) print(f"\n📚 Found {len(articles)} articles") print(f"📁 Assets directory: {assets_dir}\n") # Filter articles that need images generated (hosted on aitmpl.com/blog/assets/) articles_needing_images = [] for article in articles: image_url = article.get("image", "") if "aitmpl.com/blog/assets/" in image_url and "-cover.png" in image_url: # Extract filename from URL filename = image_url.split("/")[-1] output_path = assets_dir / filename if not output_path.exists(): articles_needing_images.append({ "article": article, "filename": filename, "output_path": output_path }) else: print(f"⏭️ Skipping {filename} (already exists)") if not articles_needing_images: print("\n✅ All blog images already exist!") return print(f"\n🎨 Generating {len(articles_needing_images)} images...\n") # Generate images success_count = 0 for item in articles_needing_images: article = item["article"] filename = item["filename"] output_path = item["output_path"] # Extract component information from article ID article_id = article.get("id", "") # Determine component type and name based on article category category = article.get("category", "") if "agent" in article_id.lower() or category == "Agents": component_type = "AGENT" # Extract agent name from ID (e.g., frontend-developer-agent -> frontend-developer) agent_name = article_id.replace("-agent", "") component_name = agent_name.replace("-", " ").title() # Find actual agent path in components/agents/ import subprocess try: result = subprocess.run( ["find", "cli-tool/components/agents", "-name", f"{agent_name}.md", "-type", "f"], capture_output=True, text=True ) agent_path = result.stdout.strip() if agent_path: # Extract folder/name from path (e.g., development-team/frontend-developer) parts = agent_path.split("/agents/")[1].replace(".md", "") install_command = f"npx claude-code-templates@latest --agent {parts}" else: install_command = f"npx claude-code-templates@latest --agent {agent_name}" except: install_command = f"npx claude-code-templates@latest --agent {agent_name}" elif "mcp" in article_id.lower() or category == "MCP": component_type = "MCP" component_name = article_id.replace("-mcp", "").replace("-", " ").title() install_command = f"npx claude-code-templates@latest --mcp {article_id.replace('-mcp', '')}" elif "skill" in article_id.lower() or category == "Skills": component_type = "SKILL" component_name = article_id.replace("-skill", "").replace("-", " ").title() install_command = f"npx claude-code-templates@latest --skill {article_id}" elif "sandbox" in article_id.lower() or "e2b" in article_id.lower(): component_type = "SANDBOX" component_name = article_id.replace("-", " ").title() install_command = f"npx claude-code-templates@latest --sandbox e2b" else: component_type = "COMPONENT" component_name = article_id.replace("-", " ").title() install_command = f"npx claude-code-templates@latest" print(f"\n{'='*60}") print(f"📄 Article: {article['title']}") print(f"🏷️ Type: {component_type}") print(f"📦 Component: {component_name}") print(f"💻 Command: {install_command}") print(f"💾 Output: {filename}") print(f"{'='*60}\n") success = generate_blog_image( title=article["title"], description=article["description"], component_type=component_type, component_name=component_name, install_command=install_command, output_path=str(output_path), api_key=api_key ) if success: success_count += 1 print() # Extra newline for readability print(f"\n{'='*60}") print(f"✅ Successfully generated {success_count}/{len(articles_needing_images)} images") print(f"{'='*60}\n") if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "scripts/generate_blog_images.py", "license": "MIT License", "lines": 258, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:scripts/generate_blog_images_v2.py
#!/usr/bin/env python3 """ Script to generate blog images using Google Gemini 2.5 Flash Image (nano banana) Generates banners and workflow diagrams for Claude Code component blogs """ import os import base64 from pathlib import Path from dotenv import load_dotenv from google import genai # Load environment variables from .env file load_dotenv(Path(__file__).parent.parent / '.env') # Configuration API_KEY = os.environ.get("GOOGLE_API_KEY") if not API_KEY: raise ValueError("GOOGLE_API_KEY not found in environment variables. Check your .env file.") OUTPUT_DIR = Path(__file__).parent.parent / "docs/blog/assets" MODEL = "gemini-2.0-flash-exp-image-generation" # Using Gemini 2.0 Flash Exp with image generation # Blog definitions with prompts BLOGS = [ { "id": "frontend-developer-agent", "title": "Claude Code Frontend Developer Agent: Complete 2025 Tutorial", "banner_prompt": """Create a professional tech banner image with these elements: - Dark terminal/coding background with subtle grid pattern - Text overlay in bright green monospace font: 'Frontend Developer Agent' - Subtitle in smaller text: 'Complete 2025 Tutorial - Claude Code' - Include subtle React, Vue, and Next.js logo icons in corners - Modern code editor aesthetic with syntax highlighting in background - Color scheme: Dark (#1a1a1a) with neon green (#00ff41) accents - Professional, clean, minimalist design - 1200x630 px banner format""", "diagram_prompt": """Create a simple technical flowchart diagram: Title: Frontend Agent Workflow Flow: User Input → Frontend Agent Analysis → Framework Detection (React/Vue/Next) → Code Generation → Component Creation → Testing → Output Style: Clean minimal flowchart with boxes and arrows Colors: Terminal theme with green text on dark background Professional documentation style""" } ] def create_output_dir(): """Create output directory if it doesn't exist""" os.makedirs(OUTPUT_DIR, exist_ok=True) print(f"✓ Output directory ready: {OUTPUT_DIR}") def generate_image_with_gemini(prompt, output_path): """Generate image using Gemini with native image generation""" try: client = genai.Client(api_key=API_KEY) print(f" Generating with {MODEL}...") # Use generate_content for Gemini models with image generation response = client.models.generate_content( model=MODEL, contents=prompt ) # The response should contain image data if hasattr(response, 'parts') and response.parts: for part in response.parts: if hasattr(part, 'inline_data') and part.inline_data: # Save the image with open(output_path, 'wb') as f: f.write(part.inline_data.data) print(f" ✓ Saved: {output_path}") return True print(f" ✗ No image data in response") print(f" Response: {response}") return False except Exception as e: print(f" ✗ Error: {str(e)}") return False def test_single_image(): """Test with a single image first""" create_output_dir() blog = BLOGS[0] print(f"\n🎨 Testing image generation for: {blog['title']}\n") # Test banner banner_path = os.path.join(OUTPUT_DIR, f"{blog['id']}-cover-test.png") print("Testing Banner Generation:") success = generate_image_with_gemini(blog["banner_prompt"], banner_path) if success: print(f"\n✅ Success! Test image saved to: {banner_path}") else: print(f"\n❌ Failed to generate image. Check API key and model availability.") print(f"\nTip: The API key might need Imagen 4 enabled or use a different approach.") if __name__ == "__main__": test_single_image()
{ "repo_id": "davila7/claude-code-templates", "file_path": "scripts/generate_blog_images_v2.py", "license": "MIT License", "lines": 85, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/arboreto/scripts/basic_grn_inference.py
#!/usr/bin/env python3 """ Basic GRN inference example using Arboreto. This script demonstrates the standard workflow for inferring gene regulatory networks from expression data using GRNBoost2. Usage: python basic_grn_inference.py <expression_file> <output_file> [--tf-file TF_FILE] [--seed SEED] Arguments: expression_file: Path to expression matrix (TSV format, genes as columns) output_file: Path for output network (TSV format) --tf-file: Optional path to transcription factors file (one per line) --seed: Random seed for reproducibility (default: 777) """ import argparse import pandas as pd from arboreto.algo import grnboost2 from arboreto.utils import load_tf_names def run_grn_inference(expression_file, output_file, tf_file=None, seed=777): """ Run GRN inference using GRNBoost2. Args: expression_file: Path to expression matrix TSV file output_file: Path for output network file tf_file: Optional path to TF names file seed: Random seed for reproducibility """ print(f"Loading expression data from {expression_file}...") expression_data = pd.read_csv(expression_file, sep='\t') print(f"Expression matrix shape: {expression_data.shape}") print(f"Number of genes: {expression_data.shape[1]}") print(f"Number of observations: {expression_data.shape[0]}") # Load TF names if provided tf_names = 'all' if tf_file: print(f"Loading transcription factors from {tf_file}...") tf_names = load_tf_names(tf_file) print(f"Number of TFs: {len(tf_names)}") # Run GRN inference print(f"Running GRNBoost2 with seed={seed}...") network = grnboost2( expression_data=expression_data, tf_names=tf_names, seed=seed, verbose=True ) # Save results print(f"Saving network to {output_file}...") network.to_csv(output_file, sep='\t', index=False, header=False) print(f"Done! Network contains {len(network)} regulatory links.") print(f"\nTop 10 regulatory links:") print(network.head(10).to_string(index=False)) if __name__ == '__main__': parser = argparse.ArgumentParser( description='Infer gene regulatory network using GRNBoost2' ) parser.add_argument( 'expression_file', help='Path to expression matrix (TSV format, genes as columns)' ) parser.add_argument( 'output_file', help='Path for output network (TSV format)' ) parser.add_argument( '--tf-file', help='Path to transcription factors file (one per line)', default=None ) parser.add_argument( '--seed', help='Random seed for reproducibility (default: 777)', type=int, default=777 ) args = parser.parse_args() run_grn_inference( expression_file=args.expression_file, output_file=args.output_file, tf_file=args.tf_file, seed=args.seed )
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/arboreto/scripts/basic_grn_inference.py", "license": "MIT License", "lines": 81, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
davila7/claude-code-templates:cli-tool/components/skills/scientific/biomni/scripts/generate_report.py
#!/usr/bin/env python3 """ Enhanced PDF report generation for biomni conversation histories. This script provides additional customization options for biomni reports: - Custom styling and branding - Formatted code blocks - Section organization - Metadata inclusion - Export format options (PDF, HTML, Markdown) Usage: python generate_report.py --input conversation.json --output report.pdf python generate_report.py --agent-object agent --output report.pdf --format html """ import argparse import json from pathlib import Path from typing import Dict, List, Optional, Any from datetime import datetime def format_conversation_history( messages: List[Dict[str, Any]], include_metadata: bool = True, include_code: bool = True, include_timestamps: bool = False ) -> str: """ Format conversation history into structured markdown. Args: messages: List of conversation message dictionaries include_metadata: Include metadata section include_code: Include code blocks include_timestamps: Include message timestamps Returns: Formatted markdown string """ sections = [] # Header sections.append("# Biomni Analysis Report\n") # Metadata if include_metadata: sections.append("## Metadata\n") sections.append(f"- **Generated**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") sections.append(f"- **Number of interactions**: {len(messages)}") sections.append("\n---\n") # Process messages sections.append("## Analysis\n") for i, msg in enumerate(messages, 1): role = msg.get('role', 'unknown') content = msg.get('content', '') if role == 'user': sections.append(f"### Task {i // 2 + 1}\n") sections.append(f"**Query:**\n```\n{content}\n```\n") elif role == 'assistant': sections.append(f"**Response:**\n") # Check if content contains code if include_code and ('```' in content or 'import ' in content): # Attempt to separate text and code parts = content.split('```') for j, part in enumerate(parts): if j % 2 == 0: # Text content if part.strip(): sections.append(f"{part.strip()}\n") else: # Code content # Check if language is specified lines = part.split('\n', 1) if len(lines) > 1 and lines[0].strip() in ['python', 'r', 'bash', 'sql']: lang = lines[0].strip() code = lines[1] else: lang = 'python' # Default to python code = part sections.append(f"```{lang}\n{code}\n```\n") else: sections.append(f"{content}\n") sections.append("\n---\n") return '\n'.join(sections) def markdown_to_html(markdown_content: str, title: str = "Biomni Report") -> str: """ Convert markdown to styled HTML. Args: markdown_content: Markdown string title: HTML page title Returns: HTML string """ # Simple markdown to HTML conversion # For production use, consider using a library like markdown or mistune html_template = f""" <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{title}</title> <style> body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; line-height: 1.6; max-width: 900px; margin: 0 auto; padding: 20px; color: #333; }} h1 {{ color: #2c3e50; border-bottom: 3px solid #3498db; padding-bottom: 10px; }} h2 {{ color: #34495e; margin-top: 30px; border-bottom: 2px solid #95a5a6; padding-bottom: 5px; }} h3 {{ color: #555; }} code {{ background-color: #f4f4f4; padding: 2px 6px; border-radius: 3px; font-family: 'Monaco', 'Menlo', 'Courier New', monospace; }} pre {{ background-color: #f8f8f8; border: 1px solid #ddd; border-radius: 5px; padding: 15px; overflow-x: auto; }} pre code {{ background-color: transparent; padding: 0; }} hr {{ border: none; border-top: 1px solid #ddd; margin: 30px 0; }} .metadata {{ background-color: #ecf0f1; padding: 15px; border-radius: 5px; margin-bottom: 20px; }} .task {{ background-color: #e8f4f8; padding: 10px; border-left: 4px solid #3498db; margin: 20px 0; }} .footer {{ margin-top: 50px; text-align: center; color: #7f8c8d; font-size: 0.9em; }} </style> </head> <body> <div class="content"> {markdown_to_html_simple(markdown_content)} </div> <div class="footer"> <p>Generated with Biomni | Stanford SNAP Lab</p> <p><a href="https://github.com/snap-stanford/biomni">github.com/snap-stanford/biomni</a></p> </div> </body> </html> """ return html_template def markdown_to_html_simple(md: str) -> str: """Simple markdown to HTML converter (basic implementation).""" lines = md.split('\n') html_lines = [] in_code_block = False in_list = False for line in lines: # Code blocks if line.startswith('```'): if in_code_block: html_lines.append('</code></pre>') in_code_block = False else: lang = line[3:].strip() html_lines.append(f'<pre><code class="language-{lang}">') in_code_block = True continue if in_code_block: html_lines.append(line) continue # Headers if line.startswith('# '): html_lines.append(f'<h1>{line[2:]}</h1>') elif line.startswith('## '): html_lines.append(f'<h2>{line[3:]}</h2>') elif line.startswith('### '): html_lines.append(f'<h3>{line[4:]}</h3>') # Lists elif line.startswith('- '): if not in_list: html_lines.append('<ul>') in_list = True html_lines.append(f'<li>{line[2:]}</li>') else: if in_list: html_lines.append('</ul>') in_list = False # Horizontal rule if line.strip() == '---': html_lines.append('<hr>') # Bold elif '**' in line: line = line.replace('**', '<strong>', 1).replace('**', '</strong>', 1) html_lines.append(f'<p>{line}</p>') # Regular paragraph elif line.strip(): html_lines.append(f'<p>{line}</p>') else: html_lines.append('<br>') if in_list: html_lines.append('</ul>') return '\n'.join(html_lines) def generate_report( conversation_data: Dict[str, Any], output_path: Path, format: str = 'markdown', title: Optional[str] = None ): """ Generate formatted report from conversation data. Args: conversation_data: Conversation history dictionary output_path: Output file path format: Output format ('markdown', 'html', or 'pdf') title: Report title """ messages = conversation_data.get('messages', []) if not title: title = f"Biomni Analysis - {datetime.now().strftime('%Y-%m-%d')}" # Generate markdown markdown_content = format_conversation_history(messages) if format == 'markdown': output_path.write_text(markdown_content) print(f"✓ Markdown report saved to {output_path}") elif format == 'html': html_content = markdown_to_html(markdown_content, title) output_path.write_text(html_content) print(f"✓ HTML report saved to {output_path}") elif format == 'pdf': # For PDF generation, we'd typically use a library like weasyprint or reportlab # This is a placeholder implementation print("PDF generation requires additional dependencies (weasyprint or reportlab)") print("Falling back to HTML format...") html_path = output_path.with_suffix('.html') html_content = markdown_to_html(markdown_content, title) html_path.write_text(html_content) print(f"✓ HTML report saved to {html_path}") print(" To convert to PDF:") print(f" 1. Install weasyprint: pip install weasyprint") print(f" 2. Run: weasyprint {html_path} {output_path}") else: raise ValueError(f"Unsupported format: {format}") def main(): """Main entry point for CLI usage.""" parser = argparse.ArgumentParser( description="Generate enhanced reports from biomni conversation histories" ) parser.add_argument( '--input', type=Path, required=True, help='Input conversation history JSON file' ) parser.add_argument( '--output', type=Path, required=True, help='Output report file path' ) parser.add_argument( '--format', choices=['markdown', 'html', 'pdf'], default='markdown', help='Output format (default: markdown)' ) parser.add_argument( '--title', type=str, help='Report title (optional)' ) args = parser.parse_args() # Load conversation data try: with open(args.input, 'r') as f: conversation_data = json.load(f) except FileNotFoundError: print(f"❌ Input file not found: {args.input}") return 1 except json.JSONDecodeError: print(f"❌ Invalid JSON in input file: {args.input}") return 1 # Generate report try: generate_report( conversation_data, args.output, format=args.format, title=args.title ) return 0 except Exception as e: print(f"❌ Error generating report: {e}") return 1 if __name__ == '__main__': import sys sys.exit(main())
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/biomni/scripts/generate_report.py", "license": "MIT License", "lines": 318, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/biomni/scripts/setup_environment.py
#!/usr/bin/env python3 """ Interactive setup script for biomni environment configuration. This script helps users set up: 1. Conda environment with required dependencies 2. API keys for LLM providers 3. Data lake directory configuration 4. MCP server setup (optional) Usage: python setup_environment.py """ import os import sys import subprocess from pathlib import Path from typing import Dict, Optional def check_conda_installed() -> bool: """Check if conda is available in the system.""" try: subprocess.run( ['conda', '--version'], capture_output=True, check=True ) return True except (subprocess.CalledProcessError, FileNotFoundError): return False def setup_conda_environment(): """Guide user through conda environment setup.""" print("\n=== Conda Environment Setup ===") if not check_conda_installed(): print("❌ Conda not found. Please install Miniconda or Anaconda:") print(" https://docs.conda.io/en/latest/miniconda.html") return False print("✓ Conda is installed") # Check if biomni_e1 environment exists result = subprocess.run( ['conda', 'env', 'list'], capture_output=True, text=True ) if 'biomni_e1' in result.stdout: print("✓ biomni_e1 environment already exists") return True print("\nCreating biomni_e1 conda environment...") print("This will install Python 3.10 and required dependencies.") response = input("Proceed? [y/N]: ").strip().lower() if response != 'y': print("Skipping conda environment setup") return False try: # Create conda environment subprocess.run( ['conda', 'create', '-n', 'biomni_e1', 'python=3.10', '-y'], check=True ) print("\n✓ Conda environment created successfully") print("\nTo activate: conda activate biomni_e1") print("Then install biomni: pip install biomni --upgrade") return True except subprocess.CalledProcessError as e: print(f"❌ Failed to create conda environment: {e}") return False def setup_api_keys() -> Dict[str, str]: """Interactive API key configuration.""" print("\n=== API Key Configuration ===") print("Biomni supports multiple LLM providers.") print("At minimum, configure one provider.") api_keys = {} # Anthropic (recommended) print("\n1. Anthropic Claude (Recommended)") print(" Get your API key from: https://console.anthropic.com/") anthropic_key = input(" Enter ANTHROPIC_API_KEY (or press Enter to skip): ").strip() if anthropic_key: api_keys['ANTHROPIC_API_KEY'] = anthropic_key # OpenAI print("\n2. OpenAI") print(" Get your API key from: https://platform.openai.com/api-keys") openai_key = input(" Enter OPENAI_API_KEY (or press Enter to skip): ").strip() if openai_key: api_keys['OPENAI_API_KEY'] = openai_key # Google Gemini print("\n3. Google Gemini") print(" Get your API key from: https://makersuite.google.com/app/apikey") google_key = input(" Enter GOOGLE_API_KEY (or press Enter to skip): ").strip() if google_key: api_keys['GOOGLE_API_KEY'] = google_key # Groq print("\n4. Groq") print(" Get your API key from: https://console.groq.com/keys") groq_key = input(" Enter GROQ_API_KEY (or press Enter to skip): ").strip() if groq_key: api_keys['GROQ_API_KEY'] = groq_key if not api_keys: print("\n⚠️ No API keys configured. You'll need at least one to use biomni.") return {} return api_keys def save_api_keys(api_keys: Dict[str, str], method: str = 'env_file'): """Save API keys using specified method.""" if method == 'env_file': env_file = Path.cwd() / '.env' # Read existing .env if present existing_vars = {} if env_file.exists(): with open(env_file, 'r') as f: for line in f: line = line.strip() if line and not line.startswith('#'): if '=' in line: key, val = line.split('=', 1) existing_vars[key.strip()] = val.strip() # Update with new keys existing_vars.update(api_keys) # Write to .env with open(env_file, 'w') as f: f.write("# Biomni API Keys\n") f.write(f"# Generated by setup_environment.py\n\n") for key, value in existing_vars.items(): f.write(f"{key}={value}\n") print(f"\n✓ API keys saved to {env_file}") print(" Keys will be loaded automatically when biomni runs in this directory") elif method == 'shell_export': shell_file = Path.home() / '.bashrc' # or .zshrc for zsh users print("\n📋 Add these lines to your shell configuration:") for key, value in api_keys.items(): print(f" export {key}=\"{value}\"") print(f"\nThen run: source {shell_file}") def setup_data_directory() -> Optional[Path]: """Configure biomni data lake directory.""" print("\n=== Data Lake Configuration ===") print("Biomni requires ~11GB for integrated biomedical databases.") default_path = Path.cwd() / 'biomni_data' print(f"\nDefault location: {default_path}") response = input("Use default location? [Y/n]: ").strip().lower() if response == 'n': custom_path = input("Enter custom path: ").strip() data_path = Path(custom_path).expanduser().resolve() else: data_path = default_path # Create directory if it doesn't exist data_path.mkdir(parents=True, exist_ok=True) print(f"\n✓ Data directory configured: {data_path}") print(" Data will be downloaded automatically on first use") return data_path def test_installation(data_path: Path): """Test biomni installation with a simple query.""" print("\n=== Installation Test ===") print("Testing biomni installation with a simple query...") response = input("Run test? [Y/n]: ").strip().lower() if response == 'n': print("Skipping test") return test_code = f''' import os from biomni.agent import A1 # Use environment variables for API keys agent = A1(path='{data_path}', llm='claude-sonnet-4-20250514') # Simple test query result = agent.go("What is the primary function of the TP53 gene?") print("Test result:", result) ''' test_file = Path('test_biomni.py') with open(test_file, 'w') as f: f.write(test_code) print(f"\nTest script created: {test_file}") print("Running test...") try: subprocess.run([sys.executable, str(test_file)], check=True) print("\n✓ Test completed successfully!") test_file.unlink() # Clean up test file except subprocess.CalledProcessError: print("\n❌ Test failed. Check your configuration.") print(f" Test script saved as {test_file} for debugging") def generate_example_script(data_path: Path): """Generate example usage script.""" example_code = f'''#!/usr/bin/env python3 """ Example biomni usage script This demonstrates basic biomni usage patterns. Modify this script for your research tasks. """ from biomni.agent import A1 # Initialize agent agent = A1( path='{data_path}', llm='claude-sonnet-4-20250514' # or your preferred LLM ) # Example 1: Simple gene query print("Example 1: Gene function query") result = agent.go(""" What are the main functions of the BRCA1 gene? Include information about: - Molecular function - Associated diseases - Protein interactions """) print(result) print("-" * 80) # Example 2: Data analysis print("\\nExample 2: GWAS analysis") result = agent.go(""" Explain how to analyze GWAS summary statistics for: 1. Identifying genome-wide significant variants 2. Mapping variants to genes 3. Pathway enrichment analysis """) print(result) # Save conversation history agent.save_conversation_history("example_results.pdf") print("\\nResults saved to example_results.pdf") ''' example_file = Path('example_biomni_usage.py') with open(example_file, 'w') as f: f.write(example_code) print(f"\n✓ Example script created: {example_file}") def main(): """Main setup workflow.""" print("=" * 60) print("Biomni Environment Setup") print("=" * 60) # Step 1: Conda environment conda_success = setup_conda_environment() if conda_success: print("\n⚠️ Remember to activate the environment:") print(" conda activate biomni_e1") print(" pip install biomni --upgrade") # Step 2: API keys api_keys = setup_api_keys() if api_keys: print("\nHow would you like to store API keys?") print("1. .env file (recommended, local to this directory)") print("2. Shell export (add to .bashrc/.zshrc)") choice = input("Choose [1/2]: ").strip() if choice == '2': save_api_keys(api_keys, method='shell_export') else: save_api_keys(api_keys, method='env_file') # Step 3: Data directory data_path = setup_data_directory() # Step 4: Generate example script if data_path: generate_example_script(data_path) # Step 5: Test installation (optional) if api_keys and data_path: test_installation(data_path) # Summary print("\n" + "=" * 60) print("Setup Complete!") print("=" * 60) if conda_success: print("✓ Conda environment: biomni_e1") if api_keys: print(f"✓ API keys configured: {', '.join(api_keys.keys())}") if data_path: print(f"✓ Data directory: {data_path}") print("\nNext steps:") if conda_success: print("1. conda activate biomni_e1") print("2. pip install biomni --upgrade") print("3. Run example_biomni_usage.py to test") else: print("1. Install conda/miniconda") print("2. Run this script again") print("\nFor documentation, see:") print(" - GitHub: https://github.com/snap-stanford/biomni") print(" - Paper: https://www.biorxiv.org/content/10.1101/2025.05.30.656746v1") if __name__ == "__main__": try: main() except KeyboardInterrupt: print("\n\nSetup interrupted by user") sys.exit(1) except Exception as e: print(f"\n❌ Error during setup: {e}") sys.exit(1)
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/biomni/scripts/setup_environment.py", "license": "MIT License", "lines": 275, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/biorxiv-database/scripts/biorxiv_search.py
#!/usr/bin/env python3 """ bioRxiv Search Tool A comprehensive Python tool for searching and retrieving preprints from bioRxiv. Supports keyword search, author search, date filtering, category filtering, and more. Note: This tool is focused exclusively on bioRxiv (life sciences preprints). """ import requests import json import argparse from datetime import datetime, timedelta from typing import List, Dict, Optional, Any import time import sys from urllib.parse import quote class BioRxivSearcher: """Efficient search interface for bioRxiv preprints.""" BASE_URL = "https://api.biorxiv.org" # Valid bioRxiv categories CATEGORIES = [ "animal-behavior-and-cognition", "biochemistry", "bioengineering", "bioinformatics", "biophysics", "cancer-biology", "cell-biology", "clinical-trials", "developmental-biology", "ecology", "epidemiology", "evolutionary-biology", "genetics", "genomics", "immunology", "microbiology", "molecular-biology", "neuroscience", "paleontology", "pathology", "pharmacology-and-toxicology", "physiology", "plant-biology", "scientific-communication-and-education", "synthetic-biology", "systems-biology", "zoology" ] def __init__(self, verbose: bool = False): """Initialize the searcher.""" self.verbose = verbose self.session = requests.Session() self.session.headers.update({ 'User-Agent': 'BioRxiv-Search-Tool/1.0' }) def _log(self, message: str): """Print verbose logging messages.""" if self.verbose: print(f"[INFO] {message}", file=sys.stderr) def _make_request(self, endpoint: str, params: Optional[Dict] = None) -> Dict: """Make an API request with error handling and rate limiting.""" url = f"{self.BASE_URL}/{endpoint}" self._log(f"Requesting: {url}") try: response = self.session.get(url, params=params, timeout=30) response.raise_for_status() # Rate limiting - be respectful to the API time.sleep(0.5) return response.json() except requests.exceptions.RequestException as e: self._log(f"Error making request: {e}") return {"messages": [{"status": "error", "message": str(e)}], "collection": []} def search_by_date_range( self, start_date: str, end_date: str, category: Optional[str] = None ) -> List[Dict]: """ Search for preprints within a date range. Args: start_date: Start date in YYYY-MM-DD format end_date: End date in YYYY-MM-DD format category: Optional category filter (e.g., 'neuroscience') Returns: List of preprint dictionaries """ self._log(f"Searching bioRxiv from {start_date} to {end_date}") if category: endpoint = f"details/biorxiv/{start_date}/{end_date}/{category}" else: endpoint = f"details/biorxiv/{start_date}/{end_date}" data = self._make_request(endpoint) if "collection" in data: self._log(f"Found {len(data['collection'])} preprints") return data["collection"] return [] def search_by_interval( self, interval: str = "1", cursor: int = 0, format: str = "json" ) -> Dict: """ Retrieve preprints from a specific time interval. Args: interval: Number of days back to search cursor: Pagination cursor (0 for first page, then use returned cursor) format: Response format ('json' or 'xml') Returns: Dictionary with collection and pagination info """ endpoint = f"pubs/biorxiv/{interval}/{cursor}/{format}" return self._make_request(endpoint) def get_paper_details(self, doi: str) -> Dict: """ Get detailed information about a specific paper by DOI. Args: doi: The DOI of the paper (e.g., '10.1101/2021.01.01.123456') Returns: Dictionary with paper details """ # Clean DOI if full URL was provided if 'doi.org' in doi: doi = doi.split('doi.org/')[-1] self._log(f"Fetching details for DOI: {doi}") endpoint = f"details/biorxiv/{doi}" data = self._make_request(endpoint) if "collection" in data and len(data["collection"]) > 0: return data["collection"][0] return {} def search_by_author( self, author_name: str, start_date: Optional[str] = None, end_date: Optional[str] = None ) -> List[Dict]: """ Search for papers by author name. Args: author_name: Author name to search for start_date: Optional start date (YYYY-MM-DD) end_date: Optional end date (YYYY-MM-DD) Returns: List of matching preprints """ # If no date range specified, search last 3 years if not start_date: end_date = datetime.now().strftime("%Y-%m-%d") start_date = (datetime.now() - timedelta(days=1095)).strftime("%Y-%m-%d") self._log(f"Searching for author: {author_name}") # Get all papers in date range papers = self.search_by_date_range(start_date, end_date) # Filter by author name (case-insensitive) author_lower = author_name.lower() matching_papers = [] for paper in papers: authors = paper.get("authors", "") if author_lower in authors.lower(): matching_papers.append(paper) self._log(f"Found {len(matching_papers)} papers by {author_name}") return matching_papers def search_by_keywords( self, keywords: List[str], start_date: Optional[str] = None, end_date: Optional[str] = None, category: Optional[str] = None, search_fields: List[str] = ["title", "abstract"] ) -> List[Dict]: """ Search for papers containing specific keywords. Args: keywords: List of keywords to search for start_date: Optional start date (YYYY-MM-DD) end_date: Optional end date (YYYY-MM-DD) category: Optional category filter search_fields: Fields to search in (title, abstract, authors) Returns: List of matching preprints """ # If no date range specified, search last year if not start_date: end_date = datetime.now().strftime("%Y-%m-%d") start_date = (datetime.now() - timedelta(days=365)).strftime("%Y-%m-%d") self._log(f"Searching for keywords: {keywords}") # Get all papers in date range papers = self.search_by_date_range(start_date, end_date, category) # Filter by keywords matching_papers = [] keywords_lower = [k.lower() for k in keywords] for paper in papers: # Build search text from specified fields search_text = "" for field in search_fields: if field in paper: search_text += " " + str(paper[field]).lower() # Check if any keyword matches if any(keyword in search_text for keyword in keywords_lower): matching_papers.append(paper) self._log(f"Found {len(matching_papers)} papers matching keywords") return matching_papers def download_pdf(self, doi: str, output_path: str) -> bool: """ Download the PDF of a paper. Args: doi: The DOI of the paper output_path: Path where PDF should be saved Returns: True if download successful, False otherwise """ # Clean DOI if 'doi.org' in doi: doi = doi.split('doi.org/')[-1] # Construct PDF URL pdf_url = f"https://www.biorxiv.org/content/{doi}v1.full.pdf" self._log(f"Downloading PDF from: {pdf_url}") try: response = self.session.get(pdf_url, timeout=60) response.raise_for_status() with open(output_path, 'wb') as f: f.write(response.content) self._log(f"PDF saved to: {output_path}") return True except Exception as e: self._log(f"Error downloading PDF: {e}") return False def format_result(self, paper: Dict, include_abstract: bool = True) -> Dict: """ Format a paper result with standardized fields. Args: paper: Raw paper dictionary from API include_abstract: Whether to include the abstract Returns: Formatted paper dictionary """ result = { "doi": paper.get("doi", ""), "title": paper.get("title", ""), "authors": paper.get("authors", ""), "author_corresponding": paper.get("author_corresponding", ""), "author_corresponding_institution": paper.get("author_corresponding_institution", ""), "date": paper.get("date", ""), "version": paper.get("version", ""), "type": paper.get("type", ""), "license": paper.get("license", ""), "category": paper.get("category", ""), "jatsxml": paper.get("jatsxml", ""), "published": paper.get("published", "") } if include_abstract: result["abstract"] = paper.get("abstract", "") # Add PDF and HTML URLs if result["doi"]: result["pdf_url"] = f"https://www.biorxiv.org/content/{result['doi']}v{result['version']}.full.pdf" result["html_url"] = f"https://www.biorxiv.org/content/{result['doi']}v{result['version']}" return result def main(): """Command-line interface for bioRxiv search.""" parser = argparse.ArgumentParser( description="Search bioRxiv preprints efficiently", formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument("--verbose", "-v", action="store_true", help="Enable verbose logging") # Search type arguments search_group = parser.add_argument_group("Search options") search_group.add_argument("--keywords", "-k", nargs="+", help="Keywords to search for") search_group.add_argument("--author", "-a", help="Author name to search for") search_group.add_argument("--doi", help="Get details for specific DOI") # Date range arguments date_group = parser.add_argument_group("Date range options") date_group.add_argument("--start-date", help="Start date (YYYY-MM-DD)") date_group.add_argument("--end-date", help="End date (YYYY-MM-DD)") date_group.add_argument("--days-back", type=int, help="Search N days back from today") # Filter arguments filter_group = parser.add_argument_group("Filter options") filter_group.add_argument("--category", "-c", choices=BioRxivSearcher.CATEGORIES, help="Filter by category") filter_group.add_argument("--search-fields", nargs="+", default=["title", "abstract"], choices=["title", "abstract", "authors"], help="Fields to search in for keywords") # Output arguments output_group = parser.add_argument_group("Output options") output_group.add_argument("--output", "-o", help="Output file (default: stdout)") output_group.add_argument("--include-abstract", action="store_true", default=True, help="Include abstracts in output") output_group.add_argument("--download-pdf", help="Download PDF to specified path (requires --doi)") output_group.add_argument("--limit", type=int, help="Limit number of results") args = parser.parse_args() # Initialize searcher searcher = BioRxivSearcher(verbose=args.verbose) # Handle date range end_date = args.end_date or datetime.now().strftime("%Y-%m-%d") if args.days_back: start_date = (datetime.now() - timedelta(days=args.days_back)).strftime("%Y-%m-%d") else: start_date = args.start_date # Execute search based on arguments results = [] if args.download_pdf: if not args.doi: print("Error: --doi required with --download-pdf", file=sys.stderr) return 1 success = searcher.download_pdf(args.doi, args.download_pdf) return 0 if success else 1 elif args.doi: # Get specific paper by DOI paper = searcher.get_paper_details(args.doi) if paper: results = [paper] elif args.author: # Search by author results = searcher.search_by_author( args.author, start_date, end_date ) elif args.keywords: # Search by keywords if not start_date: print("Error: --start-date or --days-back required for keyword search", file=sys.stderr) return 1 results = searcher.search_by_keywords( args.keywords, start_date, end_date, args.category, args.search_fields ) else: # Date range search if not start_date: print("Error: Must specify search criteria (--keywords, --author, or --doi)", file=sys.stderr) return 1 results = searcher.search_by_date_range( start_date, end_date, args.category ) # Apply limit if args.limit: results = results[:args.limit] # Format results formatted_results = [ searcher.format_result(paper, args.include_abstract) for paper in results ] # Output results output_data = { "query": { "keywords": args.keywords, "author": args.author, "doi": args.doi, "start_date": start_date, "end_date": end_date, "category": args.category }, "result_count": len(formatted_results), "results": formatted_results } output_json = json.dumps(output_data, indent=2) if args.output: with open(args.output, 'w') as f: f.write(output_json) print(f"Results written to {args.output}", file=sys.stderr) else: print(output_json) return 0 if __name__ == "__main__": sys.exit(main())
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/biorxiv-database/scripts/biorxiv_search.py", "license": "MIT License", "lines": 358, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/bioservices/scripts/batch_id_converter.py
#!/usr/bin/env python3 """ Batch Identifier Converter This script converts multiple identifiers between biological databases using UniProt's mapping service. Supports batch processing with automatic chunking and error handling. Usage: python batch_id_converter.py INPUT_FILE --from DB1 --to DB2 [options] Examples: python batch_id_converter.py uniprot_ids.txt --from UniProtKB_AC-ID --to KEGG python batch_id_converter.py gene_ids.txt --from GeneID --to UniProtKB --output mapping.csv python batch_id_converter.py ids.txt --from UniProtKB_AC-ID --to Ensembl --chunk-size 50 Input file format: One identifier per line (plain text) Common database codes: UniProtKB_AC-ID - UniProt accession/ID KEGG - KEGG gene IDs GeneID - NCBI Gene (Entrez) IDs Ensembl - Ensembl gene IDs Ensembl_Protein - Ensembl protein IDs RefSeq_Protein - RefSeq protein IDs PDB - Protein Data Bank IDs HGNC - Human gene symbols GO - Gene Ontology IDs """ import sys import argparse import csv import time from bioservices import UniProt # Common database code mappings DATABASE_CODES = { 'uniprot': 'UniProtKB_AC-ID', 'uniprotkb': 'UniProtKB_AC-ID', 'kegg': 'KEGG', 'geneid': 'GeneID', 'entrez': 'GeneID', 'ensembl': 'Ensembl', 'ensembl_protein': 'Ensembl_Protein', 'ensembl_transcript': 'Ensembl_Transcript', 'refseq': 'RefSeq_Protein', 'refseq_protein': 'RefSeq_Protein', 'pdb': 'PDB', 'hgnc': 'HGNC', 'mgi': 'MGI', 'go': 'GO', 'pfam': 'Pfam', 'interpro': 'InterPro', 'reactome': 'Reactome', 'string': 'STRING', 'biogrid': 'BioGRID' } def normalize_database_code(code): """Normalize database code to official format.""" # Try exact match first if code in DATABASE_CODES.values(): return code # Try lowercase lookup lowercase = code.lower() if lowercase in DATABASE_CODES: return DATABASE_CODES[lowercase] # Return as-is if not found (may still be valid) return code def read_ids_from_file(filename): """Read identifiers from file (one per line).""" print(f"Reading identifiers from {filename}...") ids = [] with open(filename, 'r') as f: for line in f: line = line.strip() if line and not line.startswith('#'): ids.append(line) print(f"✓ Read {len(ids)} identifier(s)") return ids def batch_convert(ids, from_db, to_db, chunk_size=100, delay=0.5): """Convert IDs with automatic chunking and error handling.""" print(f"\nConverting {len(ids)} IDs:") print(f" From: {from_db}") print(f" To: {to_db}") print(f" Chunk size: {chunk_size}") print() u = UniProt(verbose=False) all_results = {} failed_ids = [] total_chunks = (len(ids) + chunk_size - 1) // chunk_size for i in range(0, len(ids), chunk_size): chunk = ids[i:i+chunk_size] chunk_num = (i // chunk_size) + 1 query = ",".join(chunk) try: print(f" [{chunk_num}/{total_chunks}] Processing {len(chunk)} IDs...", end=" ") results = u.mapping(fr=from_db, to=to_db, query=query) if results: all_results.update(results) mapped_count = len([v for v in results.values() if v]) print(f"✓ Mapped: {mapped_count}/{len(chunk)}") else: print(f"✗ No mappings returned") failed_ids.extend(chunk) # Rate limiting if delay > 0 and i + chunk_size < len(ids): time.sleep(delay) except Exception as e: print(f"✗ Error: {e}") # Try individual IDs in failed chunk print(f" Retrying individual IDs...") for single_id in chunk: try: result = u.mapping(fr=from_db, to=to_db, query=single_id) if result: all_results.update(result) print(f" ✓ {single_id}") else: failed_ids.append(single_id) print(f" ✗ {single_id} - no mapping") except Exception as e2: failed_ids.append(single_id) print(f" ✗ {single_id} - {e2}") time.sleep(0.2) # Add missing IDs to results (mark as failed) for id_ in ids: if id_ not in all_results: all_results[id_] = None print(f"\n✓ Conversion complete:") print(f" Total: {len(ids)}") print(f" Mapped: {len([v for v in all_results.values() if v])}") print(f" Failed: {len(failed_ids)}") return all_results, failed_ids def save_mapping_csv(mapping, output_file, from_db, to_db): """Save mapping results to CSV.""" print(f"\nSaving results to {output_file}...") with open(output_file, 'w', newline='') as f: writer = csv.writer(f) # Header writer.writerow(['Source_ID', 'Source_DB', 'Target_IDs', 'Target_DB', 'Mapping_Status']) # Data for source_id, target_ids in sorted(mapping.items()): if target_ids: target_str = ";".join(target_ids) status = "Success" else: target_str = "" status = "Failed" writer.writerow([source_id, from_db, target_str, to_db, status]) print(f"✓ Results saved") def save_failed_ids(failed_ids, output_file): """Save failed IDs to file.""" if not failed_ids: return print(f"\nSaving failed IDs to {output_file}...") with open(output_file, 'w') as f: for id_ in failed_ids: f.write(f"{id_}\n") print(f"✓ Saved {len(failed_ids)} failed ID(s)") def print_mapping_summary(mapping, from_db, to_db): """Print summary of mapping results.""" print(f"\n{'='*70}") print("MAPPING SUMMARY") print(f"{'='*70}") total = len(mapping) mapped = len([v for v in mapping.values() if v]) failed = total - mapped print(f"\nSource database: {from_db}") print(f"Target database: {to_db}") print(f"\nTotal identifiers: {total}") print(f"Successfully mapped: {mapped} ({mapped/total*100:.1f}%)") print(f"Failed to map: {failed} ({failed/total*100:.1f}%)") # Show some examples if mapped > 0: print(f"\nExample mappings (first 5):") count = 0 for source_id, target_ids in mapping.items(): if target_ids: target_str = ", ".join(target_ids[:3]) if len(target_ids) > 3: target_str += f" ... +{len(target_ids)-3} more" print(f" {source_id} → {target_str}") count += 1 if count >= 5: break # Show multiple mapping statistics multiple_mappings = [v for v in mapping.values() if v and len(v) > 1] if multiple_mappings: print(f"\nMultiple target mappings: {len(multiple_mappings)} ID(s)") print(f" (These source IDs map to multiple target IDs)") print(f"{'='*70}") def list_common_databases(): """Print list of common database codes.""" print("\nCommon Database Codes:") print("-" * 70) print(f"{'Alias':<20} {'Official Code':<30}") print("-" * 70) for alias, code in sorted(DATABASE_CODES.items()): if alias != code.lower(): print(f"{alias:<20} {code:<30}") print("-" * 70) print("\nNote: Many other database codes are supported.") print("See UniProt documentation for complete list.") def main(): """Main conversion workflow.""" parser = argparse.ArgumentParser( description="Batch convert biological identifiers between databases", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: python batch_id_converter.py uniprot_ids.txt --from UniProtKB_AC-ID --to KEGG python batch_id_converter.py ids.txt --from GeneID --to UniProtKB -o mapping.csv python batch_id_converter.py ids.txt --from uniprot --to ensembl --chunk-size 50 Common database codes: UniProtKB_AC-ID, KEGG, GeneID, Ensembl, Ensembl_Protein, RefSeq_Protein, PDB, HGNC, GO, Pfam, InterPro, Reactome Use --list-databases to see all supported aliases. """ ) parser.add_argument("input_file", help="Input file with IDs (one per line)") parser.add_argument("--from", dest="from_db", required=True, help="Source database code") parser.add_argument("--to", dest="to_db", required=True, help="Target database code") parser.add_argument("-o", "--output", default=None, help="Output CSV file (default: mapping_results.csv)") parser.add_argument("--chunk-size", type=int, default=100, help="Number of IDs per batch (default: 100)") parser.add_argument("--delay", type=float, default=0.5, help="Delay between batches in seconds (default: 0.5)") parser.add_argument("--save-failed", action="store_true", help="Save failed IDs to separate file") parser.add_argument("--list-databases", action="store_true", help="List common database codes and exit") args = parser.parse_args() # List databases and exit if args.list_databases: list_common_databases() sys.exit(0) print("=" * 70) print("BIOSERVICES: Batch Identifier Converter") print("=" * 70) # Normalize database codes from_db = normalize_database_code(args.from_db) to_db = normalize_database_code(args.to_db) if from_db != args.from_db: print(f"\nNote: Normalized '{args.from_db}' → '{from_db}'") if to_db != args.to_db: print(f"Note: Normalized '{args.to_db}' → '{to_db}'") # Read input IDs try: ids = read_ids_from_file(args.input_file) except Exception as e: print(f"\n✗ Error reading input file: {e}") sys.exit(1) if not ids: print("\n✗ No IDs found in input file") sys.exit(1) # Perform conversion mapping, failed_ids = batch_convert( ids, from_db, to_db, chunk_size=args.chunk_size, delay=args.delay ) # Print summary print_mapping_summary(mapping, from_db, to_db) # Save results output_file = args.output or "mapping_results.csv" save_mapping_csv(mapping, output_file, from_db, to_db) # Save failed IDs if requested if args.save_failed and failed_ids: failed_file = output_file.replace(".csv", "_failed.txt") save_failed_ids(failed_ids, failed_file) print(f"\n✓ Done!") if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/bioservices/scripts/batch_id_converter.py", "license": "MIT License", "lines": 273, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/bioservices/scripts/compound_cross_reference.py
#!/usr/bin/env python3 """ Compound Cross-Database Search This script searches for a compound by name and retrieves identifiers from multiple databases: - KEGG Compound - ChEBI - ChEMBL (via UniChem) - Basic compound properties Usage: python compound_cross_reference.py COMPOUND_NAME [--output FILE] Examples: python compound_cross_reference.py Geldanamycin python compound_cross_reference.py "Adenosine triphosphate" python compound_cross_reference.py Aspirin --output aspirin_info.txt """ import sys import argparse from bioservices import KEGG, UniChem, ChEBI, ChEMBL def search_kegg_compound(compound_name): """Search KEGG for compound by name.""" print(f"\n{'='*70}") print("STEP 1: KEGG Compound Search") print(f"{'='*70}") k = KEGG() print(f"Searching KEGG for: {compound_name}") try: results = k.find("compound", compound_name) if not results or not results.strip(): print(f"✗ No results found in KEGG") return k, None # Parse results lines = results.strip().split("\n") print(f"✓ Found {len(lines)} result(s):\n") for i, line in enumerate(lines[:5], 1): parts = line.split("\t") kegg_id = parts[0] description = parts[1] if len(parts) > 1 else "No description" print(f" {i}. {kegg_id}: {description}") # Use first result first_result = lines[0].split("\t") kegg_id = first_result[0].replace("cpd:", "") print(f"\nUsing: {kegg_id}") return k, kegg_id except Exception as e: print(f"✗ Error: {e}") return k, None def get_kegg_info(kegg, kegg_id): """Retrieve detailed KEGG compound information.""" print(f"\n{'='*70}") print("STEP 2: KEGG Compound Details") print(f"{'='*70}") try: print(f"Retrieving KEGG entry for {kegg_id}...") entry = kegg.get(f"cpd:{kegg_id}") if not entry: print("✗ Failed to retrieve entry") return None # Parse entry compound_info = { 'kegg_id': kegg_id, 'name': None, 'formula': None, 'exact_mass': None, 'mol_weight': None, 'chebi_id': None, 'pathways': [] } current_section = None for line in entry.split("\n"): if line.startswith("NAME"): compound_info['name'] = line.replace("NAME", "").strip().rstrip(";") elif line.startswith("FORMULA"): compound_info['formula'] = line.replace("FORMULA", "").strip() elif line.startswith("EXACT_MASS"): compound_info['exact_mass'] = line.replace("EXACT_MASS", "").strip() elif line.startswith("MOL_WEIGHT"): compound_info['mol_weight'] = line.replace("MOL_WEIGHT", "").strip() elif "ChEBI:" in line: parts = line.split("ChEBI:") if len(parts) > 1: compound_info['chebi_id'] = parts[1].strip().split()[0] elif line.startswith("PATHWAY"): current_section = "pathway" pathway = line.replace("PATHWAY", "").strip() if pathway: compound_info['pathways'].append(pathway) elif current_section == "pathway" and line.startswith(" "): pathway = line.strip() if pathway: compound_info['pathways'].append(pathway) elif line.startswith(" ") and not line.startswith(" "): current_section = None # Display information print(f"\n✓ KEGG Compound Information:") print(f" ID: {compound_info['kegg_id']}") print(f" Name: {compound_info['name']}") print(f" Formula: {compound_info['formula']}") print(f" Exact Mass: {compound_info['exact_mass']}") print(f" Molecular Weight: {compound_info['mol_weight']}") if compound_info['chebi_id']: print(f" ChEBI ID: {compound_info['chebi_id']}") if compound_info['pathways']: print(f" Pathways: {len(compound_info['pathways'])} found") return compound_info except Exception as e: print(f"✗ Error: {e}") return None def get_chembl_id(kegg_id): """Map KEGG ID to ChEMBL via UniChem.""" print(f"\n{'='*70}") print("STEP 3: ChEMBL Mapping (via UniChem)") print(f"{'='*70}") try: u = UniChem() print(f"Mapping KEGG:{kegg_id} to ChEMBL...") chembl_id = u.get_compound_id_from_kegg(kegg_id) if chembl_id: print(f"✓ ChEMBL ID: {chembl_id}") return chembl_id else: print("✗ No ChEMBL mapping found") return None except Exception as e: print(f"✗ Error: {e}") return None def get_chebi_info(chebi_id): """Retrieve ChEBI compound information.""" print(f"\n{'='*70}") print("STEP 4: ChEBI Details") print(f"{'='*70}") if not chebi_id: print("⊘ No ChEBI ID available") return None try: c = ChEBI() print(f"Retrieving ChEBI entry for {chebi_id}...") # Ensure proper format if not chebi_id.startswith("CHEBI:"): chebi_id = f"CHEBI:{chebi_id}" entity = c.getCompleteEntity(chebi_id) if entity: print(f"\n✓ ChEBI Information:") print(f" ID: {entity.chebiId}") print(f" Name: {entity.chebiAsciiName}") if hasattr(entity, 'Formulae') and entity.Formulae: print(f" Formula: {entity.Formulae}") if hasattr(entity, 'mass') and entity.mass: print(f" Mass: {entity.mass}") if hasattr(entity, 'charge') and entity.charge: print(f" Charge: {entity.charge}") return { 'chebi_id': entity.chebiId, 'name': entity.chebiAsciiName, 'formula': entity.Formulae if hasattr(entity, 'Formulae') else None, 'mass': entity.mass if hasattr(entity, 'mass') else None } else: print("✗ Failed to retrieve ChEBI entry") return None except Exception as e: print(f"✗ Error: {e}") return None def get_chembl_info(chembl_id): """Retrieve ChEMBL compound information.""" print(f"\n{'='*70}") print("STEP 5: ChEMBL Details") print(f"{'='*70}") if not chembl_id: print("⊘ No ChEMBL ID available") return None try: c = ChEMBL() print(f"Retrieving ChEMBL entry for {chembl_id}...") compound = c.get_compound_by_chemblId(chembl_id) if compound: print(f"\n✓ ChEMBL Information:") print(f" ID: {chembl_id}") if 'pref_name' in compound and compound['pref_name']: print(f" Preferred Name: {compound['pref_name']}") if 'molecule_properties' in compound: props = compound['molecule_properties'] if 'full_mwt' in props: print(f" Molecular Weight: {props['full_mwt']}") if 'alogp' in props: print(f" LogP: {props['alogp']}") if 'hba' in props: print(f" H-Bond Acceptors: {props['hba']}") if 'hbd' in props: print(f" H-Bond Donors: {props['hbd']}") if 'molecule_structures' in compound: structs = compound['molecule_structures'] if 'canonical_smiles' in structs: smiles = structs['canonical_smiles'] print(f" SMILES: {smiles[:60]}{'...' if len(smiles) > 60 else ''}") return compound else: print("✗ Failed to retrieve ChEMBL entry") return None except Exception as e: print(f"✗ Error: {e}") return None def save_results(compound_name, kegg_info, chembl_id, output_file): """Save results to file.""" print(f"\n{'='*70}") print(f"Saving results to {output_file}") print(f"{'='*70}") with open(output_file, 'w') as f: f.write("=" * 70 + "\n") f.write(f"Compound Cross-Reference Report: {compound_name}\n") f.write("=" * 70 + "\n\n") # KEGG information if kegg_info: f.write("KEGG Compound\n") f.write("-" * 70 + "\n") f.write(f"ID: {kegg_info['kegg_id']}\n") f.write(f"Name: {kegg_info['name']}\n") f.write(f"Formula: {kegg_info['formula']}\n") f.write(f"Exact Mass: {kegg_info['exact_mass']}\n") f.write(f"Molecular Weight: {kegg_info['mol_weight']}\n") f.write(f"Pathways: {len(kegg_info['pathways'])} found\n") f.write("\n") # Database IDs f.write("Cross-Database Identifiers\n") f.write("-" * 70 + "\n") if kegg_info: f.write(f"KEGG: {kegg_info['kegg_id']}\n") if kegg_info['chebi_id']: f.write(f"ChEBI: {kegg_info['chebi_id']}\n") if chembl_id: f.write(f"ChEMBL: {chembl_id}\n") f.write("\n") print(f"✓ Results saved") def main(): """Main workflow.""" parser = argparse.ArgumentParser( description="Search compound across multiple databases", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: python compound_cross_reference.py Geldanamycin python compound_cross_reference.py "Adenosine triphosphate" python compound_cross_reference.py Aspirin --output aspirin_info.txt """ ) parser.add_argument("compound", help="Compound name to search") parser.add_argument("--output", default=None, help="Output file for results (optional)") args = parser.parse_args() print("=" * 70) print("BIOSERVICES: Compound Cross-Database Search") print("=" * 70) # Step 1: Search KEGG kegg, kegg_id = search_kegg_compound(args.compound) if not kegg_id: print("\n✗ Failed to find compound. Exiting.") sys.exit(1) # Step 2: Get KEGG details kegg_info = get_kegg_info(kegg, kegg_id) # Step 3: Map to ChEMBL chembl_id = get_chembl_id(kegg_id) # Step 4: Get ChEBI details chebi_info = None if kegg_info and kegg_info['chebi_id']: chebi_info = get_chebi_info(kegg_info['chebi_id']) # Step 5: Get ChEMBL details chembl_info = None if chembl_id: chembl_info = get_chembl_info(chembl_id) # Summary print(f"\n{'='*70}") print("SUMMARY") print(f"{'='*70}") print(f" Compound: {args.compound}") if kegg_info: print(f" KEGG ID: {kegg_info['kegg_id']}") if kegg_info['chebi_id']: print(f" ChEBI ID: {kegg_info['chebi_id']}") if chembl_id: print(f" ChEMBL ID: {chembl_id}") print(f"{'='*70}") # Save to file if requested if args.output: save_results(args.compound, kegg_info, chembl_id, args.output) if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/bioservices/scripts/compound_cross_reference.py", "license": "MIT License", "lines": 286, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/bioservices/scripts/pathway_analysis.py
#!/usr/bin/env python3 """ KEGG Pathway Network Analysis This script analyzes all pathways for an organism and extracts: - Pathway sizes (number of genes) - Protein-protein interactions - Interaction type distributions - Network data in various formats (CSV, SIF) Usage: python pathway_analysis.py ORGANISM OUTPUT_DIR [--limit N] Examples: python pathway_analysis.py hsa ./human_pathways python pathway_analysis.py mmu ./mouse_pathways --limit 50 Organism codes: hsa = Homo sapiens (human) mmu = Mus musculus (mouse) dme = Drosophila melanogaster sce = Saccharomyces cerevisiae (yeast) eco = Escherichia coli """ import sys import os import argparse import csv from collections import Counter from bioservices import KEGG def get_all_pathways(kegg, organism): """Get all pathway IDs for organism.""" print(f"\nRetrieving pathways for {organism}...") kegg.organism = organism pathway_ids = kegg.pathwayIds print(f"✓ Found {len(pathway_ids)} pathways") return pathway_ids def analyze_pathway(kegg, pathway_id): """Analyze single pathway for size and interactions.""" try: # Parse KGML pathway kgml = kegg.parse_kgml_pathway(pathway_id) entries = kgml.get('entries', []) relations = kgml.get('relations', []) # Count relation types relation_types = Counter() for rel in relations: rel_type = rel.get('name', 'unknown') relation_types[rel_type] += 1 # Get pathway name try: entry = kegg.get(pathway_id) pathway_name = "Unknown" for line in entry.split("\n"): if line.startswith("NAME"): pathway_name = line.replace("NAME", "").strip() break except: pathway_name = "Unknown" result = { 'pathway_id': pathway_id, 'pathway_name': pathway_name, 'num_entries': len(entries), 'num_relations': len(relations), 'relation_types': dict(relation_types), 'entries': entries, 'relations': relations } return result except Exception as e: print(f" ✗ Error analyzing {pathway_id}: {e}") return None def analyze_all_pathways(kegg, pathway_ids, limit=None): """Analyze all pathways.""" if limit: pathway_ids = pathway_ids[:limit] print(f"\n⚠ Limiting analysis to first {limit} pathways") print(f"\nAnalyzing {len(pathway_ids)} pathways...") results = [] for i, pathway_id in enumerate(pathway_ids, 1): print(f" [{i}/{len(pathway_ids)}] {pathway_id}", end="\r") result = analyze_pathway(kegg, pathway_id) if result: results.append(result) print(f"\n✓ Successfully analyzed {len(results)}/{len(pathway_ids)} pathways") return results def save_pathway_summary(results, output_file): """Save pathway summary to CSV.""" print(f"\nSaving pathway summary to {output_file}...") with open(output_file, 'w', newline='') as f: writer = csv.writer(f) # Header writer.writerow([ 'Pathway_ID', 'Pathway_Name', 'Num_Genes', 'Num_Interactions', 'Activation', 'Inhibition', 'Phosphorylation', 'Binding', 'Other' ]) # Data for result in results: rel_types = result['relation_types'] writer.writerow([ result['pathway_id'], result['pathway_name'], result['num_entries'], result['num_relations'], rel_types.get('activation', 0), rel_types.get('inhibition', 0), rel_types.get('phosphorylation', 0), rel_types.get('binding/association', 0), sum(v for k, v in rel_types.items() if k not in ['activation', 'inhibition', 'phosphorylation', 'binding/association']) ]) print(f"✓ Summary saved") def save_interactions_sif(results, output_file): """Save all interactions in SIF format.""" print(f"\nSaving interactions to {output_file}...") with open(output_file, 'w') as f: for result in results: pathway_id = result['pathway_id'] for rel in result['relations']: entry1 = rel.get('entry1', '') entry2 = rel.get('entry2', '') interaction_type = rel.get('name', 'interaction') # Write SIF format: source\tinteraction\ttarget f.write(f"{entry1}\t{interaction_type}\t{entry2}\n") print(f"✓ Interactions saved") def save_detailed_pathway_info(results, output_dir): """Save detailed information for each pathway.""" print(f"\nSaving detailed pathway files to {output_dir}/pathways/...") pathway_dir = os.path.join(output_dir, "pathways") os.makedirs(pathway_dir, exist_ok=True) for result in results: pathway_id = result['pathway_id'].replace(":", "_") filename = os.path.join(pathway_dir, f"{pathway_id}_interactions.csv") with open(filename, 'w', newline='') as f: writer = csv.writer(f) writer.writerow(['Source', 'Target', 'Interaction_Type', 'Link_Type']) for rel in result['relations']: writer.writerow([ rel.get('entry1', ''), rel.get('entry2', ''), rel.get('name', 'unknown'), rel.get('link', 'unknown') ]) print(f"✓ Detailed files saved for {len(results)} pathways") def print_statistics(results): """Print analysis statistics.""" print(f"\n{'='*70}") print("PATHWAY ANALYSIS STATISTICS") print(f"{'='*70}") # Total stats total_pathways = len(results) total_interactions = sum(r['num_relations'] for r in results) total_genes = sum(r['num_entries'] for r in results) print(f"\nOverall:") print(f" Total pathways: {total_pathways}") print(f" Total genes/proteins: {total_genes}") print(f" Total interactions: {total_interactions}") # Largest pathways print(f"\nLargest pathways (by gene count):") sorted_by_size = sorted(results, key=lambda x: x['num_entries'], reverse=True) for i, result in enumerate(sorted_by_size[:10], 1): print(f" {i}. {result['pathway_id']}: {result['num_entries']} genes") print(f" {result['pathway_name']}") # Most connected pathways print(f"\nMost connected pathways (by interactions):") sorted_by_connections = sorted(results, key=lambda x: x['num_relations'], reverse=True) for i, result in enumerate(sorted_by_connections[:10], 1): print(f" {i}. {result['pathway_id']}: {result['num_relations']} interactions") print(f" {result['pathway_name']}") # Interaction type distribution print(f"\nInteraction type distribution:") all_types = Counter() for result in results: for rel_type, count in result['relation_types'].items(): all_types[rel_type] += count for rel_type, count in all_types.most_common(): percentage = (count / total_interactions) * 100 if total_interactions > 0 else 0 print(f" {rel_type}: {count} ({percentage:.1f}%)") def main(): """Main analysis workflow.""" parser = argparse.ArgumentParser( description="Analyze KEGG pathways for an organism", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: python pathway_analysis.py hsa ./human_pathways python pathway_analysis.py mmu ./mouse_pathways --limit 50 Organism codes: hsa = Homo sapiens (human) mmu = Mus musculus (mouse) dme = Drosophila melanogaster sce = Saccharomyces cerevisiae (yeast) eco = Escherichia coli """ ) parser.add_argument("organism", help="KEGG organism code (e.g., hsa, mmu)") parser.add_argument("output_dir", help="Output directory for results") parser.add_argument("--limit", type=int, default=None, help="Limit analysis to first N pathways") args = parser.parse_args() print("=" * 70) print("BIOSERVICES: KEGG Pathway Network Analysis") print("=" * 70) # Create output directory os.makedirs(args.output_dir, exist_ok=True) # Initialize KEGG kegg = KEGG() # Get all pathways pathway_ids = get_all_pathways(kegg, args.organism) if not pathway_ids: print(f"\n✗ No pathways found for {args.organism}") sys.exit(1) # Analyze pathways results = analyze_all_pathways(kegg, pathway_ids, args.limit) if not results: print("\n✗ No pathways successfully analyzed") sys.exit(1) # Print statistics print_statistics(results) # Save results summary_file = os.path.join(args.output_dir, "pathway_summary.csv") save_pathway_summary(results, summary_file) sif_file = os.path.join(args.output_dir, "all_interactions.sif") save_interactions_sif(results, sif_file) save_detailed_pathway_info(results, args.output_dir) # Final summary print(f"\n{'='*70}") print("OUTPUT FILES") print(f"{'='*70}") print(f" Summary: {summary_file}") print(f" Interactions: {sif_file}") print(f" Detailed: {args.output_dir}/pathways/") print(f"{'='*70}") if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/bioservices/scripts/pathway_analysis.py", "license": "MIT License", "lines": 238, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/bioservices/scripts/protein_analysis_workflow.py
#!/usr/bin/env python3 """ Complete Protein Analysis Workflow This script performs a comprehensive protein analysis pipeline: 1. UniProt search and identifier retrieval 2. FASTA sequence retrieval 3. BLAST similarity search 4. KEGG pathway discovery 5. PSICQUIC interaction mapping 6. GO annotation retrieval Usage: python protein_analysis_workflow.py PROTEIN_NAME EMAIL [--skip-blast] Examples: python protein_analysis_workflow.py ZAP70_HUMAN user@example.com python protein_analysis_workflow.py P43403 user@example.com --skip-blast Note: BLAST searches can take several minutes. Use --skip-blast to skip this step. """ import sys import time import argparse from bioservices import UniProt, KEGG, NCBIblast, PSICQUIC, QuickGO def search_protein(query): """Search UniProt for protein and retrieve basic information.""" print(f"\n{'='*70}") print("STEP 1: UniProt Search") print(f"{'='*70}") u = UniProt(verbose=False) print(f"Searching for: {query}") # Try direct retrieval first (if query looks like accession) if len(query) == 6 and query[0] in "OPQ": try: entry = u.retrieve(query, frmt="tab") if entry: uniprot_id = query print(f"✓ Found UniProt entry: {uniprot_id}") return u, uniprot_id except: pass # Otherwise search results = u.search(query, frmt="tab", columns="id,genes,organism,length,protein names", limit=5) if not results: print("✗ No results found") return u, None lines = results.strip().split("\n") if len(lines) < 2: print("✗ No entries found") return u, None # Display results print(f"\n✓ Found {len(lines)-1} result(s):") for i, line in enumerate(lines[1:], 1): fields = line.split("\t") print(f" {i}. {fields[0]} - {fields[1]} ({fields[2]})") # Use first result first_entry = lines[1].split("\t") uniprot_id = first_entry[0] gene_names = first_entry[1] if len(first_entry) > 1 else "N/A" organism = first_entry[2] if len(first_entry) > 2 else "N/A" length = first_entry[3] if len(first_entry) > 3 else "N/A" protein_name = first_entry[4] if len(first_entry) > 4 else "N/A" print(f"\nUsing first result:") print(f" UniProt ID: {uniprot_id}") print(f" Gene names: {gene_names}") print(f" Organism: {organism}") print(f" Length: {length} aa") print(f" Protein: {protein_name}") return u, uniprot_id def retrieve_sequence(uniprot, uniprot_id): """Retrieve FASTA sequence for protein.""" print(f"\n{'='*70}") print("STEP 2: FASTA Sequence Retrieval") print(f"{'='*70}") try: sequence = uniprot.retrieve(uniprot_id, frmt="fasta") if sequence: # Extract sequence only (remove header) lines = sequence.strip().split("\n") header = lines[0] seq_only = "".join(lines[1:]) print(f"✓ Retrieved sequence:") print(f" Header: {header}") print(f" Length: {len(seq_only)} residues") print(f" First 60 residues: {seq_only[:60]}...") return seq_only else: print("✗ Failed to retrieve sequence") return None except Exception as e: print(f"✗ Error: {e}") return None def run_blast(sequence, email, skip=False): """Run BLAST similarity search.""" print(f"\n{'='*70}") print("STEP 3: BLAST Similarity Search") print(f"{'='*70}") if skip: print("⊘ Skipped (--skip-blast flag)") return None if not email or "@" not in email: print("⊘ Skipped (valid email required for BLAST)") return None try: print(f"Submitting BLASTP job...") print(f" Database: uniprotkb") print(f" Sequence length: {len(sequence)} aa") s = NCBIblast(verbose=False) jobid = s.run( program="blastp", sequence=sequence, stype="protein", database="uniprotkb", email=email ) print(f"✓ Job submitted: {jobid}") print(f" Waiting for completion...") # Poll for completion max_wait = 300 # 5 minutes start_time = time.time() while time.time() - start_time < max_wait: status = s.getStatus(jobid) elapsed = int(time.time() - start_time) print(f" Status: {status} (elapsed: {elapsed}s)", end="\r") if status == "FINISHED": print(f"\n✓ BLAST completed in {elapsed}s") # Retrieve results results = s.getResult(jobid, "out") # Parse and display summary lines = results.split("\n") print(f"\n Results preview:") for line in lines[:20]: if line.strip(): print(f" {line}") return results elif status == "ERROR": print(f"\n✗ BLAST job failed") return None time.sleep(5) print(f"\n✗ Timeout after {max_wait}s") return None except Exception as e: print(f"✗ Error: {e}") return None def discover_pathways(uniprot, kegg, uniprot_id): """Discover KEGG pathways for protein.""" print(f"\n{'='*70}") print("STEP 4: KEGG Pathway Discovery") print(f"{'='*70}") try: # Map UniProt → KEGG print(f"Mapping {uniprot_id} to KEGG...") kegg_mapping = uniprot.mapping(fr="UniProtKB_AC-ID", to="KEGG", query=uniprot_id) if not kegg_mapping or uniprot_id not in kegg_mapping: print("✗ No KEGG mapping found") return [] kegg_ids = kegg_mapping[uniprot_id] print(f"✓ KEGG ID(s): {kegg_ids}") # Get pathways for first KEGG ID kegg_id = kegg_ids[0] organism, gene_id = kegg_id.split(":") print(f"\nSearching pathways for {kegg_id}...") pathways = kegg.get_pathway_by_gene(gene_id, organism) if not pathways: print("✗ No pathways found") return [] print(f"✓ Found {len(pathways)} pathway(s):\n") # Get pathway names pathway_info = [] for pathway_id in pathways: try: entry = kegg.get(pathway_id) # Extract pathway name pathway_name = "Unknown" for line in entry.split("\n"): if line.startswith("NAME"): pathway_name = line.replace("NAME", "").strip() break pathway_info.append((pathway_id, pathway_name)) print(f" • {pathway_id}: {pathway_name}") except Exception as e: print(f" • {pathway_id}: [Error retrieving name]") return pathway_info except Exception as e: print(f"✗ Error: {e}") return [] def find_interactions(protein_query): """Find protein-protein interactions via PSICQUIC.""" print(f"\n{'='*70}") print("STEP 5: Protein-Protein Interactions") print(f"{'='*70}") try: p = PSICQUIC() # Try querying MINT database query = f"{protein_query} AND species:9606" print(f"Querying MINT database...") print(f" Query: {query}") results = p.query("mint", query) if not results: print("✗ No interactions found in MINT") return [] # Parse PSI-MI TAB format lines = results.strip().split("\n") print(f"✓ Found {len(lines)} interaction(s):\n") # Display first 10 interactions interactions = [] for i, line in enumerate(lines[:10], 1): fields = line.split("\t") if len(fields) >= 12: protein_a = fields[4].split(":")[1] if ":" in fields[4] else fields[4] protein_b = fields[5].split(":")[1] if ":" in fields[5] else fields[5] interaction_type = fields[11] interactions.append((protein_a, protein_b, interaction_type)) print(f" {i}. {protein_a} ↔ {protein_b}") if len(lines) > 10: print(f" ... and {len(lines)-10} more") return interactions except Exception as e: print(f"✗ Error: {e}") return [] def get_go_annotations(uniprot_id): """Retrieve GO annotations.""" print(f"\n{'='*70}") print("STEP 6: Gene Ontology Annotations") print(f"{'='*70}") try: g = QuickGO() print(f"Retrieving GO annotations for {uniprot_id}...") annotations = g.Annotation(protein=uniprot_id, format="tsv") if not annotations: print("✗ No GO annotations found") return [] lines = annotations.strip().split("\n") print(f"✓ Found {len(lines)-1} annotation(s)\n") # Group by aspect aspects = {"P": [], "F": [], "C": []} for line in lines[1:]: fields = line.split("\t") if len(fields) >= 9: go_id = fields[6] go_term = fields[7] go_aspect = fields[8] if go_aspect in aspects: aspects[go_aspect].append((go_id, go_term)) # Display summary print(f" Biological Process (P): {len(aspects['P'])} terms") for go_id, go_term in aspects['P'][:5]: print(f" • {go_id}: {go_term}") if len(aspects['P']) > 5: print(f" ... and {len(aspects['P'])-5} more") print(f"\n Molecular Function (F): {len(aspects['F'])} terms") for go_id, go_term in aspects['F'][:5]: print(f" • {go_id}: {go_term}") if len(aspects['F']) > 5: print(f" ... and {len(aspects['F'])-5} more") print(f"\n Cellular Component (C): {len(aspects['C'])} terms") for go_id, go_term in aspects['C'][:5]: print(f" • {go_id}: {go_term}") if len(aspects['C']) > 5: print(f" ... and {len(aspects['C'])-5} more") return aspects except Exception as e: print(f"✗ Error: {e}") return {} def main(): """Main workflow.""" parser = argparse.ArgumentParser( description="Complete protein analysis workflow using BioServices", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: python protein_analysis_workflow.py ZAP70_HUMAN user@example.com python protein_analysis_workflow.py P43403 user@example.com --skip-blast """ ) parser.add_argument("protein", help="Protein name or UniProt ID") parser.add_argument("email", help="Email address (required for BLAST)") parser.add_argument("--skip-blast", action="store_true", help="Skip BLAST search (faster)") args = parser.parse_args() print("=" * 70) print("BIOSERVICES: Complete Protein Analysis Workflow") print("=" * 70) # Step 1: Search protein uniprot, uniprot_id = search_protein(args.protein) if not uniprot_id: print("\n✗ Failed to find protein. Exiting.") sys.exit(1) # Step 2: Retrieve sequence sequence = retrieve_sequence(uniprot, uniprot_id) if not sequence: print("\n⚠ Warning: Could not retrieve sequence") # Step 3: BLAST search if sequence: blast_results = run_blast(sequence, args.email, args.skip_blast) # Step 4: Pathway discovery kegg = KEGG() pathways = discover_pathways(uniprot, kegg, uniprot_id) # Step 5: Interaction mapping interactions = find_interactions(args.protein) # Step 6: GO annotations go_terms = get_go_annotations(uniprot_id) # Summary print(f"\n{'='*70}") print("WORKFLOW SUMMARY") print(f"{'='*70}") print(f" Protein: {args.protein}") print(f" UniProt ID: {uniprot_id}") print(f" Sequence: {'✓' if sequence else '✗'}") print(f" BLAST: {'✓' if not args.skip_blast and sequence else '⊘'}") print(f" Pathways: {len(pathways)} found") print(f" Interactions: {len(interactions)} found") print(f" GO annotations: {sum(len(v) for v in go_terms.values())} found") print(f"{'='*70}") if __name__ == "__main__": main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/bioservices/scripts/protein_analysis_workflow.py", "license": "MIT License", "lines": 313, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/brenda-database/scripts/brenda_queries.py
""" BRENDA Database Query Utilities This module provides high-level functions for querying and analyzing enzyme data from the BRENDA database using the SOAP API. Key features: - Parse BRENDA response data entries - Search for enzymes by substrate/product - Compare enzyme properties across organisms - Retrieve kinetic parameters and environmental conditions - Analyze substrate specificity and inhibition - Support for enzyme engineering and pathway design - Export data in various formats Installation: uv pip install zeep requests pandas Usage: from scripts.brenda_queries import search_enzymes_by_substrate, compare_across_organisms enzymes = search_enzymes_by_substrate("glucose", limit=20) comparison = compare_across_organisms("1.1.1.1", ["E. coli", "S. cerevisiae"]) """ import re import time import json import csv from typing import List, Dict, Any, Optional, Tuple from pathlib import Path try: from zeep import Client, Settings from zeep.exceptions import Fault, TransportError ZEEP_AVAILABLE = True except ImportError: print("Warning: zeep not installed. Install with: uv pip install zeep") ZEEP_AVAILABLE = False try: import requests REQUESTS_AVAILABLE = True except ImportError: print("Warning: requests not installed. Install with: uv pip install requests") REQUESTS_AVAILABLE = False try: import pandas as pd PANDAS_AVAILABLE = True except ImportError: print("Warning: pandas not installed. Install with: uv pip install pandas") PANDAS_AVAILABLE = False # Import the brenda_client from the project root import sys sys.path.append(str(Path(__file__).parent.parent.parent.parent)) try: from brenda_client import get_km_values, get_reactions, call_brenda BRENDA_CLIENT_AVAILABLE = True except ImportError: print("Warning: brenda_client not available") BRENDA_CLIENT_AVAILABLE = False def validate_dependencies(): """Validate that required dependencies are installed.""" missing = [] if not ZEEP_AVAILABLE: missing.append("zeep") if not REQUESTS_AVAILABLE: missing.append("requests") if not BRENDA_CLIENT_AVAILABLE: missing.append("brenda_client") if missing: raise ImportError(f"Missing required dependencies: {', '.join(missing)}") def parse_km_entry(entry: str) -> Dict[str, Any]: """Parse a BRENDA Km value entry into structured data.""" if not entry or not isinstance(entry, str): return {} parsed = {} parts = entry.split('#') for part in parts: if '*' in part: key, value = part.split('*', 1) parsed[key.strip()] = value.strip() # Extract numeric values from kmValue if 'kmValue' in parsed: km_value = parsed['kmValue'] # Extract first numeric value (in mM typically) numeric_match = re.search(r'(\d+\.?\d*)', km_value) if numeric_match: parsed['km_value_numeric'] = float(numeric_match.group(1)) # Extract pH from commentary if 'commentary' in parsed: commentary = parsed['commentary'] ph_match = re.search(r'pH\s*([0-9.]+)', commentary) if ph_match: parsed['ph'] = float(ph_match.group(1)) temp_match = re.search(r'(\d+)\s*°?C', commentary) if temp_match: parsed['temperature'] = float(temp_match.group(1)) return parsed def parse_reaction_entry(entry: str) -> Dict[str, Any]: """Parse a BRENDA reaction entry into structured data.""" if not entry or not isinstance(entry, str): return {} parsed = {} parts = entry.split('#') for part in parts: if '*' in part: key, value = part.split('*', 1) parsed[key.strip()] = value.strip() # Parse reaction equation if 'reaction' in parsed: reaction = parsed['reaction'] # Extract reactants and products if '<=>' in reaction: reactants, products = reaction.split('<=>', 1) elif '->' in reaction: reactants, products = reaction.split('->', 1) elif '=' in reaction: reactants, products = reaction.split('=', 1) else: reactants, products = reaction, '' parsed['reactants'] = [r.strip() for r in reactants.split('+')] parsed['products'] = [p.strip() for p in products.split('+')] return parsed def extract_organism_data(entry: str) -> Dict[str, Any]: """Extract organism-specific information from BRENDA entry.""" parsed = parse_km_entry(entry) if 'kmValue' in entry else parse_reaction_entry(entry) if 'organism' in parsed: return { 'organism': parsed['organism'], 'ec_number': parsed.get('ecNumber', ''), 'substrate': parsed.get('substrate', ''), 'km_value': parsed.get('kmValue', ''), 'km_numeric': parsed.get('km_value_numeric', None), 'ph': parsed.get('ph', None), 'temperature': parsed.get('temperature', None), 'commentary': parsed.get('commentary', ''), 'literature': parsed.get('literature', '') } return {} def search_enzymes_by_substrate(substrate: str, limit: int = 50) -> List[Dict[str, Any]]: """Search for enzymes that act on a specific substrate.""" validate_dependencies() enzymes = [] # Search for Km values with the substrate try: km_data = get_km_values("*", substrate=substrate) time.sleep(0.5) # Rate limiting for entry in km_data[:limit]: parsed = parse_km_entry(entry) if parsed: enzymes.append({ 'ec_number': parsed.get('ecNumber', ''), 'organism': parsed.get('organism', ''), 'substrate': parsed.get('substrate', ''), 'km_value': parsed.get('kmValue', ''), 'km_numeric': parsed.get('km_value_numeric', None), 'commentary': parsed.get('commentary', '') }) except Exception as e: print(f"Error searching enzymes by substrate: {e}") # Remove duplicates based on EC number and organism unique_enzymes = [] seen = set() for enzyme in enzymes: key = (enzyme['ec_number'], enzyme['organism']) if key not in seen: seen.add(key) unique_enzymes.append(enzyme) return unique_enzymes[:limit] def search_enzymes_by_product(product: str, limit: int = 50) -> List[Dict[str, Any]]: """Search for enzymes that produce a specific product.""" validate_dependencies() enzymes = [] # Search for reactions containing the product try: # This is a simplified approach - in practice you might need # more sophisticated pattern matching for products reactions = get_reactions("*", reaction=f"*{product}*") time.sleep(0.5) # Rate limiting for entry in reactions[:limit]: parsed = parse_reaction_entry(entry) if parsed and 'products' in parsed: # Check if our target product is in the products list if any(product.lower() in prod.lower() for prod in parsed['products']): enzymes.append({ 'ec_number': parsed.get('ecNumber', ''), 'organism': parsed.get('organism', ''), 'reaction': parsed.get('reaction', ''), 'reactants': parsed.get('reactants', []), 'products': parsed.get('products', []), 'commentary': parsed.get('commentary', '') }) except Exception as e: print(f"Error searching enzymes by product: {e}") return enzymes[:limit] def compare_across_organisms(ec_number: str, organisms: List[str]) -> List[Dict[str, Any]]: """Compare enzyme properties across different organisms.""" validate_dependencies() comparison = [] for organism in organisms: try: # Get Km data for this organism km_data = get_km_values(ec_number, organism=organism) time.sleep(0.5) # Rate limiting if km_data: # Calculate statistics numeric_kms = [] phs = [] temperatures = [] for entry in km_data: parsed = parse_km_entry(entry) if 'km_value_numeric' in parsed: numeric_kms.append(parsed['km_value_numeric']) if 'ph' in parsed: phs.append(parsed['ph']) if 'temperature' in parsed: temperatures.append(parsed['temperature']) org_data = { 'organism': organism, 'ec_number': ec_number, 'data_points': len(km_data), 'average_km': sum(numeric_kms) / len(numeric_kms) if numeric_kms else None, 'min_km': min(numeric_kms) if numeric_kms else None, 'max_km': max(numeric_kms) if numeric_kms else None, 'optimal_ph': sum(phs) / len(phs) if phs else None, 'optimal_temperature': sum(temperatures) / len(temperatures) if temperatures else None, 'temperature_range': (min(temperatures), max(temperatures)) if temperatures else None } comparison.append(org_data) else: comparison.append({ 'organism': organism, 'ec_number': ec_number, 'data_points': 0, 'note': 'No data found' }) except Exception as e: print(f"Error comparing organism {organism}: {e}") comparison.append({ 'organism': organism, 'ec_number': ec_number, 'error': str(e) }) return comparison def get_organisms_for_enzyme(ec_number: str) -> List[str]: """Get list of organisms that have data for a specific enzyme.""" validate_dependencies() try: km_data = get_km_values(ec_number) time.sleep(0.5) # Rate limiting organisms = set() for entry in km_data: parsed = parse_km_entry(entry) if 'organism' in parsed: organisms.add(parsed['organism']) return sorted(list(organisms)) except Exception as e: print(f"Error getting organisms for enzyme {ec_number}: {e}") return [] def get_environmental_parameters(ec_number: str) -> Dict[str, Any]: """Get environmental parameters (pH, temperature) for an enzyme.""" validate_dependencies() try: km_data = get_km_values(ec_number) time.sleep(0.5) # Rate limiting phs = [] temperatures = [] ph_stabilities = [] temp_stabilities = [] for entry in km_data: parsed = parse_km_entry(entry) if 'ph' in parsed: phs.append(parsed['ph']) if 'temperature' in parsed: temperatures.append(parsed['temperature']) # Check commentary for stability information commentary = parsed.get('commentary', '').lower() if 'stable' in commentary and 'ph' in commentary: # Extract pH stability range ph_range_match = re.search(r'ph\s*([\d.]+)\s*[-–]\s*([\d.]+)', commentary) if ph_range_match: ph_stabilities.append((float(ph_range_match.group(1)), float(ph_range_match.group(2)))) if 'stable' in commentary and ('temp' in commentary or '°c' in commentary): # Extract temperature stability temp_match = re.search(r'(\d+)\s*[-–]\s*(\d+)\s*°?c', commentary) if temp_match: temp_stabilities.append((int(temp_match.group(1)), int(temp_match.group(2)))) params = { 'ec_number': ec_number, 'data_points': len(km_data), 'ph_range': (min(phs), max(phs)) if phs else None, 'optimal_ph': sum(phs) / len(phs) if phs else None, 'optimal_temperature': sum(temperatures) / len(temperatures) if temperatures else None, 'temperature_range': (min(temperatures), max(temperatures)) if temperatures else None, 'stability_ph': ph_stabilities[0] if ph_stabilities else None, 'temperature_stability': temp_stabilities[0] if temp_stabilities else None } return params except Exception as e: print(f"Error getting environmental parameters for {ec_number}: {e}") return {'ec_number': ec_number, 'error': str(e)} def get_cofactor_requirements(ec_number: str) -> List[Dict[str, Any]]: """Get cofactor requirements for an enzyme from reaction data.""" validate_dependencies() cofactors = [] try: reactions = get_reactions(ec_number) time.sleep(0.5) # Rate limiting for entry in reactions: parsed = parse_reaction_entry(entry) if parsed and 'reactants' in parsed: # Look for common cofactors in reactants common_cofactors = [ 'NAD+', 'NADH', 'NADP+', 'NADPH', 'ATP', 'ADP', 'AMP', 'FAD', 'FADH2', 'CoA', 'acetyl-CoA', 'pyridoxal phosphate', 'PLP', 'biotin', 'heme', 'iron-sulfur' ] for reactant in parsed['reactants']: for cofactor in common_cofactors: if cofactor.lower() in reactant.lower(): cofactors.append({ 'name': cofactor, 'full_name': reactant, 'type': 'oxidoreductase' if 'NAD' in cofactor else 'other', 'organism': parsed.get('organism', ''), 'ec_number': ec_number }) except Exception as e: print(f"Error getting cofactor requirements for {ec_number}: {e}") # Remove duplicates unique_cofactors = [] seen = set() for cofactor in cofactors: key = (cofactor['name'], cofactor['organism']) if key not in seen: seen.add(key) unique_cofactors.append(cofactor) return unique_cofactors def get_substrate_specificity(ec_number: str) -> List[Dict[str, Any]]: """Get substrate specificity data for an enzyme.""" validate_dependencies() specificity = [] try: km_data = get_km_values(ec_number) time.sleep(0.5) # Rate limiting substrate_data = {} for entry in km_data: parsed = parse_km_entry(entry) if 'substrate' in parsed and 'km_value_numeric' in parsed: substrate = parsed['substrate'] if substrate not in substrate_data: substrate_data[substrate] = { 'name': substrate, 'km_values': [], 'organisms': set(), 'vmax_values': [], # If available 'kcat_values': [] # If available } substrate_data[substrate]['km_values'].append(parsed['km_value_numeric']) if 'organism' in parsed: substrate_data[substrate]['organisms'].add(parsed['organism']) # Calculate summary statistics for substrate, data in substrate_data.items(): if data['km_values']: specificity.append({ 'name': substrate, 'km': sum(data['km_values']) / len(data['km_values']), 'min_km': min(data['km_values']), 'max_km': max(data['km_values']), 'data_points': len(data['km_values']), 'organisms': list(data['organisms']), 'vmax': sum(data['vmax_values']) / len(data['vmax_values']) if data['vmax_values'] else None, 'kcat': sum(data['kcat_values']) / len(data['kcat_values']) if data['kcat_values'] else None, 'kcat_km_ratio': None # Would need kcat data to calculate }) # Sort by Km (lower is better affinity) specificity.sort(key=lambda x: x['km'] if x['km'] else float('inf')) except Exception as e: print(f"Error getting substrate specificity for {ec_number}: {e}") return specificity def compare_substrate_affinity(ec_number: str) -> List[Dict[str, Any]]: """Compare substrate affinity for an enzyme.""" return get_substrate_specificity(ec_number) def get_inhibitors(ec_number: str) -> List[Dict[str, Any]]: """Get inhibitor information for an enzyme (from commentary).""" validate_dependencies() inhibitors = [] try: km_data = get_km_values(ec_number) time.sleep(0.5) # Rate limiting for entry in km_data: parsed = parse_km_entry(entry) commentary = parsed.get('commentary', '').lower() # Look for inhibitor keywords inhibitor_keywords = ['inhibited', 'inhibition', 'blocked', 'prevented', 'reduced'] if any(keyword in commentary for keyword in inhibitor_keywords): # Try to extract inhibitor names (this is approximate) # Common inhibitors common_inhibitors = [ 'iodoacetate', 'n-ethylmaleimide', 'p-chloromercuribenzoate', 'heavy metals', 'mercury', 'copper', 'zinc', 'cyanide', 'azide', 'carbon monoxide', 'edta', 'egta' ] for inhibitor in common_inhibitors: if inhibitor in commentary: inhibitors.append({ 'name': inhibitor, 'type': 'irreversible' if 'iodoacetate' in inhibitor or 'maleimide' in inhibitor else 'reversible', 'organism': parsed.get('organism', ''), 'ec_number': ec_number, 'commentary': parsed.get('commentary', '') }) except Exception as e: print(f"Error getting inhibitors for {ec_number}: {e}") # Remove duplicates unique_inhibitors = [] seen = set() for inhibitor in inhibitors: key = (inhibitor['name'], inhibitor['organism']) if key not in seen: seen.add(key) unique_inhibitors.append(inhibitor) return unique_inhibitors def get_activators(ec_number: str) -> List[Dict[str, Any]]: """Get activator information for an enzyme (from commentary).""" validate_dependencies() activators = [] try: km_data = get_km_values(ec_number) time.sleep(0.5) # Rate limiting for entry in km_data: parsed = parse_km_entry(entry) commentary = parsed.get('commentary', '').lower() # Look for activator keywords activator_keywords = ['activated', 'stimulated', 'enhanced', 'increased'] if any(keyword in commentary for keyword in activator_keywords): # Try to extract activator names (this is approximate) common_activators = [ 'mg2+', 'mn2+', 'ca2+', 'zn2+', 'k+', 'na+', 'phosphate', 'pyrophosphate', 'dithiothreitol', 'dtt', 'β-mercaptoethanol' ] for activator in common_activators: if activator in commentary: activators.append({ 'name': activator, 'type': 'metal ion' if '+' in activator else 'reducing agent' if 'dtt' in activator.lower() or 'mercapto' in activator.lower() else 'other', 'mechanism': 'allosteric' if 'allosteric' in commentary else 'cofactor' else 'unknown', 'organism': parsed.get('organism', ''), 'ec_number': ec_number, 'commentary': parsed.get('commentary', '') }) except Exception as e: print(f"Error getting activators for {ec_number}: {e}") # Remove duplicates unique_activators = [] seen = set() for activator in activators: key = (activator['name'], activator['organism']) if key not in seen: seen.add(key) unique_activators.append(activator) return unique_activators def find_thermophilic_homologs(ec_number: str, min_temp: int = 50) -> List[Dict[str, Any]]: """Find thermophilic homologs of an enzyme.""" validate_dependencies() thermophilic = [] try: organisms = get_organisms_for_enzyme(ec_number) for organism in organisms: # Check if organism might be thermophilic based on name thermophilic_keywords = ['therm', 'hypertherm', 'pyro'] if any(keyword in organism.lower() for keyword in thermophilic_keywords): # Get kinetic data to extract temperature information km_data = get_km_values(ec_number, organism=organism) time.sleep(0.2) # Rate limiting temperatures = [] kms = [] for entry in km_data: parsed = parse_km_entry(entry) if 'temperature' in parsed: temperatures.append(parsed['temperature']) if 'km_value_numeric' in parsed: kms.append(parsed['km_value_numeric']) if temperatures and max(temperatures) >= min_temp: thermophilic.append({ 'organism': organism, 'ec_number': ec_number, 'optimal_temperature': max(temperatures), 'temperature_range': (min(temperatures), max(temperatures)), 'km': sum(kms) / len(kms) if kms else None, 'data_points': len(km_data) }) except Exception as e: print(f"Error finding thermophilic homologs for {ec_number}: {e}") return thermophilic def find_ph_stable_variants(ec_number: str, min_ph: float = 8.0, max_ph: float = 6.0) -> List[Dict[str, Any]]: """Find pH-stable variants of an enzyme.""" validate_dependencies() ph_stable = [] try: organisms = get_organisms_for_enzyme(ec_number) for organism in organisms: km_data = get_km_values(ec_number, organism=organism) time.sleep(0.2) # Rate limiting phs = [] kms = [] for entry in km_data: parsed = parse_km_entry(entry) if 'ph' in parsed: phs.append(parsed['ph']) if 'km_value_numeric' in parsed: kms.append(parsed['km_value_numeric']) if phs: ph_range = (min(phs), max(phs)) is_alkaline_stable = min_ph and ph_range[0] >= min_ph is_acid_stable = max_ph and ph_range[1] <= max_ph if is_alkaline_stable or is_acid_stable: ph_stable.append({ 'organism': organism, 'ec_number': ec_number, 'ph_range': ph_range, 'optimal_ph': sum(phs) / len(phs), 'km': sum(kms) / len(kms) if kms else None, 'stability_type': 'alkaline' if is_alkaline_stable else 'acidic', 'data_points': len(km_data) }) except Exception as e: print(f"Error finding pH-stable variants for {ec_number}: {e}") return ph_stable def get_modeling_parameters(ec_number: str, substrate: str = None) -> Dict[str, Any]: """Get parameters suitable for kinetic modeling.""" validate_dependencies() try: if substrate: km_data = get_km_values(ec_number, substrate=substrate) else: km_data = get_km_values(ec_number) time.sleep(0.5) # Rate limiting if not km_data: return {'ec_number': ec_number, 'error': 'No kinetic data found'} # Extract modeling parameters kms = [] phs = [] temperatures = [] v_max_values = [] kcat_values = [] for entry in km_data: parsed = parse_km_entry(entry) if 'km_value_numeric' in parsed: kms.append(parsed['km_value_numeric']) if 'ph' in parsed: phs.append(parsed['ph']) if 'temperature' in parsed: temperatures.append(parsed['temperature']) # Look for Vmax and kcat in commentary (rare in BRENDA) commentary = parsed.get('commentary', '').lower() vmax_match = re.search(r'vmax\s*=\s*([\d.]+)', commentary) if vmax_match: v_max_values.append(float(vmax_match.group(1))) kcat_match = re.search(r'kcat\s*=\s*([\d.]+)', commentary) if kcat_match: kcat_values.append(float(kcat_match.group(1))) modeling_data = { 'ec_number': ec_number, 'substrate': substrate if substrate else 'various', 'km': sum(kms) / len(kms) if kms else None, 'km_std': (sum((x - sum(kms)/len(kms))**2 for x in kms) / len(kms))**0.5 if kms else None, 'vmax': sum(v_max_values) / len(v_max_values) if v_max_values else None, 'kcat': sum(kcat_values) / len(kcat_values) if kcat_values else None, 'optimal_ph': sum(phs) / len(phs) if phs else None, 'optimal_temperature': sum(temperatures) / len(temperatures) if temperatures else None, 'data_points': len(km_data), 'temperature': sum(temperatures) / len(temperatures) if temperatures else 25.0, # Default to 25°C 'ph': sum(phs) / len(phs) if phs else 7.0, # Default to pH 7.0 'enzyme_conc': 1.0, # Default enzyme concentration (μM) 'substrate_conc': None, # Would be set by user } return modeling_data except Exception as e: return {'ec_number': ec_number, 'error': str(e)} def export_kinetic_data(ec_number: str, format: str = 'csv', filename: str = None) -> str: """Export kinetic data to file.""" validate_dependencies() if not filename: filename = f"brenda_kinetic_data_{ec_number.replace('.', '_')}.{format}" try: # Get all kinetic data km_data = get_km_values(ec_number) time.sleep(0.5) # Rate limiting if not km_data: print(f"No kinetic data found for EC {ec_number}") return filename # Parse all entries parsed_data = [] for entry in km_data: parsed = parse_km_entry(entry) if parsed: parsed_data.append(parsed) # Export based on format if format.lower() == 'csv': if parsed_data: df = pd.DataFrame(parsed_data) df.to_csv(filename, index=False) else: with open(filename, 'w', newline='') as f: f.write('No data found') elif format.lower() == 'json': with open(filename, 'w') as f: json.dump(parsed_data, f, indent=2, default=str) elif format.lower() == 'excel': if parsed_data and PANDAS_AVAILABLE: df = pd.DataFrame(parsed_data) df.to_excel(filename, index=False) else: print("pandas required for Excel export") return filename print(f"Exported {len(parsed_data)} entries to {filename}") return filename except Exception as e: print(f"Error exporting data: {e}") return filename def search_by_pattern(pattern: str, limit: int = 50) -> List[Dict[str, Any]]: """Search enzymes using a reaction pattern or keyword.""" validate_dependencies() enzymes = [] try: # Search reactions containing the pattern reactions = get_reactions("*", reaction=f"*{pattern}*") time.sleep(0.5) # Rate limiting for entry in reactions[:limit]: parsed = parse_reaction_entry(entry) if parsed: enzymes.append({ 'ec_number': parsed.get('ecNumber', ''), 'organism': parsed.get('organism', ''), 'reaction': parsed.get('reaction', ''), 'reactants': parsed.get('reactants', []), 'products': parsed.get('products', []), 'commentary': parsed.get('commentary', '') }) except Exception as e: print(f"Error searching by pattern '{pattern}': {e}") return enzymes if __name__ == "__main__": # Example usage print("BRENDA Database Query Examples") print("=" * 40) try: # Example 1: Search enzymes by substrate print("\n1. Searching enzymes for 'glucose':") enzymes = search_enzymes_by_substrate("glucose", limit=5) for enzyme in enzymes: print(f" EC {enzyme['ec_number']}: {enzyme['organism']}") print(f" Km: {enzyme['km_value']}") # Example 2: Compare across organisms print("\n2. Comparing alcohol dehydrogenase (1.1.1.1) across organisms:") organisms = ["Escherichia coli", "Saccharomyces cerevisiae", "Homo sapiens"] comparison = compare_across_organisms("1.1.1.1", organisms) for comp in comparison: if comp.get('data_points', 0) > 0: print(f" {comp['organism']}:") print(f" Avg Km: {comp.get('average_km', 'N/A')}") print(f" Optimal pH: {comp.get('optimal_ph', 'N/A')}") # Example 3: Get environmental parameters print("\n3. Environmental parameters for 1.1.1.1:") params = get_environmental_parameters("1.1.1.1") if params.get('data_points', 0) > 0: print(f" pH range: {params.get('ph_range', 'N/A')}") print(f" Temperature range: {params.get('temperature_range', 'N/A')}") except Exception as e: print(f"Example failed: {e}")
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/brenda-database/scripts/brenda_queries.py", "license": "MIT License", "lines": 672, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/brenda-database/scripts/brenda_visualization.py
""" BRENDA Database Visualization Utilities This module provides visualization functions for BRENDA enzyme data, including kinetic parameters, environmental conditions, and pathway analysis. Key features: - Plot Km, kcat, and Vmax distributions - Compare enzyme properties across organisms - Visualize pH and temperature activity profiles - Plot substrate specificity and affinity data - Generate Michaelis-Menten curves - Create heatmaps and correlation plots - Support for pathway visualization Installation: uv pip install matplotlib seaborn pandas numpy Usage: from scripts.brenda_visualization import plot_kinetic_parameters, plot_michaelis_menten plot_kinetic_parameters("1.1.1.1") plot_michaelis_menten("1.1.1.1", substrate="ethanol") """ import math import numpy as np from typing import List, Dict, Any, Optional, Tuple import matplotlib.pyplot as plt import seaborn as sns from pathlib import Path try: import pandas as pd PANDAS_AVAILABLE = True except ImportError: print("Warning: pandas not installed. Install with: uv pip install pandas") PANDAS_AVAILABLE = False try: from brenda_queries import ( get_km_values, get_reactions, parse_km_entry, parse_reaction_entry, compare_across_organisms, get_environmental_parameters, get_substrate_specificity, get_modeling_parameters, search_enzymes_by_substrate, search_by_pattern ) BRENDA_QUERIES_AVAILABLE = True except ImportError: print("Warning: brenda_queries not available") BRENDA_QUERIES_AVAILABLE = False # Set style for plots plt.style.use('default') sns.set_palette("husl") def validate_dependencies(): """Validate that required dependencies are installed.""" missing = [] if not PANDAS_AVAILABLE: missing.append("pandas") if not BRENDA_QUERIES_AVAILABLE: missing.append("brenda_queries") if missing: raise ImportError(f"Missing required dependencies: {', '.join(missing)}") def plot_kinetic_parameters(ec_number: str, save_path: str = None, show_plot: bool = True) -> str: """Plot kinetic parameter distributions for an enzyme.""" validate_dependencies() try: # Get Km data km_data = get_km_values(ec_number) if not km_data: print(f"No kinetic data found for EC {ec_number}") return save_path # Parse data parsed_entries = [] for entry in km_data: parsed = parse_km_entry(entry) if 'km_value_numeric' in parsed: parsed_entries.append(parsed) if not parsed_entries: print(f"No numeric Km data found for EC {ec_number}") return save_path # Create figure with subplots fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 12)) fig.suptitle(f'Kinetic Parameters for EC {ec_number}', fontsize=16, fontweight='bold') # Extract data km_values = [entry['km_value_numeric'] for entry in parsed_entries] organisms = [entry.get('organism', 'Unknown') for entry in parsed_entries] substrates = [entry.get('substrate', 'Unknown') for entry in parsed_entries] # Plot 1: Km distribution histogram ax1.hist(km_values, bins=30, alpha=0.7, edgecolor='black') ax1.set_xlabel('Km (mM)') ax1.set_ylabel('Frequency') ax1.set_title('Km Value Distribution') ax1.axvline(np.mean(km_values), color='red', linestyle='--', label=f'Mean: {np.mean(km_values):.2f}') ax1.axvline(np.median(km_values), color='blue', linestyle='--', label=f'Median: {np.median(km_values):.2f}') ax1.legend() # Plot 2: Km by organism (top 10) if PANDAS_AVAILABLE: df = pd.DataFrame({'Km': km_values, 'Organism': organisms}) organism_means = df.groupby('Organism')['Km'].mean().sort_values(ascending=False).head(10) organism_means.plot(kind='bar', ax=ax2) ax2.set_ylabel('Mean Km (mM)') ax2.set_title('Mean Km by Organism (Top 10)') ax2.tick_params(axis='x', rotation=45) # Plot 3: Km by substrate (top 10) if PANDAS_AVAILABLE: df = pd.DataFrame({'Km': km_values, 'Substrate': substrates}) substrate_means = df.groupby('Substrate')['Km'].mean().sort_values(ascending=False).head(10) substrate_means.plot(kind='bar', ax=ax3) ax3.set_ylabel('Mean Km (mM)') ax3.set_title('Mean Km by Substrate (Top 10)') ax3.tick_params(axis='x', rotation=45) # Plot 4: Box plot by organism (top 5) if PANDAS_AVAILABLE: top_organisms = df.groupby('Organism')['Km'].count().sort_values(ascending=False).head(5).index top_data = df[df['Organism'].isin(top_organisms)] sns.boxplot(data=top_data, x='Organism', y='Km', ax=ax4) ax4.set_ylabel('Km (mM)') ax4.set_title('Km Distribution by Organism (Top 5)') ax4.tick_params(axis='x', rotation=45) plt.tight_layout() # Save plot if save_path: plt.savefig(save_path, dpi=300, bbox_inches='tight') print(f"Kinetic parameters plot saved to {save_path}") if show_plot: plt.show() else: plt.close() return save_path or f"kinetic_parameters_{ec_number.replace('.', '_')}.png" except Exception as e: print(f"Error plotting kinetic parameters: {e}") return save_path def plot_organism_comparison(ec_number: str, organisms: List[str], save_path: str = None, show_plot: bool = True) -> str: """Compare enzyme properties across multiple organisms.""" validate_dependencies() try: # Get comparison data comparison = compare_across_organisms(ec_number, organisms) if not comparison: print(f"No comparison data found for EC {ec_number}") return save_path # Filter out entries with no data valid_data = [c for c in comparison if c.get('data_points', 0) > 0] if not valid_data: print(f"No valid data for organism comparison of EC {ec_number}") return save_path # Create figure fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 12)) fig.suptitle(f'Organism Comparison for EC {ec_number}', fontsize=16, fontweight='bold') # Extract data names = [c['organism'] for c in valid_data] avg_kms = [c.get('average_km', 0) for c in valid_data if c.get('average_km')] optimal_phs = [c.get('optimal_ph', 0) for c in valid_data if c.get('optimal_ph')] optimal_temps = [c.get('optimal_temperature', 0) for c in valid_data if c.get('optimal_temperature')] data_points = [c.get('data_points', 0) for c in valid_data] # Plot 1: Average Km comparison if avg_kms: ax1.bar(names, avg_kms) ax1.set_ylabel('Average Km (mM)') ax1.set_title('Average Km Comparison') ax1.tick_params(axis='x', rotation=45) # Plot 2: Optimal pH comparison if optimal_phs: ax2.bar(names, optimal_phs) ax2.set_ylabel('Optimal pH') ax2.set_title('Optimal pH Comparison') ax2.tick_params(axis='x', rotation=45) # Plot 3: Optimal temperature comparison if optimal_temps: ax3.bar(names, optimal_temps) ax3.set_ylabel('Optimal Temperature (°C)') ax3.set_title('Optimal Temperature Comparison') ax3.tick_params(axis='x', rotation=45) # Plot 4: Data points comparison ax4.bar(names, data_points) ax4.set_ylabel('Number of Data Points') ax4.set_title('Available Data Points') ax4.tick_params(axis='x', rotation=45) plt.tight_layout() # Save plot if save_path: plt.savefig(save_path, dpi=300, bbox_inches='tight') print(f"Organism comparison plot saved to {save_path}") if show_plot: plt.show() else: plt.close() return save_path or f"organism_comparison_{ec_number.replace('.', '_')}.png" except Exception as e: print(f"Error plotting organism comparison: {e}") return save_path def plot_pH_profiles(ec_number: str, save_path: str = None, show_plot: bool = True) -> str: """Plot pH activity profiles for an enzyme.""" validate_dependencies() try: # Get kinetic data km_data = get_km_values(ec_number) if not km_data: print(f"No pH data found for EC {ec_number}") return save_path # Parse data and extract pH information ph_kms = [] ph_organisms = [] for entry in km_data: parsed = parse_km_entry(entry) if 'ph' in parsed and 'km_value_numeric' in parsed: ph_kms.append((parsed['ph'], parsed['km_value_numeric'])) ph_organisms.append(parsed.get('organism', 'Unknown')) if not ph_kms: print(f"No pH-Km data found for EC {ec_number}") return save_path # Create figure fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6)) fig.suptitle(f'pH Activity Profiles for EC {ec_number}', fontsize=16, fontweight='bold') # Extract data ph_values = [item[0] for item in ph_kms] km_values = [item[1] for item in ph_kms] # Plot 1: pH vs Km scatter plot scatter = ax1.scatter(ph_values, km_values, alpha=0.6, s=50) ax1.set_xlabel('pH') ax1.set_ylabel('Km (mM)') ax1.set_title('pH vs Km Values') ax1.grid(True, alpha=0.3) # Add trend line if len(ph_values) > 2: z = np.polyfit(ph_values, km_values, 1) p = np.poly1d(z) ax1.plot(ph_values, p(ph_values), "r--", alpha=0.8, label=f'Trend: y={z[0]:.3f}x+{z[1]:.3f}') ax1.legend() # Plot 2: pH distribution histogram ax2.hist(ph_values, bins=20, alpha=0.7, edgecolor='black') ax2.set_xlabel('pH') ax2.set_ylabel('Frequency') ax2.set_title('pH Distribution') ax2.axvline(np.mean(ph_values), color='red', linestyle='--', label=f'Mean: {np.mean(ph_values):.2f}') ax2.axvline(np.median(ph_values), color='blue', linestyle='--', label=f'Median: {np.median(ph_values):.2f}') ax2.legend() plt.tight_layout() # Save plot if save_path: plt.savefig(save_path, dpi=300, bbox_inches='tight') print(f"pH profile plot saved to {save_path}") if show_plot: plt.show() else: plt.close() return save_path or f"ph_profile_{ec_number.replace('.', '_')}.png" except Exception as e: print(f"Error plotting pH profiles: {e}") return save_path def plot_temperature_profiles(ec_number: str, save_path: str = None, show_plot: bool = True) -> str: """Plot temperature activity profiles for an enzyme.""" validate_dependencies() try: # Get kinetic data km_data = get_km_values(ec_number) if not km_data: print(f"No temperature data found for EC {ec_number}") return save_path # Parse data and extract temperature information temp_kms = [] temp_organisms = [] for entry in km_data: parsed = parse_km_entry(entry) if 'temperature' in parsed and 'km_value_numeric' in parsed: temp_kms.append((parsed['temperature'], parsed['km_value_numeric'])) temp_organisms.append(parsed.get('organism', 'Unknown')) if not temp_kms: print(f"No temperature-Km data found for EC {ec_number}") return save_path # Create figure fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6)) fig.suptitle(f'Temperature Activity Profiles for EC {ec_number}', fontsize=16, fontweight='bold') # Extract data temp_values = [item[0] for item in temp_kms] km_values = [item[1] for item in temp_kms] # Plot 1: Temperature vs Km scatter plot scatter = ax1.scatter(temp_values, km_values, alpha=0.6, s=50) ax1.set_xlabel('Temperature (°C)') ax1.set_ylabel('Km (mM)') ax1.set_title('Temperature vs Km Values') ax1.grid(True, alpha=0.3) # Add trend line if len(temp_values) > 2: z = np.polyfit(temp_values, km_values, 2) # Quadratic fit for temperature optima p = np.poly1d(z) x_smooth = np.linspace(min(temp_values), max(temp_values), 100) ax1.plot(x_smooth, p(x_smooth), "r--", alpha=0.8, label='Polynomial fit') # Find optimum temperature optimum_idx = np.argmin(p(x_smooth)) optimum_temp = x_smooth[optimum_idx] ax1.axvline(optimum_temp, color='green', linestyle=':', label=f'Optimal: {optimum_temp:.1f}°C') ax1.legend() # Plot 2: Temperature distribution histogram ax2.hist(temp_values, bins=20, alpha=0.7, edgecolor='black') ax2.set_xlabel('Temperature (°C)') ax2.set_ylabel('Frequency') ax2.set_title('Temperature Distribution') ax2.axvline(np.mean(temp_values), color='red', linestyle='--', label=f'Mean: {np.mean(temp_values):.1f}°C') ax2.axvline(np.median(temp_values), color='blue', linestyle='--', label=f'Median: {np.median(temp_values):.1f}°C') ax2.legend() plt.tight_layout() # Save plot if save_path: plt.savefig(save_path, dpi=300, bbox_inches='tight') print(f"Temperature profile plot saved to {save_path}") if show_plot: plt.show() else: plt.close() return save_path or f"temperature_profile_{ec_number.replace('.', '_')}.png" except Exception as e: print(f"Error plotting temperature profiles: {e}") return save_path def plot_substrate_specificity(ec_number: str, save_path: str = None, show_plot: bool = True) -> str: """Plot substrate specificity and affinity for an enzyme.""" validate_dependencies() try: # Get substrate specificity data specificity = get_substrate_specificity(ec_number) if not specificity: print(f"No substrate specificity data found for EC {ec_number}") return save_path # Create figure fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 12)) fig.suptitle(f'Substrate Specificity for EC {ec_number}', fontsize=16, fontweight='bold') # Extract data substrates = [s['name'] for s in specificity] kms = [s['km'] for s in specificity if s.get('km')] data_points = [s['data_points'] for s in specificity] # Get top substrates for plotting if PANDAS_AVAILABLE and kms: df = pd.DataFrame({'Substrate': substrates, 'Km': kms, 'DataPoints': data_points}) top_substrates = df.nlargest(15, 'DataPoints') # Top 15 by data points # Plot 1: Km values for top substrates (sorted by affinity) top_sorted = top_substrates.sort_values('Km') ax1.barh(range(len(top_sorted)), top_sorted['Km']) ax1.set_yticks(range(len(top_sorted))) ax1.set_yticklabels([s[:30] + '...' if len(s) > 30 else s for s in top_sorted['Substrate']]) ax1.set_xlabel('Km (mM)') ax1.set_title('Substrate Affinity (Lower Km = Higher Affinity)') ax1.invert_yaxis() # Best affinity at top # Plot 2: Data points by substrate ax2.barh(range(len(top_sorted)), top_sorted['DataPoints']) ax2.set_yticks(range(len(top_sorted))) ax2.set_yticklabels([s[:30] + '...' if len(s) > 30 else s for s in top_sorted['Substrate']]) ax2.set_xlabel('Number of Data Points') ax2.set_title('Data Availability by Substrate') ax2.invert_yaxis() # Plot 3: Km distribution ax3.hist(kms, bins=20, alpha=0.7, edgecolor='black') ax3.set_xlabel('Km (mM)') ax3.set_ylabel('Frequency') ax3.set_title('Km Value Distribution') ax3.axvline(np.mean(kms), color='red', linestyle='--', label=f'Mean: {np.mean(kms):.2f}') ax3.axvline(np.median(kms), color='blue', linestyle='--', label=f'Median: {np.median(kms):.2f}') ax3.legend() # Plot 4: Km vs Data Points scatter ax4.scatter(df['DataPoints'], df['Km'], alpha=0.6) ax4.set_xlabel('Number of Data Points') ax4.set_ylabel('Km (mM)') ax4.set_title('Km vs Data Points') ax4.grid(True, alpha=0.3) plt.tight_layout() # Save plot if save_path: plt.savefig(save_path, dpi=300, bbox_inches='tight') print(f"Substrate specificity plot saved to {save_path}") if show_plot: plt.show() else: plt.close() return save_path or f"substrate_specificity_{ec_number.replace('.', '_')}.png" except Exception as e: print(f"Error plotting substrate specificity: {e}") return save_path def plot_michaelis_menten(ec_number: str, substrate: str = None, save_path: str = None, show_plot: bool = True) -> str: """Generate Michaelis-Menten curves for an enzyme.""" validate_dependencies() try: # Get modeling parameters model_data = get_modeling_parameters(ec_number, substrate) if not model_data or model_data.get('error'): print(f"No modeling data found for EC {ec_number}") return save_path km = model_data.get('km') vmax = model_data.get('vmax') kcat = model_data.get('kcat') enzyme_conc = model_data.get('enzyme_conc', 1.0) if not km: print(f"No Km data available for plotting") return save_path # Create figure fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6)) fig.suptitle(f'Michaelis-Menten Kinetics for EC {ec_number}' + (f' - {substrate}' if substrate else ''), fontsize=16, fontweight='bold') # Generate substrate concentration range substrate_range = np.linspace(0, km * 5, 1000) # Calculate reaction rates if vmax: # Use actual Vmax if available rates = (vmax * substrate_range) / (km + substrate_range) elif kcat and enzyme_conc: # Calculate Vmax from kcat and enzyme concentration vmax_calc = kcat * enzyme_conc rates = (vmax_calc * substrate_range) / (km + substrate_range) else: # Use normalized Vmax = 1.0 rates = substrate_range / (km + substrate_range) # Plot 1: Michaelis-Menten curve ax1.plot(substrate_range, rates, 'b-', linewidth=2, label='Michaelis-Menten') ax1.axhline(y=rates[-1] * 0.5, color='r', linestyle='--', alpha=0.7, label='0.5 × Vmax') ax1.axvline(x=km, color='g', linestyle='--', alpha=0.7, label=f'Km = {km:.2f}') ax1.set_xlabel('Substrate Concentration (mM)') ax1.set_ylabel('Reaction Rate') ax1.set_title('Michaelis-Menten Curve') ax1.legend() ax1.grid(True, alpha=0.3) # Add annotation for Km km_rate = (substrate_range[km == min(substrate_range, key=lambda x: abs(x-km))] * (vmax if vmax else kcat * enzyme_conc if kcat else 1.0)) / (km + substrate_range[km == min(substrate_range, key=lambda x: abs(x-km))]) ax1.plot(km, km_rate, 'ro', markersize=8) # Plot 2: Lineweaver-Burk plot (double reciprocal) substrate_range_nonzero = substrate_range[substrate_range > 0] rates_nonzero = rates[substrate_range > 0] reciprocal_substrate = 1 / substrate_range_nonzero reciprocal_rate = 1 / rates_nonzero ax2.scatter(reciprocal_substrate, reciprocal_rate, alpha=0.6, s=10) # Fit linear regression z = np.polyfit(reciprocal_substrate, reciprocal_rate, 1) p = np.poly1d(z) x_fit = np.linspace(min(reciprocal_substrate), max(reciprocal_substrate), 100) ax2.plot(x_fit, p(x_fit), 'r-', linewidth=2, label=f'1/Vmax = {z[1]:.3f}') ax2.set_xlabel('1/[Substrate] (1/mM)') ax2.set_ylabel('1/Rate') ax2.set_title('Lineweaver-Burk Plot') ax2.legend() ax2.grid(True, alpha=0.3) # Add parameter information info_text = f"Km = {km:.3f} mM" if vmax: info_text += f"\nVmax = {vmax:.3f}" if kcat: info_text += f"\nkcat = {kcat:.3f} s⁻¹" if enzyme_conc: info_text += f"\n[Enzyme] = {enzyme_conc:.3f} μM" fig.text(0.02, 0.98, info_text, transform=fig.transFigure, fontsize=10, verticalalignment='top', bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.8)) plt.tight_layout() # Save plot if save_path: plt.savefig(save_path, dpi=300, bbox_inches='tight') print(f"Michaelis-Menten plot saved to {save_path}") if show_plot: plt.show() else: plt.close() return save_path or f"michaelis_menten_{ec_number.replace('.', '_')}_{substrate or 'all'}.png" except Exception as e: print(f"Error plotting Michaelis-Menten: {e}") return save_path def create_heatmap_data(ec_number: str, parameters: List[str] = None) -> Dict[str, Any]: """Create data for heatmap visualization.""" validate_dependencies() try: # Get comparison data across organisms organisms = ["Escherichia coli", "Saccharomyces cerevisiae", "Bacillus subtilis", "Homo sapiens", "Mus musculus", "Rattus norvegicus"] comparison = compare_across_organisms(ec_number, organisms) if not comparison: return None # Create heatmap data heatmap_data = { 'organisms': [], 'average_km': [], 'optimal_ph': [], 'optimal_temperature': [], 'data_points': [] } for comp in comparison: if comp.get('data_points', 0) > 0: heatmap_data['organisms'].append(comp['organism']) heatmap_data['average_km'].append(comp.get('average_km', 0)) heatmap_data['optimal_ph'].append(comp.get('optimal_ph', 0)) heatmap_data['optimal_temperature'].append(comp.get('optimal_temperature', 0)) heatmap_data['data_points'].append(comp.get('data_points', 0)) return heatmap_data except Exception as e: print(f"Error creating heatmap data: {e}") return None def plot_heatmap(ec_number: str, save_path: str = None, show_plot: bool = True) -> str: """Create heatmap visualization of enzyme properties.""" validate_dependencies() try: heatmap_data = create_heatmap_data(ec_number) if not heatmap_data or not heatmap_data['organisms']: print(f"No heatmap data available for EC {ec_number}") return save_path if not PANDAS_AVAILABLE: print("pandas required for heatmap plotting") return save_path # Create DataFrame for heatmap df = pd.DataFrame({ 'Organism': heatmap_data['organisms'], 'Avg Km (mM)': heatmap_data['average_km'], 'Optimal pH': heatmap_data['optimal_ph'], 'Optimal Temp (°C)': heatmap_data['optimal_temperature'], 'Data Points': heatmap_data['data_points'] }) # Normalize data for better visualization df_normalized = df.copy() for col in ['Avg Km (mM)', 'Optimal pH', 'Optimal Temp (°C)', 'Data Points']: if col in df.columns: df_normalized[col] = (df[col] - df[col].min()) / (df[col].max() - df[col].min()) # Create figure fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 8)) fig.suptitle(f'Enzyme Properties Heatmap for EC {ec_number}', fontsize=16, fontweight='bold') # Plot 1: Raw data heatmap heatmap_data_raw = df.set_index('Organism')[['Avg Km (mM)', 'Optimal pH', 'Optimal Temp (°C)', 'Data Points']].T sns.heatmap(heatmap_data_raw, annot=True, fmt='.2f', cmap='viridis', ax=ax1) ax1.set_title('Raw Values') # Plot 2: Normalized data heatmap heatmap_data_norm = df_normalized.set_index('Organism')[['Avg Km (mM)', 'Optimal pH', 'Optimal Temp (°C)', 'Data Points']].T sns.heatmap(heatmap_data_norm, annot=True, fmt='.2f', cmap='viridis', ax=ax2) ax2.set_title('Normalized Values (0-1)') plt.tight_layout() # Save plot if save_path: plt.savefig(save_path, dpi=300, bbox_inches='tight') print(f"Heatmap plot saved to {save_path}") if show_plot: plt.show() else: plt.close() return save_path or f"heatmap_{ec_number.replace('.', '_')}.png" except Exception as e: print(f"Error plotting heatmap: {e}") return save_path def generate_summary_plots(ec_number: str, save_dir: str = None) -> List[str]: """Generate a comprehensive set of plots for an enzyme.""" validate_dependencies() if save_dir is None: save_dir = f"enzyme_plots_{ec_number.replace('.', '_')}" # Create save directory Path(save_dir).mkdir(exist_ok=True) generated_files = [] # Generate all plot types plot_functions = [ ('kinetic_parameters', plot_kinetic_parameters), ('ph_profiles', plot_pH_profiles), ('temperature_profiles', plot_temperature_profiles), ('substrate_specificity', plot_substrate_specificity), ('heatmap', plot_heatmap), ] for plot_name, plot_func in plot_functions: try: save_path = f"{save_dir}/{plot_name}_{ec_number.replace('.', '_')}.png" result_path = plot_func(ec_number, save_path=save_path, show_plot=False) if result_path: generated_files.append(result_path) print(f"Generated {plot_name} plot") else: print(f"Failed to generate {plot_name} plot") except Exception as e: print(f"Error generating {plot_name} plot: {e}") # Generate organism comparison for common model organisms model_organisms = ["Escherichia coli", "Saccharomyces cerevisiae", "Homo sapiens"] try: save_path = f"{save_dir}/organism_comparison_{ec_number.replace('.', '_')}.png" result_path = plot_organism_comparison(ec_number, model_organisms, save_path=save_path, show_plot=False) if result_path: generated_files.append(result_path) print("Generated organism comparison plot") except Exception as e: print(f"Error generating organism comparison plot: {e}") # Generate Michaelis-Menten plot for most common substrate try: specificity = get_substrate_specificity(ec_number) if specificity: most_common = max(specificity, key=lambda x: x.get('data_points', 0)) substrate_name = most_common['name'].split()[0] # Take first word save_path = f"{save_dir}/michaelis_menten_{ec_number.replace('.', '_')}_{substrate_name}.png" result_path = plot_michaelis_menten(ec_number, substrate_name, save_path=save_path, show_plot=False) if result_path: generated_files.append(result_path) print(f"Generated Michaelis-Menten plot for {substrate_name}") except Exception as e: print(f"Error generating Michaelis-Menten plot: {e}") print(f"\nGenerated {len(generated_files)} plots in directory: {save_dir}") return generated_files if __name__ == "__main__": # Example usage print("BRENDA Visualization Examples") print("=" * 40) try: ec_number = "1.1.1.1" # Alcohol dehydrogenase print(f"\n1. Generating kinetic parameters plot for EC {ec_number}") plot_kinetic_parameters(ec_number, show_plot=False) print(f"\n2. Generating pH profile plot for EC {ec_number}") plot_pH_profiles(ec_number, show_plot=False) print(f"\n3. Generating substrate specificity plot for EC {ec_number}") plot_substrate_specificity(ec_number, show_plot=False) print(f"\n4. Generating Michaelis-Menten plot for EC {ec_number}") plot_michaelis_menten(ec_number, substrate="ethanol", show_plot=False) print(f"\n5. Generating organism comparison plot for EC {ec_number}") organisms = ["Escherichia coli", "Saccharomyces cerevisiae", "Homo sapiens"] plot_organism_comparison(ec_number, organisms, show_plot=False) print(f"\n6. Generating comprehensive summary plots for EC {ec_number}") summary_files = generate_summary_plots(ec_number, show_plot=False) print(f"Generated {len(summary_files)} summary plots") except Exception as e: print(f"Example failed: {e}")
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/brenda-database/scripts/brenda_visualization.py", "license": "MIT License", "lines": 606, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/brenda-database/scripts/enzyme_pathway_builder.py
""" Enzyme Pathway Builder for Retrosynthetic Analysis This module provides tools for constructing enzymatic pathways and retrosynthetic trees using BRENDA database information. Key features: - Find enzymatic pathways for target products - Build retrosynthetic trees from products - Suggest enzyme substitutions and alternatives - Calculate pathway feasibility and thermodynamics - Optimize pathway conditions (pH, temperature, cofactors) - Generate detailed pathway reports - Support for metabolic engineering and synthetic biology Installation: uv pip install networkx matplotlib pandas Usage: from scripts.enzyme_pathway_builder import find_pathway_for_product, build_retrosynthetic_tree pathway = find_pathway_for_product("lactate", max_steps=3) tree = build_retrosynthetic_tree("lactate", depth=2) """ import re import json import time from typing import List, Dict, Any, Optional, Set, Tuple from pathlib import Path try: import networkx as nx NETWORKX_AVAILABLE = True except ImportError: print("Warning: networkx not installed. Install with: uv pip install networkx") NETWORKX_AVAILABLE = False try: import pandas as pd PANDAS_AVAILABLE = True except ImportError: print("Warning: pandas not installed. Install with: uv pip install pandas") PANDAS_AVAILABLE = False try: import matplotlib.pyplot as plt MATPLOTLIB_AVAILABLE = True except ImportError: print("Warning: matplotlib not installed. Install with: uv pip install matplotlib") MATPLOTLIB_AVAILABLE = False try: from brenda_queries import ( search_enzymes_by_product, search_enzymes_by_substrate, get_environmental_parameters, compare_across_organisms, get_substrate_specificity, get_cofactor_requirements, find_thermophilic_homologs, find_ph_stable_variants ) BRENDA_QUERIES_AVAILABLE = True except ImportError: print("Warning: brenda_queries not available") BRENDA_QUERIES_AVAILABLE = False def validate_dependencies(): """Validate that required dependencies are installed.""" missing = [] if not NETWORKX_AVAILABLE: missing.append("networkx") if not PANDAS_AVAILABLE: missing.append("pandas") if not BRENDA_QUERIES_AVAILABLE: missing.append("brenda_queries") if missing: raise ImportError(f"Missing required dependencies: {', '.join(missing)}") # Common biochemical transformations with typical EC numbers COMMON_TRANSFORMATIONS = { 'oxidation': ['1.1.1'], # Alcohol dehydrogenases 'reduction': ['1.1.1'], # Alcohol dehydrogenases 'hydrolysis': ['3.1.1', '3.1.3'], # Esterases, phosphatases 'carboxylation': ['6.4.1'], # Carboxylases 'decarboxylation': ['4.1.1'], # Decarboxylases 'transamination': ['2.6.1'], # Aminotransferases 'phosphorylation': ['2.7.1'], # Kinases 'dephosphorylation': ['3.1.3'], # Phosphatases 'isomerization': ['5.1.1', '5.3.1'], # Isomerases 'ligation': ['6.3.1'], # Ligases 'transfer': ['2.1.1', '2.2.1', '2.4.1'], # Transferases 'hydride_transfer': ['1.1.1', '1.2.1'], # Oxidoreductases 'group_transfer': ['2.1.1'], # Methyltransferases } # Simple metabolite database (expanded for pathway building) METABOLITE_DATABASE = { # Primary metabolites 'glucose': {'formula': 'C6H12O6', 'mw': 180.16, 'class': 'sugar'}, 'fructose': {'formula': 'C6H12O6', 'mw': 180.16, 'class': 'sugar'}, 'galactose': {'formula': 'C6H12O6', 'mw': 180.16, 'class': 'sugar'}, 'pyruvate': {'formula': 'C3H4O3', 'mw': 90.08, 'class': 'carboxylic_acid'}, 'lactate': {'formula': 'C3H6O3', 'mw': 90.08, 'class': 'carboxylic_acid'}, 'acetate': {'formula': 'C2H4O2', 'mw': 60.05, 'class': 'carboxylic_acid'}, 'ethanol': {'formula': 'C2H6O', 'mw': 46.07, 'class': 'alcohol'}, 'acetaldehyde': {'formula': 'C2H4O', 'mw': 44.05, 'class': 'aldehyde'}, 'acetone': {'formula': 'C3H6O', 'mw': 58.08, 'class': 'ketone'}, 'glycerol': {'formula': 'C3H8O3', 'mw': 92.09, 'class': 'alcohol'}, 'ammonia': {'formula': 'NH3', 'mw': 17.03, 'class': 'inorganic'}, 'carbon dioxide': {'formula': 'CO2', 'mw': 44.01, 'class': 'inorganic'}, 'water': {'formula': 'H2O', 'mw': 18.02, 'class': 'inorganic'}, 'oxygen': {'formula': 'O2', 'mw': 32.00, 'class': 'inorganic'}, 'hydrogen': {'formula': 'H2', 'mw': 2.02, 'class': 'inorganic'}, 'nitrogen': {'formula': 'N2', 'mw': 28.01, 'class': 'inorganic'}, 'phosphate': {'formula': 'PO4', 'mw': 94.97, 'class': 'inorganic'}, 'sulfate': {'formula': 'SO4', 'mw': 96.06, 'class': 'inorganic'}, # Amino acids 'alanine': {'formula': 'C3H7NO2', 'mw': 89.09, 'class': 'amino_acid'}, 'glycine': {'formula': 'C2H5NO2', 'mw': 75.07, 'class': 'amino_acid'}, 'serine': {'formula': 'C3H7NO3', 'mw': 105.09, 'class': 'amino_acid'}, 'threonine': {'formula': 'C4H9NO3', 'mw': 119.12, 'class': 'amino_acid'}, 'aspartate': {'formula': 'C4H7NO4', 'mw': 133.10, 'class': 'amino_acid'}, 'glutamate': {'formula': 'C5H9NO4', 'mw': 147.13, 'class': 'amino_acid'}, 'asparagine': {'formula': 'C4H8N2O3', 'mw': 132.12, 'class': 'amino_acid'}, 'glutamine': {'formula': 'C5H10N2O3', 'mw': 146.15, 'class': 'amino_acid'}, 'lysine': {'formula': 'C6H14N2O2', 'mw': 146.19, 'class': 'amino_acid'}, 'arginine': {'formula': 'C6H14N4O2', 'mw': 174.20, 'class': 'amino_acid'}, 'histidine': {'formula': 'C6H9N3O2', 'mw': 155.16, 'class': 'amino_acid'}, 'phenylalanine': {'formula': 'C9H11NO2', 'mw': 165.19, 'class': 'amino_acid'}, 'tyrosine': {'formula': 'C9H11NO3', 'mw': 181.19, 'class': 'amino_acid'}, 'tryptophan': {'formula': 'C11H12N2O2', 'mw': 204.23, 'class': 'amino_acid'}, 'leucine': {'formula': 'C6H13NO2', 'mw': 131.18, 'class': 'amino_acid'}, 'isoleucine': {'formula': 'C6H13NO2', 'mw': 131.18, 'class': 'amino_acid'}, 'valine': {'formula': 'C5H11NO2', 'mw': 117.15, 'class': 'amino_acid'}, 'methionine': {'formula': 'C5H11NO2S', 'mw': 149.21, 'class': 'amino_acid'}, 'cysteine': {'formula': 'C3H7NO2S', 'mw': 121.16, 'class': 'amino_acid'}, 'proline': {'formula': 'C5H9NO2', 'mw': 115.13, 'class': 'amino_acid'}, # Nucleotides (simplified) 'atp': {'formula': 'C10H16N5O13P3', 'mw': 507.18, 'class': 'nucleotide'}, 'adp': {'formula': 'C10H15N5O10P2', 'mw': 427.20, 'class': 'nucleotide'}, 'amp': {'formula': 'C10H14N5O7P', 'mw': 347.22, 'class': 'nucleotide'}, 'nad': {'formula': 'C21H27N7O14P2', 'mw': 663.43, 'class': 'cofactor'}, 'nadh': {'formula': 'C21H29N7O14P2', 'mw': 665.44, 'class': 'cofactor'}, 'nadp': {'formula': 'C21H28N7O17P3', 'mw': 743.44, 'class': 'cofactor'}, 'nadph': {'formula': 'C21H30N7O17P3', 'mw': 745.45, 'class': 'cofactor'}, 'fadh2': {'formula': 'C21H30N7O14P2', 'mw': 785.55, 'class': 'cofactor'}, 'fadx': {'formula': 'C21H20N4O2', 'mw': 350.36, 'class': 'cofactor'}, # Common organic acids 'malate': {'formula': 'C4H6O5', 'mw': 134.09, 'class': 'carboxylic_acid'}, 'oxaloacetate': {'formula': 'C4H4O5', 'mw': 132.07, 'class': 'carboxylic_acid'}, 'succinate': {'formula': 'C4H6O4', 'mw': 118.09, 'class': 'carboxylic_acid'}, 'fumarate': {'formula': 'C4H4O4', 'mw': 116.07, 'class': 'carboxylic_acid'}, 'oxalosuccinate': {'formula': 'C6H6O7', 'mw': 190.12, 'class': 'carboxylic_acid'}, 'alpha-ketoglutarate': {'formula': 'C5H6O5', 'mw': 146.11, 'class': 'carboxylic_acid'}, # Energy carriers 'acetyl-coa': {'formula': 'C23H38N7O17P3S', 'mw': 809.51, 'class': 'cofactor'}, 'coenzyme-a': {'formula': 'C21H36N7O16P3S', 'mw': 767.54, 'class': 'cofactor'}, } # Common cofactors and their roles COFACTOR_ROLES = { 'nad+': {'role': 'oxidation', 'oxidation_state': '+1'}, 'nadh': {'role': 'reduction', 'oxidation_state': '0'}, 'nadp+': {'role': 'oxidation', 'oxidation_state': '+1'}, 'nadph': {'role': 'reduction', 'oxidation_state': '0'}, 'fadx': {'role': 'oxidation', 'oxidation_state': '0'}, 'fadh2': {'role': 'reduction', 'oxidation_state': '-2'}, 'atp': {'role': 'phosphorylation', 'oxidation_state': '0'}, 'adp': {'role': 'energy', 'oxidation_state': '0'}, 'amp': {'role': 'energy', 'oxidation_state': '0'}, 'acetyl-coa': {'role': 'acetylation', 'oxidation_state': '0'}, 'coenzyme-a': {'role': 'thiolation', 'oxidation_state': '0'}, } def identify_metabolite(metabolite_name: str) -> Dict[str, Any]: """Identify a metabolite from the database or create entry.""" metabolite_name = metabolite_name.lower().strip() # Check if it's in the database if metabolite_name in METABOLITE_DATABASE: return {'name': metabolite_name, **METABOLITE_DATABASE[metabolite_name]} # Simple formula extraction from common patterns formula_patterns = { r'c(\d+)h(\d+)o(\d+)': lambda m: f"C{m[0]}H{m[1]}O{m[2]}", r'c(\d+)h(\d+)n(\d+)o(\d+)': lambda m: f"C{m[0]}H{m[1]}N{m[2]}O{m[3]}", } for pattern, formatter in formula_patterns.items(): match = re.search(pattern, metabolite_name) if match: formula = formatter(match.groups()) # Estimate molecular weight (C=12, H=1, N=14, O=16) mw = 0 elements = re.findall(r'([A-Z])(\d*)', formula) for elem, count in elements: count = int(count) if count else 1 if elem == 'C': mw += count * 12.01 elif elem == 'H': mw += count * 1.008 elif elem == 'N': mw += count * 14.01 elif elem == 'O': mw += count * 16.00 elif elem == 'P': mw += count * 30.97 elif elem == 'S': mw += count * 32.07 return { 'name': metabolite_name, 'formula': formula, 'mw': mw, 'class': 'unknown' } # Fallback - unknown metabolite return { 'name': metabolite_name, 'formula': 'Unknown', 'mw': 0, 'class': 'unknown' } def infer_transformation_type(substrate: str, product: str) -> List[str]: """Infer the type of transformation based on substrate and product.""" substrate_info = identify_metabolite(substrate) product_info = identify_metabolite(product) transformations = [] # Check for oxidation/reduction patterns if 'alcohol' in substrate_info.get('class', '') and 'carboxylic_acid' in product_info.get('class', ''): transformations.append('oxidation') elif 'aldehyde' in substrate_info.get('class', '') and 'alcohol' in product_info.get('class', ''): transformations.append('reduction') elif 'alcohol' in substrate_info.get('class', '') and 'aldehyde' in product_info.get('class', ''): transformations.append('oxidation') # Check for phosphorylation/dephosphorylation if 'phosphate' in product and 'phosphate' not in substrate: transformations.append('phosphorylation') elif 'phosphate' in substrate and 'phosphate' not in product: transformations.append('dephosphorylation') # Check for carboxylation/decarboxylation if 'co2' in product and 'co2' not in substrate: transformations.append('carboxylation') elif 'co2' in substrate and 'co2' not in product: transformations.append('decarboxylation') # Check for hydrolysis (simple heuristic) if 'ester' in substrate.lower() and ('carboxylic_acid' in product_info.get('class', '') or 'alcohol' in product_info.get('class', '')): transformations.append('hydrolysis') # Check for transamination if 'amino_acid' in product_info.get('class', '') and 'amino_acid' not in substrate_info.get('class', ''): transformations.append('transamination') # Default to generic transformation if not transformations: transformations.append('generic') return transformations def find_enzymes_for_transformation(substrate: str, product: str, limit: int = 10) -> List[Dict[str, Any]]: """Find enzymes that catalyze a specific transformation.""" validate_dependencies() # Infer transformation types transformations = infer_transformation_type(substrate, product) all_enzymes = [] # Try to find enzymes by product try: product_enzymes = search_enzymes_by_product(product, limit=limit) for enzyme in product_enzymes: # Check if substrate is in the reactants if substrate.lower() in enzyme.get('reaction', '').lower(): enzyme['transformation'] = transformations[0] if transformations else 'generic' enzyme['substrate'] = substrate enzyme['product'] = product enzyme['confidence'] = 'high' all_enzymes.append(enzyme) time.sleep(0.5) # Rate limiting except Exception as e: print(f"Error searching enzymes by product: {e}") # Try to find enzymes by substrate try: substrate_enzymes = search_enzymes_by_substrate(substrate, limit=limit) for enzyme in substrate_enzymes: # Check if product is mentioned in substrate data (limited approach) enzyme['transformation'] = transformations[0] if transformations else 'generic' enzyme['substrate'] = substrate enzyme['product'] = product enzyme['confidence'] = 'medium' all_enzymes.append(enzyme) time.sleep(0.5) # Rate limiting except Exception as e: print(f"Error searching enzymes by substrate: {e}") # If no enzymes found, try common EC numbers for transformation types if not all_enzymes and transformations: for trans_type in transformations: if trans_type in COMMON_TRANSFORMATIONS: for ec_prefix in COMMON_TRANSFORMATIONS[trans_type]: # This is a simplified approach - in practice you'd want # to query the specific EC numbers with more detail try: generic_enzymes = search_by_pattern(trans_type, limit=5) for enzyme in generic_enzymes: enzyme['transformation'] = trans_type enzyme['substrate'] = substrate enzyme['product'] = product enzyme['confidence'] = 'low' all_enzymes.append(enzyme) time.sleep(0.5) break except Exception as e: print(f"Error searching for transformation type {trans_type}: {e}") # Remove duplicates and sort by confidence unique_enzymes = [] seen = set() for enzyme in all_enzymes: key = (enzyme.get('ec_number', ''), enzyme.get('organism', '')) if key not in seen: seen.add(key) unique_enzymes.append(enzyme) # Sort by confidence (high > medium > low) confidence_order = {'high': 3, 'medium': 2, 'low': 1} unique_enzymes.sort(key=lambda x: confidence_order.get(x.get('confidence', 'low'), 0), reverse=True) return unique_enzymes[:limit] def find_pathway_for_product(product: str, max_steps: int = 3, starting_materials: List[str] = None) -> Dict[str, Any]: """Find enzymatic pathways to synthesize a target product.""" validate_dependencies() if starting_materials is None: # Common starting materials starting_materials = ['glucose', 'pyruvate', 'acetate', 'ethanol', 'glycerol'] pathway = { 'target': product, 'max_steps': max_steps, 'starting_materials': starting_materials, 'steps': [], 'alternative_pathways': [], 'warnings': [], 'confidence': 0 } # Simple breadth-first search for pathway from collections import deque queue = deque([(product, 0, [product])]) # (current_metabolite, step_count, pathway) visited = set() while queue and len(pathway['steps']) == 0: current_metabolite, step_count, current_path = queue.popleft() if current_metabolite in visited or step_count >= max_steps: continue visited.add(current_metabolite) # Check if current metabolite is a starting material if current_metabolite.lower() in [sm.lower() for sm in starting_materials]: # Found a complete pathway pathway['steps'] = [] for i in range(len(current_path) - 1): substrate = current_path[i + 1] product_step = current_path[i] enzymes = find_enzymes_for_transformation(substrate, product_step, limit=5) if enzymes: pathway['steps'].append({ 'step_number': i + 1, 'substrate': substrate, 'product': product_step, 'enzymes': enzymes, 'transformation': infer_transformation_type(substrate, product_step) }) else: pathway['warnings'].append(f"No enzymes found for step: {substrate} -> {product_step}") pathway['confidence'] = 0.8 # High confidence for found pathway break # Try to find enzymes that produce current metabolite if step_count < max_steps: # Generate possible substrates (simplified - in practice you'd need metabolic knowledge) possible_substrates = [] # Try common metabolic precursors common_precursors = ['glucose', 'pyruvate', 'acetate', 'ethanol', 'acetyl-CoA', 'oxaloacetate'] for precursor in common_precursors: enzymes = find_enzymes_for_transformation(precursor, current_metabolite, limit=2) if enzymes: possible_substrates.append(precursor) pathway['alternative_pathways'].append({ 'precursor': precursor, 'product': current_metabolite, 'enzymes': enzymes }) # Add found substrates to queue for substrate in possible_substrates: if substrate not in current_path: new_path = [substrate] + current_path queue.append((substrate, step_count + 1, new_path)) time.sleep(0.2) # Rate limiting # If no complete pathway found, create partial pathway if not pathway['steps'] and pathway['alternative_pathways']: # Create best guess pathway from alternatives best_alternative = max(pathway['alternative_pathways'], key=lambda x: len(x.get('enzymes', []))) pathway['steps'] = [{ 'step_number': 1, 'substrate': best_alternative['precursor'], 'product': best_alternative['product'], 'enzymes': best_alternative['enzymes'], 'transformation': infer_transformation_type(best_alternative['precursor'], best_alternative['product']) }] pathway['confidence'] = 0.3 # Low confidence for partial pathway pathway['warnings'].append("Partial pathway only - complete synthesis route not found") elif not pathway['steps']: pathway['warnings'].append("No enzymatic pathway found for target product") pathway['confidence'] = 0.1 return pathway def build_retrosynthetic_tree(target: str, depth: int = 2) -> Dict[str, Any]: """Build a retrosynthetic tree for a target molecule.""" validate_dependencies() tree = { 'target': target, 'depth': depth, 'nodes': {target: {'level': 0, 'children': [], 'enzymes': []}}, 'edges': [], 'alternative_routes': [] } # Build tree recursively def build_node_recursive(metabolite: str, current_depth: int, parent: str = None) -> None: if current_depth >= depth: return # Find enzymes that can produce this metabolite potential_precursors = ['glucose', 'pyruvate', 'acetate', 'ethanol', 'acetyl-CoA', 'oxaloacetate', 'alpha-ketoglutarate', 'malate'] for precursor in potential_precursors: enzymes = find_enzymes_for_transformation(precursor, metabolite, limit=3) if enzymes: # Add precursor as node if not exists if precursor not in tree['nodes']: tree['nodes'][precursor] = { 'level': current_depth + 1, 'children': [], 'enzymes': enzymes } tree['nodes'][metabolite]['children'].append(precursor) tree['edges'].append({ 'from': precursor, 'to': metabolite, 'enzymes': enzymes, 'transformation': infer_transformation_type(precursor, metabolite) }) # Recursively build tree if current_depth + 1 < depth: build_node_recursive(precursor, current_depth + 1, metabolite) # Try common metabolic transformations if current_depth < depth - 1: transformations = ['oxidation', 'reduction', 'hydrolysis', 'carboxylation', 'decarboxylation'] for trans in transformations: try: generic_enzymes = search_by_pattern(trans, limit=2) if generic_enzymes: # Create hypothetical precursor hypothetical_precursor = f"precursor_{trans}_{metabolite}" tree['nodes'][hypothetical_precursor] = { 'level': current_depth + 1, 'children': [], 'enzymes': generic_enzymes, 'hypothetical': True } tree['nodes'][metabolite]['children'].append(hypothetical_precursor) tree['edges'].append({ 'from': hypothetical_precursor, 'to': metabolite, 'enzymes': generic_enzymes, 'transformation': trans, 'hypothetical': True }) except Exception as e: print(f"Error in retrosynthetic search for {trans}: {e}") time.sleep(0.3) # Rate limiting # Start building from target build_node_recursive(target, 0) # Calculate tree statistics tree['total_nodes'] = len(tree['nodes']) tree['total_edges'] = len(tree['edges']) tree['max_depth'] = max(node['level'] for node in tree['nodes'].values()) if tree['nodes'] else 0 return tree def suggest_enzyme_substitutions(ec_number: str, criteria: Dict[str, Any] = None) -> List[Dict[str, Any]]: """Suggest alternative enzymes with improved properties.""" validate_dependencies() if criteria is None: criteria = { 'min_temperature': 30, 'max_temperature': 70, 'min_ph': 6.0, 'max_ph': 8.0, 'min_thermostability': 40, 'prefer_organisms': ['Escherichia coli', 'Saccharomyces cerevisiae', 'Bacillus subtilis'] } substitutions = [] # Get organisms for the target enzyme try: organisms = compare_across_organisms(ec_number, criteria['prefer_organisms']) time.sleep(0.5) except Exception as e: print(f"Error comparing organisms: {e}") organisms = [] # Find thermophilic homologs if temperature is a criterion if criteria.get('min_thermostability'): try: thermophilic = find_thermophilic_homologs(ec_number, criteria['min_thermostability']) time.sleep(0.5) for enzyme in thermophilic: enzyme['substitution_reason'] = f"Thermostable (optimal temp: {enzyme['optimal_temperature']}°C)" enzyme['score'] = 8.0 if enzyme['optimal_temperature'] >= criteria['min_thermostability'] else 6.0 substitutions.append(enzyme) except Exception as e: print(f"Error finding thermophilic homologs: {e}") # Find pH-stable variants if criteria.get('min_ph') or criteria.get('max_ph'): try: ph_stable = find_ph_stable_variants(ec_number, criteria.get('min_ph'), criteria.get('max_ph')) time.sleep(0.5) for enzyme in ph_stable: enzyme['substitution_reason'] = f"pH stable ({enzyme['stability_type']} range: {enzyme['ph_range']})" enzyme['score'] = 7.5 substitutions.append(enzyme) except Exception as e: print(f"Error finding pH-stable variants: {e}") # Add organism comparison results for org_data in organisms: if org_data.get('data_points', 0) > 0: org_data['substitution_reason'] = f"Well-characterized in {org_data['organism']}" org_data['score'] = 6.5 if org_data['organism'] in criteria['prefer_organisms'] else 5.0 substitutions.append(org_data) # Sort by score substitutions.sort(key=lambda x: x.get('score', 0), reverse=True) return substitutions[:10] # Return top 10 suggestions def calculate_pathway_feasibility(pathway: Dict[str, Any]) -> Dict[str, Any]: """Calculate feasibility scores and potential issues for a pathway.""" validate_dependencies() feasibility = { 'overall_score': 0, 'step_scores': [], 'warnings': [], 'recommendations': [], 'thermodynamic_feasibility': 0, 'enzyme_availability': 0, 'cofactor_requirements': [], 'optimal_conditions': {} } if not pathway.get('steps'): feasibility['warnings'].append("No steps in pathway") feasibility['overall_score'] = 0.1 return feasibility total_score = 0 step_scores = [] for step in pathway['steps']: step_score = 0 enzymes = step.get('enzymes', []) # Score based on number of available enzymes if len(enzymes) >= 3: step_score += 3 # Multiple enzyme options elif len(enzymes) >= 1: step_score += 2 # At least one enzyme else: step_score += 0 # No enzymes feasibility['warnings'].append(f"No enzymes found for step: {step['substrate']} -> {step['product']}") # Score based on enzyme confidence if enzymes: high_confidence = sum(1 for e in enzymes if e.get('confidence') == 'high') confidence_bonus = min(high_confidence, 2) # Max 2 points for confidence step_score += confidence_bonus # Check for industrial viability industrial_organisms = ['Escherichia coli', 'Saccharomyces cerevisiae', 'Bacillus subtilis'] industrial_enzymes = sum(1 for e in enzymes if e.get('organism') in industrial_organisms) if industrial_enzymes > 0: step_score += 1 # Cap step score at 5 step_score = min(step_score, 5) step_scores.append(step_score) total_score += step_score # Analyze cofactor requirements try: for enzyme in enzymes: ec_number = enzyme.get('ec_number', '') if ec_number: cofactors = get_cofactor_requirements(ec_number) for cofactor in cofactors: if cofactor['name'] not in [c['name'] for c in feasibility['cofactor_requirements']]: feasibility['cofactor_requirements'].append(cofactor) time.sleep(0.3) except Exception as e: print(f"Error analyzing cofactors: {e}") feasibility['step_scores'] = step_scores feasibility['enzyme_availability'] = total_score / (len(step_scores) * 5) # Normalize to 0-1 feasibility['overall_score'] = feasibility['enzyme_availability'] * 0.7 # Weight enzyme availability # Thermodynamic feasibility (simplified heuristic) pathway_length = len(pathway['steps']) if pathway_length <= 2: feasibility['thermodynamic_feasibility'] = 0.8 # Short pathways are often feasible elif pathway_length <= 4: feasibility['thermodynamic_feasibility'] = 0.6 else: feasibility['thermodynamic_feasibility'] = 0.4 # Long pathways may have thermodynamic issues # Overall feasibility is weighted combination feasibility['overall_score'] = ( feasibility['enzyme_availability'] * 0.6 + feasibility['thermodynamic_feasibility'] * 0.4 ) # Generate recommendations if feasibility['overall_score'] < 0.3: feasibility['warnings'].append("Low overall pathway feasibility") feasibility['recommendations'].append("Consider alternative starting materials or target molecules") elif feasibility['overall_score'] < 0.6: feasibility['warnings'].append("Moderate pathway feasibility") feasibility['recommendations'].append("Consider enzyme engineering or cofactor recycling") if feasibility['cofactor_requirements']: feasibility['recommendations'].append("Implement cofactor recycling system for: " + ", ".join([c['name'] for c in feasibility['cofactor_requirements']])) return feasibility def optimize_pathway_conditions(pathway: Dict[str, Any]) -> Dict[str, Any]: """Suggest optimal conditions for the entire pathway.""" validate_dependencies() optimization = { 'optimal_temperature': 30.0, # Default 'optimal_ph': 7.0, # Default 'temperature_range': (20, 40), # Default 'ph_range': (6.5, 7.5), # Default 'cofactor_system': [], 'organism_compatibility': {}, 'process_recommendations': [] } temperatures = [] phs = [] organism_preferences = {} # Collect environmental data from all enzymes for step in pathway.get('steps', []): for enzyme in step.get('enzymes', []): ec_number = enzyme.get('ec_number', '') organism = enzyme.get('organism', '') if ec_number: try: env_params = get_environmental_parameters(ec_number) time.sleep(0.3) if env_params.get('optimal_temperature'): temperatures.append(env_params['optimal_temperature']) if env_params.get('optimal_ph'): phs.append(env_params['optimal_ph']) # Track organism preferences if organism not in organism_preferences: organism_preferences[organism] = { 'temperature_optima': [], 'ph_optima': [], 'step_count': 0 } organism_preferences[organism]['step_count'] += 1 if env_params.get('optimal_temperature'): organism_preferences[organism]['temperature_optima'].append(env_params['optimal_temperature']) if env_params.get('optimal_ph'): organism_preferences[organism]['ph_optima'].append(env_params['optimal_ph']) except Exception as e: print(f"Error getting environmental parameters for {ec_number}: {e}") # Calculate optimal conditions if temperatures: optimization['optimal_temperature'] = sum(temperatures) / len(temperatures) optimization['temperature_range'] = (min(temperatures) - 5, max(temperatures) + 5) if phs: optimization['optimal_ph'] = sum(phs) / len(phs) optimization['ph_range'] = (min(phs) - 0.5, max(phs) + 0.5) # Find best organism compatibility for organism, data in organism_preferences.items(): if data['temperature_optima'] and data['ph_optima']: organism_preferences[organism]['avg_temp'] = sum(data['temperature_optima']) / len(data['temperature_optima']) organism_preferences[organism]['avg_ph'] = sum(data['ph_optima']) / len(data['ph_optima']) organism_preferences[organism]['compatibility_score'] = data['step_count'] # Sort organisms by compatibility compatible_organisms = sorted( [(org, data) for org, data in organism_preferences.items() if data.get('compatibility_score', 0) > 0], key=lambda x: x[1]['compatibility_score'], reverse=True ) optimization['organism_compatibility'] = dict(compatible_organisms[:5]) # Top 5 organisms # Generate process recommendations if len(optimization['organism_compatibility']) > 1: optimization['process_recommendations'].append("Consider multi-organism system or enzyme cocktails") if optimization['temperature_range'][1] - optimization['temperature_range'][0] > 30: optimization['process_recommendations'].append("Consider temperature gradient or staged process") if optimization['ph_range'][1] - optimization['ph_range'][0] > 2: optimization['process_recommendations'].append("Consider pH control system or buffer optimization") # Cofactor system optimization cofactor_types = {} for step in pathway.get('steps', []): for enzyme in step.get('enzymes', []): ec_number = enzyme.get('ec_number', '') if ec_number: try: cofactors = get_cofactor_requirements(ec_number) for cofactor in cofactors: cofactor_type = cofactor.get('type', 'other') if cofactor_type not in cofactor_types: cofactor_types[cofactor_type] = [] if cofactor['name'] not in cofactor_types[cofactor_type]: cofactor_types[cofactor_type].append(cofactor['name']) time.sleep(0.3) except Exception as e: print(f"Error getting cofactors for {ec_number}: {e}") optimization['cofactor_system'] = cofactor_types return optimization def generate_pathway_report(pathway: Dict[str, Any], filename: str = None) -> str: """Generate a comprehensive pathway report.""" validate_dependencies() if filename is None: target_name = pathway.get('target', 'pathway').replace(' ', '_').lower() filename = f"pathway_report_{target_name}.txt" # Calculate feasibility and optimization feasibility = calculate_pathway_feasibility(pathway) optimization = optimize_pathway_conditions(pathway) report = [] report.append("=" * 80) report.append(f"ENZYMATIC PATHWAY REPORT") report.append("=" * 80) # Overview report.append(f"\nTARGET PRODUCT: {pathway.get('target', 'Unknown')}") report.append(f"PATHWAY LENGTH: {len(pathway.get('steps', []))} steps") report.append(f"OVERALL FEASIBILITY: {feasibility['overall_score']:.2f}/1.00") # Pathway steps if pathway.get('steps'): report.append("\n" + "=" * 40) report.append("PATHWAY STEPS") report.append("=" * 40) for i, step in enumerate(pathway['steps'], 1): report.append(f"\nStep {i}: {step['substrate']} -> {step['product']}") report.append(f"Transformation: {', '.join(step.get('transformation', ['Unknown']))}") if step.get('enzymes'): report.append(f"Available enzymes: {len(step['enzymes'])}") for j, enzyme in enumerate(step['enzymes'][:3], 1): # Top 3 enzymes report.append(f" {j}. EC {enzyme.get('ec_number', 'Unknown')} - {enzyme.get('organism', 'Unknown')}") report.append(f" Confidence: {enzyme.get('confidence', 'Unknown')}") if enzyme.get('reaction'): report.append(f" Reaction: {enzyme['reaction'][:100]}...") if len(step['enzymes']) > 3: report.append(f" ... and {len(step['enzymes']) - 3} additional enzymes") else: report.append(" No enzymes found for this step") if feasibility.get('step_scores') and i-1 < len(feasibility['step_scores']): report.append(f"Step feasibility score: {feasibility['step_scores'][i-1]}/5.0") # Cofactor requirements if feasibility.get('cofactor_requirements'): report.append("\n" + "=" * 40) report.append("COFACTOR REQUIREMENTS") report.append("=" * 40) for cofactor in feasibility['cofactor_requirements']: report.append(f"- {cofactor['name']} ({cofactor.get('type', 'Unknown')})") report.append(f" Organism: {cofactor.get('organism', 'Unknown')}") report.append(f" EC Number: {cofactor.get('ec_number', 'Unknown')}") # Optimal conditions report.append("\n" + "=" * 40) report.append("OPTIMAL CONDITIONS") report.append("=" * 40) report.append(f"Temperature: {optimization['optimal_temperature']:.1f}°C") report.append(f"pH: {optimization['optimal_ph']:.1f}") report.append(f"Temperature range: {optimization['temperature_range'][0]:.1f} - {optimization['temperature_range'][1]:.1f}°C") report.append(f"pH range: {optimization['ph_range'][0]:.1f} - {optimization['ph_range'][1]:.1f}") if optimization.get('organism_compatibility'): report.append("\nCompatible organisms (by preference):") for organism, data in list(optimization['organism_compatibility'].items())[:3]: report.append(f"- {organism} (compatibility score: {data.get('compatibility_score', 0)})") if data.get('avg_temp'): report.append(f" Optimal temperature: {data['avg_temp']:.1f}°C") if data.get('avg_ph'): report.append(f" Optimal pH: {data['avg_ph']:.1f}") # Warnings and recommendations if feasibility.get('warnings'): report.append("\n" + "=" * 40) report.append("WARNINGS") report.append("=" * 40) for warning in feasibility['warnings']: report.append(f"⚠️ {warning}") if feasibility.get('recommendations'): report.append("\n" + "=" * 40) report.append("RECOMMENDATIONS") report.append("=" * 40) for rec in feasibility['recommendations']: report.append(f"💡 {rec}") if optimization.get('process_recommendations'): for rec in optimization['process_recommendations']: report.append(f"🔧 {rec}") # Alternative pathways if pathway.get('alternative_pathways'): report.append("\n" + "=" * 40) report.append("ALTERNATIVE ROUTES") report.append("=" * 40) for alt in pathway['alternative_pathways'][:5]: # Top 5 alternatives report.append(f"\n{alt['precursor']} -> {alt['product']}") report.append(f"Enzymes available: {len(alt.get('enzymes', []))}") for enzyme in alt.get('enzymes', [])[:2]: # Top 2 enzymes report.append(f" - {enzyme.get('ec_number', 'Unknown')} ({enzyme.get('organism', 'Unknown')})") # Feasibility analysis report.append("\n" + "=" * 40) report.append("FEASIBILITY ANALYSIS") report.append("=" * 40) report.append(f"Enzyme availability score: {feasibility['enzyme_availability']:.2f}/1.00") report.append(f"Thermodynamic feasibility: {feasibility['thermodynamic_feasibility']:.2f}/1.00") # Write report to file with open(filename, 'w') as f: f.write('\n'.join(report)) print(f"Pathway report saved to {filename}") return filename def visualize_pathway(pathway: Dict[str, Any], save_path: str = None) -> str: """Create a visual representation of the pathway.""" validate_dependencies() if not NETWORKX_AVAILABLE or not MATPLOTLIB_AVAILABLE: print("networkx and matplotlib required for pathway visualization") return save_path or "pathway_visualization.png" try: # Create directed graph G = nx.DiGraph() # Add nodes and edges for step in pathway.get('steps', []): substrate = step['substrate'] product = step['product'] enzymes = step.get('enzymes', []) G.add_node(substrate, type='substrate') G.add_node(product, type='product') # Add edge with enzyme information edge_label = f"{len(enzymes)} enzymes" if enzymes: primary_ec = enzymes[0].get('ec_number', 'Unknown') edge_label += f"\nEC {primary_ec}" G.add_edge(substrate, product, label=edge_label) # Create figure plt.figure(figsize=(12, 8)) # Layout pos = nx.spring_layout(G, k=2, iterations=50) # Draw nodes substrate_nodes = [n for n, d in G.nodes(data=True) if d.get('type') == 'substrate'] product_nodes = [n for n, d in G.nodes(data=True) if d.get('type') == 'product'] intermediate_nodes = [n for n in G.nodes() if n not in substrate_nodes and n not in product_nodes] nx.draw_networkx_nodes(G, pos, nodelist=substrate_nodes, node_color='lightblue', node_size=1500) nx.draw_networkx_nodes(G, pos, nodelist=product_nodes, node_color='lightgreen', node_size=1500) nx.draw_networkx_nodes(G, pos, nodelist=intermediate_nodes, node_color='lightyellow', node_size=1200) # Draw edges nx.draw_networkx_edges(G, pos, edge_color='gray', arrows=True, arrowsize=20) # Draw labels nx.draw_networkx_labels(G, pos, font_size=10, font_weight='bold') # Draw edge labels edge_labels = nx.get_edge_attributes(G, 'label') nx.draw_networkx_edge_labels(G, pos, edge_labels, font_size=8) # Add title plt.title(f"Enzymatic Pathway to {pathway.get('target', 'Target')}", fontsize=14, fontweight='bold') # Add legend plt.scatter([], [], c='lightblue', s=150, label='Starting Materials') plt.scatter([], [], c='lightyellow', s=120, label='Intermediates') plt.scatter([], [], c='lightgreen', s=150, label='Products') plt.legend() plt.axis('off') plt.tight_layout() # Save or show if save_path: plt.savefig(save_path, dpi=300, bbox_inches='tight') print(f"Pathway visualization saved to {save_path}") else: plt.show() plt.close() return save_path or "pathway_visualization.png" except Exception as e: print(f"Error visualizing pathway: {e}") return save_path or "pathway_visualization.png" if __name__ == "__main__": # Example usage print("Enzyme Pathway Builder Examples") print("=" * 50) try: # Example 1: Find pathway for lactate print("\n1. Finding pathway for lactate production:") pathway = find_pathway_for_product("lactate", max_steps=3) print(f"Found pathway with {len(pathway['steps'])} steps") print(f"Feasibility: {pathway['confidence']:.2f}") # Example 2: Build retrosynthetic tree print("\n2. Building retrosynthetic tree for ethanol:") tree = build_retrosynthetic_tree("ethanol", depth=2) print(f"Tree has {tree['total_nodes']} nodes and {tree['total_edges']} edges") # Example 3: Suggest enzyme substitutions print("\n3. Suggesting enzyme substitutions for alcohol dehydrogenase:") substitutions = suggest_enzyme_substitutions("1.1.1.1") for sub in substitutions[:3]: print(f" - {sub.get('organism', 'Unknown')}: {sub.get('substitution_reason', 'No reason')}") # Example 4: Calculate feasibility print("\n4. Calculating pathway feasibility:") feasibility = calculate_pathway_feasibility(pathway) print(f"Overall score: {feasibility['overall_score']:.2f}") print(f"Warnings: {len(feasibility['warnings'])}") # Example 5: Generate pathway report print("\n5. Generating pathway report:") report_file = generate_pathway_report(pathway) print(f"Report saved to: {report_file}") # Example 6: Visualize pathway print("\n6. Visualizing pathway:") viz_file = visualize_pathway(pathway, "example_pathway.png") print(f"Visualization saved to: {viz_file}") except Exception as e: print(f"Example failed: {e}")
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/brenda-database/scripts/enzyme_pathway_builder.py", "license": "MIT License", "lines": 867, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/chembl-database/scripts/example_queries.py
#!/usr/bin/env python3 """ ChEMBL Database Query Examples This script demonstrates common query patterns for the ChEMBL database using the chembl_webresource_client Python library. Requirements: pip install chembl_webresource_client pip install pandas (optional, for data manipulation) """ from chembl_webresource_client.new_client import new_client def get_molecule_info(chembl_id): """ Retrieve detailed information about a molecule by ChEMBL ID. Args: chembl_id: ChEMBL identifier (e.g., 'CHEMBL25') Returns: Dictionary containing molecule information """ molecule = new_client.molecule return molecule.get(chembl_id) def search_molecules_by_name(name_pattern): """ Search for molecules by name pattern. Args: name_pattern: Name or pattern to search for Returns: List of matching molecules """ molecule = new_client.molecule results = molecule.filter(pref_name__icontains=name_pattern) return list(results) def find_molecules_by_properties(max_mw=500, min_logp=None, max_logp=None): """ Find molecules based on physicochemical properties. Args: max_mw: Maximum molecular weight min_logp: Minimum LogP value max_logp: Maximum LogP value Returns: List of matching molecules """ molecule = new_client.molecule filters = { 'molecule_properties__mw_freebase__lte': max_mw } if min_logp is not None: filters['molecule_properties__alogp__gte'] = min_logp if max_logp is not None: filters['molecule_properties__alogp__lte'] = max_logp results = molecule.filter(**filters) return list(results) def get_target_info(target_chembl_id): """ Retrieve information about a biological target. Args: target_chembl_id: ChEMBL target identifier (e.g., 'CHEMBL240') Returns: Dictionary containing target information """ target = new_client.target return target.get(target_chembl_id) def search_targets_by_name(target_name): """ Search for targets by name or keyword. Args: target_name: Target name or keyword (e.g., 'kinase', 'EGFR') Returns: List of matching targets """ target = new_client.target results = target.filter( target_type='SINGLE PROTEIN', pref_name__icontains=target_name ) return list(results) def get_bioactivity_data(target_chembl_id, activity_type='IC50', max_value=100): """ Retrieve bioactivity data for a specific target. Args: target_chembl_id: ChEMBL target identifier activity_type: Type of activity (IC50, Ki, EC50, etc.) max_value: Maximum activity value in nM Returns: List of activity records """ activity = new_client.activity results = activity.filter( target_chembl_id=target_chembl_id, standard_type=activity_type, standard_value__lte=max_value, standard_units='nM' ) return list(results) def find_similar_compounds(smiles, similarity_threshold=85): """ Find compounds similar to a query structure. Args: smiles: SMILES string of query molecule similarity_threshold: Minimum similarity percentage (0-100) Returns: List of similar compounds """ similarity = new_client.similarity results = similarity.filter( smiles=smiles, similarity=similarity_threshold ) return list(results) def substructure_search(smiles): """ Search for compounds containing a specific substructure. Args: smiles: SMILES string of substructure Returns: List of compounds containing the substructure """ substructure = new_client.substructure results = substructure.filter(smiles=smiles) return list(results) def get_drug_info(molecule_chembl_id): """ Retrieve drug information including indications and mechanisms. Args: molecule_chembl_id: ChEMBL molecule identifier Returns: Tuple of (drug_info, mechanisms, indications) """ drug = new_client.drug mechanism = new_client.mechanism drug_indication = new_client.drug_indication try: drug_info = drug.get(molecule_chembl_id) except: drug_info = None mechanisms = list(mechanism.filter(molecule_chembl_id=molecule_chembl_id)) indications = list(drug_indication.filter(molecule_chembl_id=molecule_chembl_id)) return drug_info, mechanisms, indications def find_kinase_inhibitors(max_ic50=100): """ Find potent kinase inhibitors. Args: max_ic50: Maximum IC50 value in nM Returns: List of kinase inhibitor activities """ target = new_client.target activity = new_client.activity # Find kinase targets kinase_targets = target.filter( target_type='SINGLE PROTEIN', pref_name__icontains='kinase' ) # Get target IDs target_ids = [t['target_chembl_id'] for t in kinase_targets[:10]] # Limit to first 10 # Find activities results = activity.filter( target_chembl_id__in=target_ids, standard_type='IC50', standard_value__lte=max_ic50, standard_units='nM' ) return list(results) def get_compound_bioactivities(molecule_chembl_id): """ Get all bioactivity data for a specific compound. Args: molecule_chembl_id: ChEMBL molecule identifier Returns: List of all activity records for the compound """ activity = new_client.activity results = activity.filter( molecule_chembl_id=molecule_chembl_id, pchembl_value__isnull=False ) return list(results) def export_to_dataframe(data): """ Convert ChEMBL data to pandas DataFrame (requires pandas). Args: data: List of ChEMBL records Returns: pandas DataFrame """ try: import pandas as pd return pd.DataFrame(data) except ImportError: print("pandas not installed. Install with: pip install pandas") return None # Example usage if __name__ == "__main__": print("ChEMBL Database Query Examples") print("=" * 50) # Example 1: Get information about aspirin print("\n1. Getting information about aspirin (CHEMBL25)...") aspirin = get_molecule_info('CHEMBL25') print(f"Name: {aspirin.get('pref_name')}") print(f"Formula: {aspirin.get('molecule_properties', {}).get('full_molformula')}") # Example 2: Search for EGFR inhibitors print("\n2. Searching for EGFR targets...") egfr_targets = search_targets_by_name('EGFR') if egfr_targets: print(f"Found {len(egfr_targets)} EGFR-related targets") print(f"First target: {egfr_targets[0]['pref_name']}") # Example 3: Find potent activities for a target print("\n3. Finding potent compounds for EGFR (CHEMBL203)...") activities = get_bioactivity_data('CHEMBL203', 'IC50', max_value=10) print(f"Found {len(activities)} compounds with IC50 <= 10 nM") print("\n" + "=" * 50) print("Examples completed successfully!")
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/chembl-database/scripts/example_queries.py", "license": "MIT License", "lines": 211, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
davila7/claude-code-templates:cli-tool/components/skills/scientific/citation-management/scripts/doi_to_bibtex.py
#!/usr/bin/env python3 """ DOI to BibTeX Converter Quick utility to convert DOIs to BibTeX format using CrossRef API. """ import sys import requests import argparse import time import json from typing import Optional, List class DOIConverter: """Convert DOIs to BibTeX entries using CrossRef API.""" def __init__(self): self.session = requests.Session() self.session.headers.update({ 'User-Agent': 'DOIConverter/1.0 (Citation Management Tool; mailto:support@example.com)' }) def doi_to_bibtex(self, doi: str) -> Optional[str]: """ Convert a single DOI to BibTeX format. Args: doi: Digital Object Identifier Returns: BibTeX string or None if conversion fails """ # Clean DOI (remove URL prefix if present) doi = doi.strip() if doi.startswith('https://doi.org/'): doi = doi.replace('https://doi.org/', '') elif doi.startswith('http://doi.org/'): doi = doi.replace('http://doi.org/', '') elif doi.startswith('doi:'): doi = doi.replace('doi:', '') # Request BibTeX from CrossRef content negotiation url = f'https://doi.org/{doi}' headers = { 'Accept': 'application/x-bibtex', 'User-Agent': 'DOIConverter/1.0 (Citation Management Tool)' } try: response = self.session.get(url, headers=headers, timeout=15) if response.status_code == 200: bibtex = response.text.strip() # CrossRef sometimes returns entries with @data type, convert to @misc if bibtex.startswith('@data{'): bibtex = bibtex.replace('@data{', '@misc{', 1) return bibtex elif response.status_code == 404: print(f'Error: DOI not found: {doi}', file=sys.stderr) return None else: print(f'Error: Failed to retrieve BibTeX for {doi} (status {response.status_code})', file=sys.stderr) return None except requests.exceptions.Timeout: print(f'Error: Request timeout for DOI: {doi}', file=sys.stderr) return None except requests.exceptions.RequestException as e: print(f'Error: Request failed for {doi}: {e}', file=sys.stderr) return None def convert_multiple(self, dois: List[str], delay: float = 0.5) -> List[str]: """ Convert multiple DOIs to BibTeX. Args: dois: List of DOIs delay: Delay between requests (seconds) for rate limiting Returns: List of BibTeX entries (excludes failed conversions) """ bibtex_entries = [] for i, doi in enumerate(dois): print(f'Converting DOI {i+1}/{len(dois)}: {doi}', file=sys.stderr) bibtex = self.doi_to_bibtex(doi) if bibtex: bibtex_entries.append(bibtex) # Rate limiting if i < len(dois) - 1: # Don't delay after last request time.sleep(delay) return bibtex_entries def main(): """Command-line interface.""" parser = argparse.ArgumentParser( description='Convert DOIs to BibTeX format using CrossRef API', epilog='Example: python doi_to_bibtex.py 10.1038/s41586-021-03819-2' ) parser.add_argument( 'dois', nargs='*', help='DOI(s) to convert (can provide multiple)' ) parser.add_argument( '-i', '--input', help='Input file with DOIs (one per line)' ) parser.add_argument( '-o', '--output', help='Output file for BibTeX (default: stdout)' ) parser.add_argument( '--delay', type=float, default=0.5, help='Delay between requests in seconds (default: 0.5)' ) parser.add_argument( '--format', choices=['bibtex', 'json'], default='bibtex', help='Output format (default: bibtex)' ) args = parser.parse_args() # Collect DOIs from command line and/or file dois = [] if args.dois: dois.extend(args.dois) if args.input: try: with open(args.input, 'r', encoding='utf-8') as f: file_dois = [line.strip() for line in f if line.strip()] dois.extend(file_dois) except FileNotFoundError: print(f'Error: Input file not found: {args.input}', file=sys.stderr) sys.exit(1) except Exception as e: print(f'Error reading input file: {e}', file=sys.stderr) sys.exit(1) if not dois: parser.print_help() sys.exit(1) # Convert DOIs converter = DOIConverter() if len(dois) == 1: bibtex = converter.doi_to_bibtex(dois[0]) if bibtex: bibtex_entries = [bibtex] else: sys.exit(1) else: bibtex_entries = converter.convert_multiple(dois, delay=args.delay) if not bibtex_entries: print('Error: No successful conversions', file=sys.stderr) sys.exit(1) # Format output if args.format == 'bibtex': output = '\n\n'.join(bibtex_entries) + '\n' else: # json output = json.dumps({ 'count': len(bibtex_entries), 'entries': bibtex_entries }, indent=2) # Write output if args.output: try: with open(args.output, 'w', encoding='utf-8') as f: f.write(output) print(f'Successfully wrote {len(bibtex_entries)} entries to {args.output}', file=sys.stderr) except Exception as e: print(f'Error writing output file: {e}', file=sys.stderr) sys.exit(1) else: print(output) # Summary if len(dois) > 1: success_rate = len(bibtex_entries) / len(dois) * 100 print(f'\nConverted {len(bibtex_entries)}/{len(dois)} DOIs ({success_rate:.1f}%)', file=sys.stderr) if __name__ == '__main__': main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/citation-management/scripts/doi_to_bibtex.py", "license": "MIT License", "lines": 167, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/citation-management/scripts/extract_metadata.py
#!/usr/bin/env python3 """ Metadata Extraction Tool Extract citation metadata from DOI, PMID, arXiv ID, or URL using various APIs. """ import sys import os import requests import argparse import time import re import json import xml.etree.ElementTree as ET from typing import Optional, Dict, List, Tuple from urllib.parse import urlparse class MetadataExtractor: """Extract metadata from various sources and generate BibTeX.""" def __init__(self, email: Optional[str] = None): """ Initialize extractor. Args: email: Email for Entrez API (recommended for PubMed) """ self.session = requests.Session() self.session.headers.update({ 'User-Agent': 'MetadataExtractor/1.0 (Citation Management Tool)' }) self.email = email or os.getenv('NCBI_EMAIL', '') def identify_type(self, identifier: str) -> Tuple[str, str]: """ Identify the type of identifier. Args: identifier: DOI, PMID, arXiv ID, or URL Returns: Tuple of (type, cleaned_identifier) """ identifier = identifier.strip() # Check if URL if identifier.startswith('http://') or identifier.startswith('https://'): return self._parse_url(identifier) # Check for DOI if identifier.startswith('10.'): return ('doi', identifier) # Check for arXiv ID if re.match(r'^\d{4}\.\d{4,5}(v\d+)?$', identifier): return ('arxiv', identifier) if identifier.startswith('arXiv:'): return ('arxiv', identifier.replace('arXiv:', '')) # Check for PMID (8-digit number typically) if identifier.isdigit() and len(identifier) >= 7: return ('pmid', identifier) # Check for PMCID if identifier.upper().startswith('PMC') and identifier[3:].isdigit(): return ('pmcid', identifier.upper()) return ('unknown', identifier) def _parse_url(self, url: str) -> Tuple[str, str]: """Parse URL to extract identifier type and value.""" parsed = urlparse(url) # DOI URLs if 'doi.org' in parsed.netloc: doi = parsed.path.lstrip('/') return ('doi', doi) # PubMed URLs if 'pubmed.ncbi.nlm.nih.gov' in parsed.netloc or 'ncbi.nlm.nih.gov/pubmed' in url: pmid = re.search(r'/(\d+)', parsed.path) if pmid: return ('pmid', pmid.group(1)) # arXiv URLs if 'arxiv.org' in parsed.netloc: arxiv_id = re.search(r'/abs/(\d{4}\.\d{4,5})', parsed.path) if arxiv_id: return ('arxiv', arxiv_id.group(1)) # Nature, Science, Cell, etc. - try to extract DOI from URL doi_match = re.search(r'10\.\d{4,}/[^\s/]+', url) if doi_match: return ('doi', doi_match.group()) return ('url', url) def extract_from_doi(self, doi: str) -> Optional[Dict]: """ Extract metadata from DOI using CrossRef API. Args: doi: Digital Object Identifier Returns: Metadata dictionary or None """ url = f'https://api.crossref.org/works/{doi}' try: response = self.session.get(url, timeout=15) if response.status_code == 200: data = response.json() message = data.get('message', {}) metadata = { 'type': 'doi', 'entry_type': self._crossref_type_to_bibtex(message.get('type')), 'doi': doi, 'title': message.get('title', [''])[0], 'authors': self._format_authors_crossref(message.get('author', [])), 'year': self._extract_year_crossref(message), 'journal': message.get('container-title', [''])[0] if message.get('container-title') else '', 'volume': str(message.get('volume', '')) if message.get('volume') else '', 'issue': str(message.get('issue', '')) if message.get('issue') else '', 'pages': message.get('page', ''), 'publisher': message.get('publisher', ''), 'url': f'https://doi.org/{doi}' } return metadata else: print(f'Error: CrossRef API returned status {response.status_code} for DOI: {doi}', file=sys.stderr) return None except Exception as e: print(f'Error extracting metadata from DOI {doi}: {e}', file=sys.stderr) return None def extract_from_pmid(self, pmid: str) -> Optional[Dict]: """ Extract metadata from PMID using PubMed E-utilities. Args: pmid: PubMed ID Returns: Metadata dictionary or None """ url = f'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi' params = { 'db': 'pubmed', 'id': pmid, 'retmode': 'xml', 'rettype': 'abstract' } if self.email: params['email'] = self.email api_key = os.getenv('NCBI_API_KEY') if api_key: params['api_key'] = api_key try: response = self.session.get(url, params=params, timeout=15) if response.status_code == 200: root = ET.fromstring(response.content) article = root.find('.//PubmedArticle') if article is None: print(f'Error: No article found for PMID: {pmid}', file=sys.stderr) return None # Extract metadata from XML medline_citation = article.find('.//MedlineCitation') article_elem = medline_citation.find('.//Article') journal = article_elem.find('.//Journal') # Get DOI if available doi = None article_ids = article.findall('.//ArticleId') for article_id in article_ids: if article_id.get('IdType') == 'doi': doi = article_id.text break metadata = { 'type': 'pmid', 'entry_type': 'article', 'pmid': pmid, 'title': article_elem.findtext('.//ArticleTitle', ''), 'authors': self._format_authors_pubmed(article_elem.findall('.//Author')), 'year': self._extract_year_pubmed(article_elem), 'journal': journal.findtext('.//Title', ''), 'volume': journal.findtext('.//JournalIssue/Volume', ''), 'issue': journal.findtext('.//JournalIssue/Issue', ''), 'pages': article_elem.findtext('.//Pagination/MedlinePgn', ''), 'doi': doi } return metadata else: print(f'Error: PubMed API returned status {response.status_code} for PMID: {pmid}', file=sys.stderr) return None except Exception as e: print(f'Error extracting metadata from PMID {pmid}: {e}', file=sys.stderr) return None def extract_from_arxiv(self, arxiv_id: str) -> Optional[Dict]: """ Extract metadata from arXiv ID using arXiv API. Args: arxiv_id: arXiv identifier Returns: Metadata dictionary or None """ url = 'http://export.arxiv.org/api/query' params = { 'id_list': arxiv_id, 'max_results': 1 } try: response = self.session.get(url, params=params, timeout=15) if response.status_code == 200: # Parse Atom XML root = ET.fromstring(response.content) ns = {'atom': 'http://www.w3.org/2005/Atom', 'arxiv': 'http://arxiv.org/schemas/atom'} entry = root.find('atom:entry', ns) if entry is None: print(f'Error: No entry found for arXiv ID: {arxiv_id}', file=sys.stderr) return None # Extract DOI if published doi_elem = entry.find('arxiv:doi', ns) doi = doi_elem.text if doi_elem is not None else None # Extract journal reference if published journal_ref_elem = entry.find('arxiv:journal_ref', ns) journal_ref = journal_ref_elem.text if journal_ref_elem is not None else None # Get publication date published = entry.findtext('atom:published', '', ns) year = published[:4] if published else '' # Get authors authors = [] for author in entry.findall('atom:author', ns): name = author.findtext('atom:name', '', ns) if name: authors.append(name) metadata = { 'type': 'arxiv', 'entry_type': 'misc' if not doi else 'article', 'arxiv_id': arxiv_id, 'title': entry.findtext('atom:title', '', ns).strip().replace('\n', ' '), 'authors': ' and '.join(authors), 'year': year, 'doi': doi, 'journal_ref': journal_ref, 'abstract': entry.findtext('atom:summary', '', ns).strip().replace('\n', ' '), 'url': f'https://arxiv.org/abs/{arxiv_id}' } return metadata else: print(f'Error: arXiv API returned status {response.status_code} for ID: {arxiv_id}', file=sys.stderr) return None except Exception as e: print(f'Error extracting metadata from arXiv {arxiv_id}: {e}', file=sys.stderr) return None def metadata_to_bibtex(self, metadata: Dict, citation_key: Optional[str] = None) -> str: """ Convert metadata dictionary to BibTeX format. Args: metadata: Metadata dictionary citation_key: Optional custom citation key Returns: BibTeX string """ if not citation_key: citation_key = self._generate_citation_key(metadata) entry_type = metadata.get('entry_type', 'misc') # Build BibTeX entry lines = [f'@{entry_type}{{{citation_key},'] # Add fields if metadata.get('authors'): lines.append(f' author = {{{metadata["authors"]}}},') if metadata.get('title'): # Protect capitalization title = self._protect_title(metadata['title']) lines.append(f' title = {{{title}}},') if entry_type == 'article' and metadata.get('journal'): lines.append(f' journal = {{{metadata["journal"]}}},') elif entry_type == 'misc' and metadata.get('type') == 'arxiv': lines.append(f' howpublished = {{arXiv}},') if metadata.get('year'): lines.append(f' year = {{{metadata["year"]}}},') if metadata.get('volume'): lines.append(f' volume = {{{metadata["volume"]}}},') if metadata.get('issue'): lines.append(f' number = {{{metadata["issue"]}}},') if metadata.get('pages'): pages = metadata['pages'].replace('-', '--') # En-dash lines.append(f' pages = {{{pages}}},') if metadata.get('doi'): lines.append(f' doi = {{{metadata["doi"]}}},') elif metadata.get('url'): lines.append(f' url = {{{metadata["url"]}}},') if metadata.get('pmid'): lines.append(f' note = {{PMID: {metadata["pmid"]}}},') if metadata.get('type') == 'arxiv' and not metadata.get('doi'): lines.append(f' note = {{Preprint}},') # Remove trailing comma from last field if lines[-1].endswith(','): lines[-1] = lines[-1][:-1] lines.append('}') return '\n'.join(lines) def _crossref_type_to_bibtex(self, crossref_type: str) -> str: """Map CrossRef type to BibTeX entry type.""" type_map = { 'journal-article': 'article', 'book': 'book', 'book-chapter': 'incollection', 'proceedings-article': 'inproceedings', 'posted-content': 'misc', 'dataset': 'misc', 'report': 'techreport' } return type_map.get(crossref_type, 'misc') def _format_authors_crossref(self, authors: List[Dict]) -> str: """Format author list from CrossRef data.""" if not authors: return '' formatted = [] for author in authors: given = author.get('given', '') family = author.get('family', '') if family: if given: formatted.append(f'{family}, {given}') else: formatted.append(family) return ' and '.join(formatted) def _format_authors_pubmed(self, authors: List) -> str: """Format author list from PubMed XML.""" formatted = [] for author in authors: last_name = author.findtext('.//LastName', '') fore_name = author.findtext('.//ForeName', '') if last_name: if fore_name: formatted.append(f'{last_name}, {fore_name}') else: formatted.append(last_name) return ' and '.join(formatted) def _extract_year_crossref(self, message: Dict) -> str: """Extract year from CrossRef message.""" # Try published-print first, then published-online date_parts = message.get('published-print', {}).get('date-parts', [[]]) if not date_parts or not date_parts[0]: date_parts = message.get('published-online', {}).get('date-parts', [[]]) if date_parts and date_parts[0]: return str(date_parts[0][0]) return '' def _extract_year_pubmed(self, article: ET.Element) -> str: """Extract year from PubMed XML.""" year = article.findtext('.//Journal/JournalIssue/PubDate/Year', '') if not year: medline_date = article.findtext('.//Journal/JournalIssue/PubDate/MedlineDate', '') if medline_date: year_match = re.search(r'\d{4}', medline_date) if year_match: year = year_match.group() return year def _generate_citation_key(self, metadata: Dict) -> str: """Generate a citation key from metadata.""" # Get first author last name authors = metadata.get('authors', '') if authors: first_author = authors.split(' and ')[0] if ',' in first_author: last_name = first_author.split(',')[0].strip() else: last_name = first_author.split()[-1] if first_author else 'Unknown' else: last_name = 'Unknown' # Get year year = metadata.get('year', '').strip() if not year: year = 'XXXX' # Clean last name (remove special characters) last_name = re.sub(r'[^a-zA-Z]', '', last_name) # Get keyword from title title = metadata.get('title', '') words = re.findall(r'\b[a-zA-Z]{4,}\b', title) keyword = words[0].lower() if words else 'paper' return f'{last_name}{year}{keyword}' def _protect_title(self, title: str) -> str: """Protect capitalization in title for BibTeX.""" # Protect common acronyms and proper nouns protected_words = [ 'DNA', 'RNA', 'CRISPR', 'COVID', 'HIV', 'AIDS', 'AlphaFold', 'Python', 'AI', 'ML', 'GPU', 'CPU', 'USA', 'UK', 'EU' ] for word in protected_words: title = re.sub(rf'\b{word}\b', f'{{{word}}}', title, flags=re.IGNORECASE) return title def extract(self, identifier: str) -> Optional[str]: """ Extract metadata and return BibTeX. Args: identifier: DOI, PMID, arXiv ID, or URL Returns: BibTeX string or None """ id_type, clean_id = self.identify_type(identifier) print(f'Identified as {id_type}: {clean_id}', file=sys.stderr) metadata = None if id_type == 'doi': metadata = self.extract_from_doi(clean_id) elif id_type == 'pmid': metadata = self.extract_from_pmid(clean_id) elif id_type == 'arxiv': metadata = self.extract_from_arxiv(clean_id) else: print(f'Error: Unknown identifier type: {identifier}', file=sys.stderr) return None if metadata: return self.metadata_to_bibtex(metadata) else: return None def main(): """Command-line interface.""" parser = argparse.ArgumentParser( description='Extract citation metadata from DOI, PMID, arXiv ID, or URL', epilog='Example: python extract_metadata.py --doi 10.1038/s41586-021-03819-2' ) parser.add_argument('--doi', help='Digital Object Identifier') parser.add_argument('--pmid', help='PubMed ID') parser.add_argument('--arxiv', help='arXiv ID') parser.add_argument('--url', help='URL to article') parser.add_argument('-i', '--input', help='Input file with identifiers (one per line)') parser.add_argument('-o', '--output', help='Output file for BibTeX (default: stdout)') parser.add_argument('--format', choices=['bibtex', 'json'], default='bibtex', help='Output format') parser.add_argument('--email', help='Email for NCBI E-utilities (recommended)') args = parser.parse_args() # Collect identifiers identifiers = [] if args.doi: identifiers.append(args.doi) if args.pmid: identifiers.append(args.pmid) if args.arxiv: identifiers.append(args.arxiv) if args.url: identifiers.append(args.url) if args.input: try: with open(args.input, 'r', encoding='utf-8') as f: file_ids = [line.strip() for line in f if line.strip()] identifiers.extend(file_ids) except Exception as e: print(f'Error reading input file: {e}', file=sys.stderr) sys.exit(1) if not identifiers: parser.print_help() sys.exit(1) # Extract metadata extractor = MetadataExtractor(email=args.email) bibtex_entries = [] for i, identifier in enumerate(identifiers): print(f'\nProcessing {i+1}/{len(identifiers)}...', file=sys.stderr) bibtex = extractor.extract(identifier) if bibtex: bibtex_entries.append(bibtex) # Rate limiting if i < len(identifiers) - 1: time.sleep(0.5) if not bibtex_entries: print('Error: No successful extractions', file=sys.stderr) sys.exit(1) # Format output if args.format == 'bibtex': output = '\n\n'.join(bibtex_entries) + '\n' else: # json output = json.dumps({ 'count': len(bibtex_entries), 'entries': bibtex_entries }, indent=2) # Write output if args.output: with open(args.output, 'w', encoding='utf-8') as f: f.write(output) print(f'\nSuccessfully wrote {len(bibtex_entries)} entries to {args.output}', file=sys.stderr) else: print(output) print(f'\nExtracted {len(bibtex_entries)}/{len(identifiers)} entries', file=sys.stderr) if __name__ == '__main__': main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/citation-management/scripts/extract_metadata.py", "license": "MIT License", "lines": 457, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/citation-management/scripts/format_bibtex.py
#!/usr/bin/env python3 """ BibTeX Formatter and Cleaner Format, clean, sort, and deduplicate BibTeX files. """ import sys import re import argparse from typing import List, Dict, Tuple from collections import OrderedDict class BibTeXFormatter: """Format and clean BibTeX entries.""" def __init__(self): # Standard field order for readability self.field_order = [ 'author', 'editor', 'title', 'booktitle', 'journal', 'year', 'month', 'volume', 'number', 'pages', 'publisher', 'address', 'edition', 'series', 'school', 'institution', 'organization', 'howpublished', 'doi', 'url', 'isbn', 'issn', 'note', 'abstract', 'keywords' ] def parse_bibtex_file(self, filepath: str) -> List[Dict]: """ Parse BibTeX file and extract entries. Args: filepath: Path to BibTeX file Returns: List of entry dictionaries """ try: with open(filepath, 'r', encoding='utf-8') as f: content = f.read() except Exception as e: print(f'Error reading file: {e}', file=sys.stderr) return [] entries = [] # Match BibTeX entries pattern = r'@(\w+)\s*\{\s*([^,\s]+)\s*,(.*?)\n\}' matches = re.finditer(pattern, content, re.DOTALL | re.IGNORECASE) for match in matches: entry_type = match.group(1).lower() citation_key = match.group(2).strip() fields_text = match.group(3) # Parse fields fields = OrderedDict() field_pattern = r'(\w+)\s*=\s*\{([^}]*)\}|(\w+)\s*=\s*"([^"]*)"' field_matches = re.finditer(field_pattern, fields_text) for field_match in field_matches: if field_match.group(1): field_name = field_match.group(1).lower() field_value = field_match.group(2) else: field_name = field_match.group(3).lower() field_value = field_match.group(4) fields[field_name] = field_value.strip() entries.append({ 'type': entry_type, 'key': citation_key, 'fields': fields }) return entries def format_entry(self, entry: Dict) -> str: """ Format a single BibTeX entry. Args: entry: Entry dictionary Returns: Formatted BibTeX string """ lines = [f'@{entry["type"]}{{{entry["key"]},'] # Order fields according to standard order ordered_fields = OrderedDict() # Add fields in standard order for field_name in self.field_order: if field_name in entry['fields']: ordered_fields[field_name] = entry['fields'][field_name] # Add any remaining fields for field_name, field_value in entry['fields'].items(): if field_name not in ordered_fields: ordered_fields[field_name] = field_value # Format each field max_field_len = max(len(f) for f in ordered_fields.keys()) if ordered_fields else 0 for field_name, field_value in ordered_fields.items(): # Pad field name for alignment padded_field = field_name.ljust(max_field_len) lines.append(f' {padded_field} = {{{field_value}}},') # Remove trailing comma from last field if lines[-1].endswith(','): lines[-1] = lines[-1][:-1] lines.append('}') return '\n'.join(lines) def fix_common_issues(self, entry: Dict) -> Dict: """ Fix common formatting issues in entry. Args: entry: Entry dictionary Returns: Fixed entry dictionary """ fixed = entry.copy() fields = fixed['fields'].copy() # Fix page ranges (single hyphen to double hyphen) if 'pages' in fields: pages = fields['pages'] # Replace single hyphen with double hyphen if it's a range if re.search(r'\d-\d', pages) and '--' not in pages: pages = re.sub(r'(\d)-(\d)', r'\1--\2', pages) fields['pages'] = pages # Remove "pp." from pages if 'pages' in fields: pages = fields['pages'] pages = re.sub(r'^pp\.\s*', '', pages, flags=re.IGNORECASE) fields['pages'] = pages # Fix DOI (remove URL prefix if present) if 'doi' in fields: doi = fields['doi'] doi = doi.replace('https://doi.org/', '') doi = doi.replace('http://doi.org/', '') doi = doi.replace('doi:', '') fields['doi'] = doi # Fix author separators (semicolon or ampersand to 'and') if 'author' in fields: author = fields['author'] author = author.replace(';', ' and') author = author.replace(' & ', ' and ') # Clean up multiple 'and's author = re.sub(r'\s+and\s+and\s+', ' and ', author) fields['author'] = author fixed['fields'] = fields return fixed def deduplicate_entries(self, entries: List[Dict]) -> List[Dict]: """ Remove duplicate entries based on DOI or citation key. Args: entries: List of entry dictionaries Returns: List of unique entries """ seen_dois = set() seen_keys = set() unique_entries = [] for entry in entries: doi = entry['fields'].get('doi', '').strip() key = entry['key'] # Check DOI first (more reliable) if doi: if doi in seen_dois: print(f'Duplicate DOI found: {doi} (skipping {key})', file=sys.stderr) continue seen_dois.add(doi) # Check citation key if key in seen_keys: print(f'Duplicate citation key found: {key} (skipping)', file=sys.stderr) continue seen_keys.add(key) unique_entries.append(entry) return unique_entries def sort_entries(self, entries: List[Dict], sort_by: str = 'key', descending: bool = False) -> List[Dict]: """ Sort entries by specified field. Args: entries: List of entry dictionaries sort_by: Field to sort by ('key', 'year', 'author', 'title') descending: Sort in descending order Returns: Sorted list of entries """ def get_sort_key(entry: Dict) -> str: if sort_by == 'key': return entry['key'].lower() elif sort_by == 'year': year = entry['fields'].get('year', '9999') return year elif sort_by == 'author': author = entry['fields'].get('author', 'ZZZ') # Get last name of first author if ',' in author: return author.split(',')[0].lower() else: return author.split()[0].lower() if author else 'zzz' elif sort_by == 'title': return entry['fields'].get('title', '').lower() else: return entry['key'].lower() return sorted(entries, key=get_sort_key, reverse=descending) def format_file(self, filepath: str, output: str = None, deduplicate: bool = False, sort_by: str = None, descending: bool = False, fix_issues: bool = True) -> None: """ Format entire BibTeX file. Args: filepath: Input BibTeX file output: Output file (None for in-place) deduplicate: Remove duplicates sort_by: Field to sort by descending: Sort in descending order fix_issues: Fix common formatting issues """ print(f'Parsing {filepath}...', file=sys.stderr) entries = self.parse_bibtex_file(filepath) if not entries: print('No entries found', file=sys.stderr) return print(f'Found {len(entries)} entries', file=sys.stderr) # Fix common issues if fix_issues: print('Fixing common issues...', file=sys.stderr) entries = [self.fix_common_issues(e) for e in entries] # Deduplicate if deduplicate: print('Removing duplicates...', file=sys.stderr) original_count = len(entries) entries = self.deduplicate_entries(entries) removed = original_count - len(entries) if removed > 0: print(f'Removed {removed} duplicate(s)', file=sys.stderr) # Sort if sort_by: print(f'Sorting by {sort_by}...', file=sys.stderr) entries = self.sort_entries(entries, sort_by, descending) # Format entries print('Formatting entries...', file=sys.stderr) formatted_entries = [self.format_entry(e) for e in entries] # Write output output_content = '\n\n'.join(formatted_entries) + '\n' output_file = output or filepath try: with open(output_file, 'w', encoding='utf-8') as f: f.write(output_content) print(f'Successfully wrote {len(entries)} entries to {output_file}', file=sys.stderr) except Exception as e: print(f'Error writing file: {e}', file=sys.stderr) sys.exit(1) def main(): """Command-line interface.""" parser = argparse.ArgumentParser( description='Format, clean, sort, and deduplicate BibTeX files', epilog='Example: python format_bibtex.py references.bib --deduplicate --sort year' ) parser.add_argument( 'file', help='BibTeX file to format' ) parser.add_argument( '-o', '--output', help='Output file (default: overwrite input file)' ) parser.add_argument( '--deduplicate', action='store_true', help='Remove duplicate entries' ) parser.add_argument( '--sort', choices=['key', 'year', 'author', 'title'], help='Sort entries by field' ) parser.add_argument( '--descending', action='store_true', help='Sort in descending order' ) parser.add_argument( '--no-fix', action='store_true', help='Do not fix common issues' ) args = parser.parse_args() # Format file formatter = BibTeXFormatter() formatter.format_file( args.file, output=args.output, deduplicate=args.deduplicate, sort_by=args.sort, descending=args.descending, fix_issues=not args.no_fix ) if __name__ == '__main__': main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/citation-management/scripts/format_bibtex.py", "license": "MIT License", "lines": 281, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/citation-management/scripts/search_google_scholar.py
#!/usr/bin/env python3 """ Google Scholar Search Tool Search Google Scholar and export results. Note: This script requires the 'scholarly' library. Install with: pip install scholarly """ import sys import argparse import json import time import random from typing import List, Dict, Optional try: from scholarly import scholarly, ProxyGenerator SCHOLARLY_AVAILABLE = True except ImportError: SCHOLARLY_AVAILABLE = False print('Warning: scholarly library not installed. Install with: pip install scholarly', file=sys.stderr) class GoogleScholarSearcher: """Search Google Scholar using scholarly library.""" def __init__(self, use_proxy: bool = False): """ Initialize searcher. Args: use_proxy: Use free proxy (helps avoid rate limiting) """ if not SCHOLARLY_AVAILABLE: raise ImportError('scholarly library required. Install with: pip install scholarly') # Setup proxy if requested if use_proxy: try: pg = ProxyGenerator() pg.FreeProxies() scholarly.use_proxy(pg) print('Using free proxy', file=sys.stderr) except Exception as e: print(f'Warning: Could not setup proxy: {e}', file=sys.stderr) def search(self, query: str, max_results: int = 50, year_start: Optional[int] = None, year_end: Optional[int] = None, sort_by: str = 'relevance') -> List[Dict]: """ Search Google Scholar. Args: query: Search query max_results: Maximum number of results year_start: Start year filter year_end: End year filter sort_by: Sort order ('relevance' or 'citations') Returns: List of result dictionaries """ if not SCHOLARLY_AVAILABLE: print('Error: scholarly library not installed', file=sys.stderr) return [] print(f'Searching Google Scholar: {query}', file=sys.stderr) print(f'Max results: {max_results}', file=sys.stderr) results = [] try: # Perform search search_query = scholarly.search_pubs(query) for i, result in enumerate(search_query): if i >= max_results: break print(f'Retrieved {i+1}/{max_results}', file=sys.stderr) # Extract metadata metadata = { 'title': result.get('bib', {}).get('title', ''), 'authors': ', '.join(result.get('bib', {}).get('author', [])), 'year': result.get('bib', {}).get('pub_year', ''), 'venue': result.get('bib', {}).get('venue', ''), 'abstract': result.get('bib', {}).get('abstract', ''), 'citations': result.get('num_citations', 0), 'url': result.get('pub_url', ''), 'eprint_url': result.get('eprint_url', ''), } # Filter by year if year_start or year_end: try: pub_year = int(metadata['year']) if metadata['year'] else 0 if year_start and pub_year < year_start: continue if year_end and pub_year > year_end: continue except ValueError: pass results.append(metadata) # Rate limiting to avoid blocking time.sleep(random.uniform(2, 5)) except Exception as e: print(f'Error during search: {e}', file=sys.stderr) # Sort if requested if sort_by == 'citations' and results: results.sort(key=lambda x: x.get('citations', 0), reverse=True) return results def metadata_to_bibtex(self, metadata: Dict) -> str: """Convert metadata to BibTeX format.""" # Generate citation key if metadata.get('authors'): first_author = metadata['authors'].split(',')[0].strip() last_name = first_author.split()[-1] if first_author else 'Unknown' else: last_name = 'Unknown' year = metadata.get('year', 'XXXX') # Get keyword from title import re title = metadata.get('title', '') words = re.findall(r'\b[a-zA-Z]{4,}\b', title) keyword = words[0].lower() if words else 'paper' citation_key = f'{last_name}{year}{keyword}' # Determine entry type (guess based on venue) venue = metadata.get('venue', '').lower() if 'proceedings' in venue or 'conference' in venue: entry_type = 'inproceedings' venue_field = 'booktitle' else: entry_type = 'article' venue_field = 'journal' # Build BibTeX lines = [f'@{entry_type}{{{citation_key},'] # Convert authors format if metadata.get('authors'): authors = metadata['authors'].replace(',', ' and') lines.append(f' author = {{{authors}}},') if metadata.get('title'): lines.append(f' title = {{{metadata["title"]}}},') if metadata.get('venue'): lines.append(f' {venue_field} = {{{metadata["venue"]}}},') if metadata.get('year'): lines.append(f' year = {{{metadata["year"]}}},') if metadata.get('url'): lines.append(f' url = {{{metadata["url"]}}},') if metadata.get('citations'): lines.append(f' note = {{Cited by: {metadata["citations"]}}},') # Remove trailing comma if lines[-1].endswith(','): lines[-1] = lines[-1][:-1] lines.append('}') return '\n'.join(lines) def main(): """Command-line interface.""" parser = argparse.ArgumentParser( description='Search Google Scholar (requires scholarly library)', epilog='Example: python search_google_scholar.py "machine learning" --limit 50' ) parser.add_argument( 'query', help='Search query' ) parser.add_argument( '--limit', type=int, default=50, help='Maximum number of results (default: 50)' ) parser.add_argument( '--year-start', type=int, help='Start year for filtering' ) parser.add_argument( '--year-end', type=int, help='End year for filtering' ) parser.add_argument( '--sort-by', choices=['relevance', 'citations'], default='relevance', help='Sort order (default: relevance)' ) parser.add_argument( '--use-proxy', action='store_true', help='Use free proxy to avoid rate limiting' ) parser.add_argument( '-o', '--output', help='Output file (default: stdout)' ) parser.add_argument( '--format', choices=['json', 'bibtex'], default='json', help='Output format (default: json)' ) args = parser.parse_args() if not SCHOLARLY_AVAILABLE: print('\nError: scholarly library not installed', file=sys.stderr) print('Install with: pip install scholarly', file=sys.stderr) print('\nAlternatively, use PubMed search for biomedical literature:', file=sys.stderr) print(' python search_pubmed.py "your query"', file=sys.stderr) sys.exit(1) # Search searcher = GoogleScholarSearcher(use_proxy=args.use_proxy) results = searcher.search( args.query, max_results=args.limit, year_start=args.year_start, year_end=args.year_end, sort_by=args.sort_by ) if not results: print('No results found', file=sys.stderr) sys.exit(1) # Format output if args.format == 'json': output = json.dumps({ 'query': args.query, 'count': len(results), 'results': results }, indent=2) else: # bibtex bibtex_entries = [searcher.metadata_to_bibtex(r) for r in results] output = '\n\n'.join(bibtex_entries) + '\n' # Write output if args.output: with open(args.output, 'w', encoding='utf-8') as f: f.write(output) print(f'Wrote {len(results)} results to {args.output}', file=sys.stderr) else: print(output) print(f'\nRetrieved {len(results)} results', file=sys.stderr) if __name__ == '__main__': main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/citation-management/scripts/search_google_scholar.py", "license": "MIT License", "lines": 225, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/citation-management/scripts/search_pubmed.py
#!/usr/bin/env python3 """ PubMed Search Tool Search PubMed using E-utilities API and export results. """ import sys import os import requests import argparse import json import time import xml.etree.ElementTree as ET from typing import List, Dict, Optional from datetime import datetime class PubMedSearcher: """Search PubMed using NCBI E-utilities API.""" def __init__(self, api_key: Optional[str] = None, email: Optional[str] = None): """ Initialize searcher. Args: api_key: NCBI API key (optional but recommended) email: Email for Entrez (optional but recommended) """ self.api_key = api_key or os.getenv('NCBI_API_KEY', '') self.email = email or os.getenv('NCBI_EMAIL', '') self.base_url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/' self.session = requests.Session() # Rate limiting self.delay = 0.11 if self.api_key else 0.34 # 10/sec with key, 3/sec without def search(self, query: str, max_results: int = 100, date_start: Optional[str] = None, date_end: Optional[str] = None, publication_types: Optional[List[str]] = None) -> List[str]: """ Search PubMed and return PMIDs. Args: query: Search query max_results: Maximum number of results date_start: Start date (YYYY/MM/DD or YYYY) date_end: End date (YYYY/MM/DD or YYYY) publication_types: List of publication types to filter Returns: List of PMIDs """ # Build query with filters full_query = query # Add date range if date_start or date_end: start = date_start or '1900' end = date_end or datetime.now().strftime('%Y') full_query += f' AND {start}:{end}[Publication Date]' # Add publication types if publication_types: pub_type_query = ' OR '.join([f'"{pt}"[Publication Type]' for pt in publication_types]) full_query += f' AND ({pub_type_query})' print(f'Searching PubMed: {full_query}', file=sys.stderr) # ESearch to get PMIDs esearch_url = self.base_url + 'esearch.fcgi' params = { 'db': 'pubmed', 'term': full_query, 'retmax': max_results, 'retmode': 'json' } if self.email: params['email'] = self.email if self.api_key: params['api_key'] = self.api_key try: response = self.session.get(esearch_url, params=params, timeout=30) response.raise_for_status() data = response.json() pmids = data['esearchresult']['idlist'] count = int(data['esearchresult']['count']) print(f'Found {count} results, retrieving {len(pmids)}', file=sys.stderr) return pmids except Exception as e: print(f'Error searching PubMed: {e}', file=sys.stderr) return [] def fetch_metadata(self, pmids: List[str]) -> List[Dict]: """ Fetch metadata for PMIDs. Args: pmids: List of PubMed IDs Returns: List of metadata dictionaries """ if not pmids: return [] metadata_list = [] # Fetch in batches of 200 batch_size = 200 for i in range(0, len(pmids), batch_size): batch = pmids[i:i+batch_size] print(f'Fetching metadata for PMIDs {i+1}-{min(i+batch_size, len(pmids))}...', file=sys.stderr) efetch_url = self.base_url + 'efetch.fcgi' params = { 'db': 'pubmed', 'id': ','.join(batch), 'retmode': 'xml', 'rettype': 'abstract' } if self.email: params['email'] = self.email if self.api_key: params['api_key'] = self.api_key try: response = self.session.get(efetch_url, params=params, timeout=60) response.raise_for_status() # Parse XML root = ET.fromstring(response.content) articles = root.findall('.//PubmedArticle') for article in articles: metadata = self._extract_metadata_from_xml(article) if metadata: metadata_list.append(metadata) # Rate limiting time.sleep(self.delay) except Exception as e: print(f'Error fetching metadata for batch: {e}', file=sys.stderr) continue return metadata_list def _extract_metadata_from_xml(self, article: ET.Element) -> Optional[Dict]: """Extract metadata from PubmedArticle XML element.""" try: medline_citation = article.find('.//MedlineCitation') article_elem = medline_citation.find('.//Article') journal = article_elem.find('.//Journal') # Get PMID pmid = medline_citation.findtext('.//PMID', '') # Get DOI doi = None article_ids = article.findall('.//ArticleId') for article_id in article_ids: if article_id.get('IdType') == 'doi': doi = article_id.text break # Get authors authors = [] author_list = article_elem.find('.//AuthorList') if author_list is not None: for author in author_list.findall('.//Author'): last_name = author.findtext('.//LastName', '') fore_name = author.findtext('.//ForeName', '') if last_name: if fore_name: authors.append(f'{last_name}, {fore_name}') else: authors.append(last_name) # Get year year = article_elem.findtext('.//Journal/JournalIssue/PubDate/Year', '') if not year: medline_date = article_elem.findtext('.//Journal/JournalIssue/PubDate/MedlineDate', '') if medline_date: import re year_match = re.search(r'\d{4}', medline_date) if year_match: year = year_match.group() metadata = { 'pmid': pmid, 'doi': doi, 'title': article_elem.findtext('.//ArticleTitle', ''), 'authors': ' and '.join(authors), 'journal': journal.findtext('.//Title', ''), 'year': year, 'volume': journal.findtext('.//JournalIssue/Volume', ''), 'issue': journal.findtext('.//JournalIssue/Issue', ''), 'pages': article_elem.findtext('.//Pagination/MedlinePgn', ''), 'abstract': article_elem.findtext('.//Abstract/AbstractText', '') } return metadata except Exception as e: print(f'Error extracting metadata: {e}', file=sys.stderr) return None def metadata_to_bibtex(self, metadata: Dict) -> str: """Convert metadata to BibTeX format.""" # Generate citation key if metadata.get('authors'): first_author = metadata['authors'].split(' and ')[0] if ',' in first_author: last_name = first_author.split(',')[0].strip() else: last_name = first_author.split()[0] else: last_name = 'Unknown' year = metadata.get('year', 'XXXX') citation_key = f'{last_name}{year}pmid{metadata.get("pmid", "")}' # Build BibTeX entry lines = [f'@article{{{citation_key},'] if metadata.get('authors'): lines.append(f' author = {{{metadata["authors"]}}},') if metadata.get('title'): lines.append(f' title = {{{metadata["title"]}}},') if metadata.get('journal'): lines.append(f' journal = {{{metadata["journal"]}}},') if metadata.get('year'): lines.append(f' year = {{{metadata["year"]}}},') if metadata.get('volume'): lines.append(f' volume = {{{metadata["volume"]}}},') if metadata.get('issue'): lines.append(f' number = {{{metadata["issue"]}}},') if metadata.get('pages'): pages = metadata['pages'].replace('-', '--') lines.append(f' pages = {{{pages}}},') if metadata.get('doi'): lines.append(f' doi = {{{metadata["doi"]}}},') if metadata.get('pmid'): lines.append(f' note = {{PMID: {metadata["pmid"]}}},') # Remove trailing comma if lines[-1].endswith(','): lines[-1] = lines[-1][:-1] lines.append('}') return '\n'.join(lines) def main(): """Command-line interface.""" parser = argparse.ArgumentParser( description='Search PubMed using E-utilities API', epilog='Example: python search_pubmed.py "CRISPR gene editing" --limit 100' ) parser.add_argument( 'query', nargs='?', help='Search query (PubMed syntax)' ) parser.add_argument( '--query', dest='query_arg', help='Search query (alternative to positional argument)' ) parser.add_argument( '--query-file', help='File containing search query' ) parser.add_argument( '--limit', type=int, default=100, help='Maximum number of results (default: 100)' ) parser.add_argument( '--date-start', help='Start date (YYYY/MM/DD or YYYY)' ) parser.add_argument( '--date-end', help='End date (YYYY/MM/DD or YYYY)' ) parser.add_argument( '--publication-types', help='Comma-separated publication types (e.g., "Review,Clinical Trial")' ) parser.add_argument( '-o', '--output', help='Output file (default: stdout)' ) parser.add_argument( '--format', choices=['json', 'bibtex'], default='json', help='Output format (default: json)' ) parser.add_argument( '--api-key', help='NCBI API key (or set NCBI_API_KEY env var)' ) parser.add_argument( '--email', help='Email for Entrez (or set NCBI_EMAIL env var)' ) args = parser.parse_args() # Get query query = args.query or args.query_arg if args.query_file: try: with open(args.query_file, 'r', encoding='utf-8') as f: query = f.read().strip() except Exception as e: print(f'Error reading query file: {e}', file=sys.stderr) sys.exit(1) if not query: parser.print_help() sys.exit(1) # Parse publication types pub_types = None if args.publication_types: pub_types = [pt.strip() for pt in args.publication_types.split(',')] # Search PubMed searcher = PubMedSearcher(api_key=args.api_key, email=args.email) pmids = searcher.search( query, max_results=args.limit, date_start=args.date_start, date_end=args.date_end, publication_types=pub_types ) if not pmids: print('No results found', file=sys.stderr) sys.exit(1) # Fetch metadata metadata_list = searcher.fetch_metadata(pmids) # Format output if args.format == 'json': output = json.dumps({ 'query': query, 'count': len(metadata_list), 'results': metadata_list }, indent=2) else: # bibtex bibtex_entries = [searcher.metadata_to_bibtex(m) for m in metadata_list] output = '\n\n'.join(bibtex_entries) + '\n' # Write output if args.output: with open(args.output, 'w', encoding='utf-8') as f: f.write(output) print(f'Wrote {len(metadata_list)} results to {args.output}', file=sys.stderr) else: print(output) if __name__ == '__main__': main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/citation-management/scripts/search_pubmed.py", "license": "MIT License", "lines": 318, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/citation-management/scripts/validate_citations.py
#!/usr/bin/env python3 """ Citation Validation Tool Validate BibTeX files for accuracy, completeness, and format compliance. """ import sys import re import requests import argparse import json from typing import Dict, List, Tuple, Optional from collections import defaultdict class CitationValidator: """Validate BibTeX entries for errors and inconsistencies.""" def __init__(self): self.session = requests.Session() self.session.headers.update({ 'User-Agent': 'CitationValidator/1.0 (Citation Management Tool)' }) # Required fields by entry type self.required_fields = { 'article': ['author', 'title', 'journal', 'year'], 'book': ['title', 'publisher', 'year'], # author OR editor 'inproceedings': ['author', 'title', 'booktitle', 'year'], 'incollection': ['author', 'title', 'booktitle', 'publisher', 'year'], 'phdthesis': ['author', 'title', 'school', 'year'], 'mastersthesis': ['author', 'title', 'school', 'year'], 'techreport': ['author', 'title', 'institution', 'year'], 'misc': ['title', 'year'] } # Recommended fields self.recommended_fields = { 'article': ['volume', 'pages', 'doi'], 'book': ['isbn'], 'inproceedings': ['pages'], } def parse_bibtex_file(self, filepath: str) -> List[Dict]: """ Parse BibTeX file and extract entries. Args: filepath: Path to BibTeX file Returns: List of entry dictionaries """ try: with open(filepath, 'r', encoding='utf-8') as f: content = f.read() except Exception as e: print(f'Error reading file: {e}', file=sys.stderr) return [] entries = [] # Match BibTeX entries pattern = r'@(\w+)\s*\{\s*([^,\s]+)\s*,(.*?)\n\}' matches = re.finditer(pattern, content, re.DOTALL | re.IGNORECASE) for match in matches: entry_type = match.group(1).lower() citation_key = match.group(2).strip() fields_text = match.group(3) # Parse fields fields = {} field_pattern = r'(\w+)\s*=\s*\{([^}]*)\}|(\w+)\s*=\s*"([^"]*)"' field_matches = re.finditer(field_pattern, fields_text) for field_match in field_matches: if field_match.group(1): field_name = field_match.group(1).lower() field_value = field_match.group(2) else: field_name = field_match.group(3).lower() field_value = field_match.group(4) fields[field_name] = field_value.strip() entries.append({ 'type': entry_type, 'key': citation_key, 'fields': fields, 'raw': match.group(0) }) return entries def validate_entry(self, entry: Dict) -> Tuple[List[Dict], List[Dict]]: """ Validate a single BibTeX entry. Args: entry: Entry dictionary Returns: Tuple of (errors, warnings) """ errors = [] warnings = [] entry_type = entry['type'] key = entry['key'] fields = entry['fields'] # Check required fields if entry_type in self.required_fields: for req_field in self.required_fields[entry_type]: if req_field not in fields or not fields[req_field]: # Special case: book can have author OR editor if entry_type == 'book' and req_field == 'author': if 'editor' not in fields or not fields['editor']: errors.append({ 'type': 'missing_required_field', 'field': 'author or editor', 'severity': 'high', 'message': f'Entry {key}: Missing required field "author" or "editor"' }) else: errors.append({ 'type': 'missing_required_field', 'field': req_field, 'severity': 'high', 'message': f'Entry {key}: Missing required field "{req_field}"' }) # Check recommended fields if entry_type in self.recommended_fields: for rec_field in self.recommended_fields[entry_type]: if rec_field not in fields or not fields[rec_field]: warnings.append({ 'type': 'missing_recommended_field', 'field': rec_field, 'severity': 'medium', 'message': f'Entry {key}: Missing recommended field "{rec_field}"' }) # Validate year if 'year' in fields: year = fields['year'] if not re.match(r'^\d{4}$', year): errors.append({ 'type': 'invalid_year', 'field': 'year', 'value': year, 'severity': 'high', 'message': f'Entry {key}: Invalid year format "{year}" (should be 4 digits)' }) elif int(year) < 1600 or int(year) > 2030: warnings.append({ 'type': 'suspicious_year', 'field': 'year', 'value': year, 'severity': 'medium', 'message': f'Entry {key}: Suspicious year "{year}" (outside reasonable range)' }) # Validate DOI format if 'doi' in fields: doi = fields['doi'] if not re.match(r'^10\.\d{4,}/[^\s]+$', doi): warnings.append({ 'type': 'invalid_doi_format', 'field': 'doi', 'value': doi, 'severity': 'medium', 'message': f'Entry {key}: Invalid DOI format "{doi}"' }) # Check for single hyphen in pages (should be --) if 'pages' in fields: pages = fields['pages'] if re.search(r'\d-\d', pages) and '--' not in pages: warnings.append({ 'type': 'page_range_format', 'field': 'pages', 'value': pages, 'severity': 'low', 'message': f'Entry {key}: Page range uses single hyphen, should use -- (en-dash)' }) # Check author format if 'author' in fields: author = fields['author'] if ';' in author or '&' in author: errors.append({ 'type': 'invalid_author_format', 'field': 'author', 'severity': 'high', 'message': f'Entry {key}: Authors should be separated by " and ", not ";" or "&"' }) return errors, warnings def verify_doi(self, doi: str) -> Tuple[bool, Optional[Dict]]: """ Verify DOI resolves correctly and get metadata. Args: doi: Digital Object Identifier Returns: Tuple of (is_valid, metadata) """ try: url = f'https://doi.org/{doi}' response = self.session.head(url, timeout=10, allow_redirects=True) if response.status_code < 400: # DOI resolves, now get metadata from CrossRef crossref_url = f'https://api.crossref.org/works/{doi}' metadata_response = self.session.get(crossref_url, timeout=10) if metadata_response.status_code == 200: data = metadata_response.json() message = data.get('message', {}) # Extract key metadata metadata = { 'title': message.get('title', [''])[0], 'year': self._extract_year_crossref(message), 'authors': self._format_authors_crossref(message.get('author', [])), } return True, metadata else: return True, None # DOI resolves but no CrossRef metadata else: return False, None except Exception: return False, None def detect_duplicates(self, entries: List[Dict]) -> List[Dict]: """ Detect duplicate entries. Args: entries: List of entry dictionaries Returns: List of duplicate groups """ duplicates = [] # Check for duplicate DOIs doi_map = defaultdict(list) for entry in entries: doi = entry['fields'].get('doi', '').strip() if doi: doi_map[doi].append(entry['key']) for doi, keys in doi_map.items(): if len(keys) > 1: duplicates.append({ 'type': 'duplicate_doi', 'doi': doi, 'entries': keys, 'severity': 'high', 'message': f'Duplicate DOI {doi} found in entries: {", ".join(keys)}' }) # Check for duplicate citation keys key_counts = defaultdict(int) for entry in entries: key_counts[entry['key']] += 1 for key, count in key_counts.items(): if count > 1: duplicates.append({ 'type': 'duplicate_key', 'key': key, 'count': count, 'severity': 'high', 'message': f'Citation key "{key}" appears {count} times' }) # Check for similar titles (possible duplicates) titles = {} for entry in entries: title = entry['fields'].get('title', '').lower() title = re.sub(r'[^\w\s]', '', title) # Remove punctuation title = ' '.join(title.split()) # Normalize whitespace if title: if title in titles: duplicates.append({ 'type': 'similar_title', 'entries': [titles[title], entry['key']], 'severity': 'medium', 'message': f'Possible duplicate: "{titles[title]}" and "{entry["key"]}" have identical titles' }) else: titles[title] = entry['key'] return duplicates def validate_file(self, filepath: str, check_dois: bool = False) -> Dict: """ Validate entire BibTeX file. Args: filepath: Path to BibTeX file check_dois: Whether to verify DOIs (slow) Returns: Validation report dictionary """ print(f'Parsing {filepath}...', file=sys.stderr) entries = self.parse_bibtex_file(filepath) if not entries: return { 'total_entries': 0, 'errors': [], 'warnings': [], 'duplicates': [] } print(f'Found {len(entries)} entries', file=sys.stderr) all_errors = [] all_warnings = [] # Validate each entry for i, entry in enumerate(entries): print(f'Validating entry {i+1}/{len(entries)}: {entry["key"]}', file=sys.stderr) errors, warnings = self.validate_entry(entry) for error in errors: error['entry'] = entry['key'] all_errors.append(error) for warning in warnings: warning['entry'] = entry['key'] all_warnings.append(warning) # Check for duplicates print('Checking for duplicates...', file=sys.stderr) duplicates = self.detect_duplicates(entries) # Verify DOIs if requested doi_errors = [] if check_dois: print('Verifying DOIs...', file=sys.stderr) for i, entry in enumerate(entries): doi = entry['fields'].get('doi', '') if doi: print(f'Verifying DOI {i+1}: {doi}', file=sys.stderr) is_valid, metadata = self.verify_doi(doi) if not is_valid: doi_errors.append({ 'type': 'invalid_doi', 'entry': entry['key'], 'doi': doi, 'severity': 'high', 'message': f'Entry {entry["key"]}: DOI does not resolve: {doi}' }) all_errors.extend(doi_errors) return { 'filepath': filepath, 'total_entries': len(entries), 'valid_entries': len(entries) - len([e for e in all_errors if e['severity'] == 'high']), 'errors': all_errors, 'warnings': all_warnings, 'duplicates': duplicates } def _extract_year_crossref(self, message: Dict) -> str: """Extract year from CrossRef message.""" date_parts = message.get('published-print', {}).get('date-parts', [[]]) if not date_parts or not date_parts[0]: date_parts = message.get('published-online', {}).get('date-parts', [[]]) if date_parts and date_parts[0]: return str(date_parts[0][0]) return '' def _format_authors_crossref(self, authors: List[Dict]) -> str: """Format author list from CrossRef.""" if not authors: return '' formatted = [] for author in authors[:3]: # First 3 authors given = author.get('given', '') family = author.get('family', '') if family: formatted.append(f'{family}, {given}' if given else family) if len(authors) > 3: formatted.append('et al.') return ', '.join(formatted) def main(): """Command-line interface.""" parser = argparse.ArgumentParser( description='Validate BibTeX files for errors and inconsistencies', epilog='Example: python validate_citations.py references.bib' ) parser.add_argument( 'file', help='BibTeX file to validate' ) parser.add_argument( '--check-dois', action='store_true', help='Verify DOIs resolve correctly (slow)' ) parser.add_argument( '--auto-fix', action='store_true', help='Attempt to auto-fix common issues (not implemented yet)' ) parser.add_argument( '--report', help='Output file for JSON validation report' ) parser.add_argument( '--verbose', action='store_true', help='Show detailed output' ) args = parser.parse_args() # Validate file validator = CitationValidator() report = validator.validate_file(args.file, check_dois=args.check_dois) # Print summary print('\n' + '='*60) print('CITATION VALIDATION REPORT') print('='*60) print(f'\nFile: {args.file}') print(f'Total entries: {report["total_entries"]}') print(f'Valid entries: {report["valid_entries"]}') print(f'Errors: {len(report["errors"])}') print(f'Warnings: {len(report["warnings"])}') print(f'Duplicates: {len(report["duplicates"])}') # Print errors if report['errors']: print('\n' + '-'*60) print('ERRORS (must fix):') print('-'*60) for error in report['errors']: print(f'\n{error["message"]}') if args.verbose: print(f' Type: {error["type"]}') print(f' Severity: {error["severity"]}') # Print warnings if report['warnings'] and args.verbose: print('\n' + '-'*60) print('WARNINGS (should fix):') print('-'*60) for warning in report['warnings']: print(f'\n{warning["message"]}') # Print duplicates if report['duplicates']: print('\n' + '-'*60) print('DUPLICATES:') print('-'*60) for dup in report['duplicates']: print(f'\n{dup["message"]}') # Save report if args.report: with open(args.report, 'w', encoding='utf-8') as f: json.dump(report, f, indent=2) print(f'\nDetailed report saved to: {args.report}') # Exit with error code if there are errors if report['errors']: sys.exit(1) if __name__ == '__main__': main()
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/citation-management/scripts/validate_citations.py", "license": "MIT License", "lines": 415, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/clinical-decision-support/scripts/biomarker_classifier.py
#!/usr/bin/env python3 """ Biomarker-Based Patient Stratification and Classification Performs patient stratification based on biomarker profiles with: - Binary classification (biomarker+/-) - Multi-class molecular subtypes - Continuous biomarker scoring - Correlation with clinical outcomes Dependencies: pandas, numpy, scipy, scikit-learn (optional for clustering) """ import pandas as pd import numpy as np from scipy import stats import argparse from pathlib import Path def classify_binary_biomarker(data, biomarker_col, threshold, above_label='Biomarker+', below_label='Biomarker-'): """ Binary classification based on biomarker threshold. Parameters: data: DataFrame biomarker_col: Column name for biomarker values threshold: Cut-point value above_label: Label for values >= threshold below_label: Label for values < threshold Returns: DataFrame with added 'biomarker_class' column """ data = data.copy() data['biomarker_class'] = data[biomarker_col].apply( lambda x: above_label if x >= threshold else below_label ) return data def classify_pd_l1_tps(data, pd_l1_col='pd_l1_tps'): """ Classify PD-L1 Tumor Proportion Score into clinical categories. Categories: - Negative: <1% - Low: 1-49% - High: >=50% Returns: DataFrame with 'pd_l1_category' column """ data = data.copy() def categorize(tps): if tps < 1: return 'PD-L1 Negative (<1%)' elif tps < 50: return 'PD-L1 Low (1-49%)' else: return 'PD-L1 High (≥50%)' data['pd_l1_category'] = data[pd_l1_col].apply(categorize) # Distribution print("\nPD-L1 TPS Distribution:") print(data['pd_l1_category'].value_counts()) return data def classify_her2_status(data, ihc_col='her2_ihc', fish_col='her2_fish'): """ Classify HER2 status based on IHC and FISH results (ASCO/CAP guidelines). IHC Scores: 0, 1+, 2+, 3+ FISH: Positive, Negative (if IHC 2+) Classification: - HER2-positive: IHC 3+ OR IHC 2+/FISH+ - HER2-negative: IHC 0/1+ OR IHC 2+/FISH- - HER2-low: IHC 1+ or IHC 2+/FISH- (subset of HER2-negative) Returns: DataFrame with 'her2_status' and 'her2_low' columns """ data = data.copy() def classify_her2(row): ihc = row[ihc_col] fish = row.get(fish_col, None) if ihc == '3+': status = 'HER2-positive' her2_low = False elif ihc == '2+': if fish == 'Positive': status = 'HER2-positive' her2_low = False elif fish == 'Negative': status = 'HER2-negative' her2_low = True # HER2-low else: status = 'HER2-equivocal (FISH needed)' her2_low = False elif ihc == '1+': status = 'HER2-negative' her2_low = True # HER2-low else: # IHC 0 status = 'HER2-negative' her2_low = False return pd.Series({'her2_status': status, 'her2_low': her2_low}) data[['her2_status', 'her2_low']] = data.apply(classify_her2, axis=1) print("\nHER2 Status Distribution:") print(data['her2_status'].value_counts()) print(f"\nHER2-low (IHC 1+ or 2+/FISH-): {data['her2_low'].sum()} patients") return data def classify_breast_cancer_subtype(data, er_col='er_positive', pr_col='pr_positive', her2_col='her2_positive'): """ Classify breast cancer into molecular subtypes. Subtypes: - HR+/HER2-: Luminal (ER+ and/or PR+, HER2-) - HER2+: Any HER2-positive (regardless of HR status) - Triple-negative: ER-, PR-, HER2- Returns: DataFrame with 'bc_subtype' column """ data = data.copy() def get_subtype(row): er = row[er_col] pr = row[pr_col] her2 = row[her2_col] if her2: if er or pr: return 'HR+/HER2+ (Luminal B HER2+)' else: return 'HR-/HER2+ (HER2-enriched)' elif er or pr: return 'HR+/HER2- (Luminal)' else: return 'Triple-Negative' data['bc_subtype'] = data.apply(get_subtype, axis=1) print("\nBreast Cancer Subtype Distribution:") print(data['bc_subtype'].value_counts()) return data def correlate_biomarker_outcome(data, biomarker_col, outcome_col, biomarker_type='binary'): """ Assess correlation between biomarker and clinical outcome. Parameters: biomarker_col: Biomarker variable outcome_col: Outcome variable biomarker_type: 'binary', 'categorical', 'continuous' Returns: Statistical test results """ print(f"\nCorrelation Analysis: {biomarker_col} vs {outcome_col}") print("="*60) # Remove missing data analysis_data = data[[biomarker_col, outcome_col]].dropna() if biomarker_type == 'binary' or biomarker_type == 'categorical': # Cross-tabulation contingency = pd.crosstab(analysis_data[biomarker_col], analysis_data[outcome_col]) print("\nContingency Table:") print(contingency) # Chi-square test chi2, p_value, dof, expected = stats.chi2_contingency(contingency) print(f"\nChi-square test:") print(f" χ² = {chi2:.2f}, df = {dof}, p = {p_value:.4f}") # Odds ratio if 2x2 table if contingency.shape == (2, 2): a, b = contingency.iloc[0, :] c, d = contingency.iloc[1, :] or_value = (a * d) / (b * c) if b * c > 0 else np.inf # Confidence interval for OR (log method) log_or = np.log(or_value) se_log_or = np.sqrt(1/a + 1/b + 1/c + 1/d) ci_lower = np.exp(log_or - 1.96 * se_log_or) ci_upper = np.exp(log_or + 1.96 * se_log_or) print(f"\nOdds Ratio: {or_value:.2f} (95% CI {ci_lower:.2f}-{ci_upper:.2f})") elif biomarker_type == 'continuous': # Correlation coefficient r, p_value = stats.pearsonr(analysis_data[biomarker_col], analysis_data[outcome_col]) print(f"\nPearson correlation:") print(f" r = {r:.3f}, p = {p_value:.4f}") # Also report Spearman for robustness rho, p_spearman = stats.spearmanr(analysis_data[biomarker_col], analysis_data[outcome_col]) print(f"Spearman correlation:") print(f" ρ = {rho:.3f}, p = {p_spearman:.4f}") return p_value def stratify_cohort_report(data, stratification_var, output_dir='stratification_report'): """ Generate comprehensive stratification report. Parameters: data: DataFrame with patient data stratification_var: Column name for stratification output_dir: Output directory for reports """ output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) print(f"\nCOHORT STRATIFICATION REPORT") print("="*60) print(f"Stratification Variable: {stratification_var}") print(f"Total Patients: {len(data)}") # Group distribution distribution = data[stratification_var].value_counts() print(f"\nGroup Distribution:") for group, count in distribution.items(): pct = count / len(data) * 100 print(f" {group}: {count} ({pct:.1f}%)") # Save distribution distribution.to_csv(output_dir / 'group_distribution.csv') # Compare baseline characteristics across groups print(f"\nBaseline Characteristics by {stratification_var}:") results = [] # Continuous variables continuous_vars = data.select_dtypes(include=[np.number]).columns.tolist() continuous_vars = [v for v in continuous_vars if v != stratification_var] for var in continuous_vars[:5]: # Limit to first 5 for demo print(f"\n{var}:") for group in distribution.index: group_data = data[data[stratification_var] == group][var].dropna() print(f" {group}: median {group_data.median():.1f} [IQR {group_data.quantile(0.25):.1f}-{group_data.quantile(0.75):.1f}]") # Statistical test if len(distribution) == 2: groups_list = distribution.index.tolist() g1 = data[data[stratification_var] == groups_list[0]][var].dropna() g2 = data[data[stratification_var] == groups_list[1]][var].dropna() _, p_value = stats.mannwhitneyu(g1, g2, alternative='two-sided') print(f" p-value: {p_value:.4f}") results.append({ 'Variable': var, 'Test': 'Mann-Whitney U', 'p_value': p_value, 'Significant': 'Yes' if p_value < 0.05 else 'No' }) # Save results if results: df_results = pd.DataFrame(results) df_results.to_csv(output_dir / 'statistical_comparisons.csv', index=False) print(f"\nStatistical comparison results saved to: {output_dir}/statistical_comparisons.csv") print(f"\nStratification report complete! Files saved to {output_dir}/") def main(): parser = argparse.ArgumentParser(description='Biomarker-based patient classification') parser.add_argument('input_file', type=str, nargs='?', default=None, help='CSV file with patient and biomarker data') parser.add_argument('-b', '--biomarker', type=str, default=None, help='Biomarker column name for stratification') parser.add_argument('-t', '--threshold', type=float, default=None, help='Threshold for binary classification') parser.add_argument('-o', '--output-dir', type=str, default='stratification', help='Output directory') parser.add_argument('--example', action='store_true', help='Run with example data') args = parser.parse_args() # Example data if requested if args.example or args.input_file is None: print("Generating example dataset...") np.random.seed(42) n = 80 data = pd.DataFrame({ 'patient_id': [f'PT{i:03d}' for i in range(1, n+1)], 'age': np.random.normal(62, 10, n), 'sex': np.random.choice(['Male', 'Female'], n), 'pd_l1_tps': np.random.exponential(20, n), # Exponential distribution for PD-L1 'tmb': np.random.exponential(8, n), # Mutations per Mb 'her2_ihc': np.random.choice(['0', '1+', '2+', '3+'], n, p=[0.6, 0.2, 0.15, 0.05]), 'response': np.random.choice(['Yes', 'No'], n, p=[0.4, 0.6]), }) # Simulate correlation: higher PD-L1 -> better response data.loc[data['pd_l1_tps'] >= 50, 'response'] = np.random.choice(['Yes', 'No'], (data['pd_l1_tps'] >= 50).sum(), p=[0.65, 0.35]) else: print(f"Loading data from {args.input_file}...") data = pd.read_csv(args.input_file) print(f"Dataset: {len(data)} patients") print(f"Columns: {list(data.columns)}") # PD-L1 classification example if 'pd_l1_tps' in data.columns or args.biomarker == 'pd_l1_tps': data = classify_pd_l1_tps(data, 'pd_l1_tps') # Correlate with response if available if 'response' in data.columns: correlate_biomarker_outcome(data, 'pd_l1_category', 'response', biomarker_type='categorical') # HER2 classification if columns present if 'her2_ihc' in data.columns: if 'her2_fish' not in data.columns: # Add placeholder FISH for IHC 2+ data['her2_fish'] = np.nan data = classify_her2_status(data, 'her2_ihc', 'her2_fish') # Generic binary classification if threshold provided if args.biomarker and args.threshold is not None: print(f"\nBinary classification: {args.biomarker} with threshold {args.threshold}") data = classify_binary_biomarker(data, args.biomarker, args.threshold) print(data['biomarker_class'].value_counts()) # Generate stratification report if args.biomarker: stratify_cohort_report(data, args.biomarker, output_dir=args.output_dir) elif 'pd_l1_category' in data.columns: stratify_cohort_report(data, 'pd_l1_category', output_dir=args.output_dir) # Save classified data output_path = Path(args.output_dir) / 'classified_data.csv' data.to_csv(output_path, index=False) print(f"\nClassified data saved to: {output_path}") if __name__ == '__main__': main() # Example usage: # python biomarker_classifier.py data.csv -b pd_l1_tps -t 50 -o classification/ # python biomarker_classifier.py --example # # Input CSV format: # patient_id,pd_l1_tps,tmb,her2_ihc,response,pfs_months,event # PT001,55.5,12.3,1+,Yes,14.2,1 # PT002,8.2,5.1,0,No,6.5,1 # ...
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/clinical-decision-support/scripts/biomarker_classifier.py", "license": "MIT License", "lines": 295, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/clinical-decision-support/scripts/build_decision_tree.py
#!/usr/bin/env python3 """ Build Clinical Decision Tree Flowcharts in TikZ Format Generates LaTeX/TikZ code for clinical decision algorithms from simple text or YAML descriptions. Dependencies: pyyaml (optional, for YAML input) """ import argparse from pathlib import Path import json class DecisionNode: """Represents a decision point in the clinical algorithm.""" def __init__(self, question, yes_path=None, no_path=None, node_id=None): self.question = question self.yes_path = yes_path self.no_path = no_path self.node_id = node_id or self._generate_id(question) def _generate_id(self, text): """Generate clean node ID from text.""" return ''.join(c for c in text if c.isalnum())[:15].lower() class ActionNode: """Represents an action/outcome in the clinical algorithm.""" def __init__(self, action, urgency='routine', node_id=None): self.action = action self.urgency = urgency # 'urgent', 'semiurgent', 'routine' self.node_id = node_id or self._generate_id(action) def _generate_id(self, text): return ''.join(c for c in text if c.isalnum())[:15].lower() def generate_tikz_header(): """Generate TikZ preamble with style definitions.""" tikz = """\\documentclass[10pt]{article} \\usepackage[margin=0.5in, landscape]{geometry} \\usepackage{tikz} \\usetikzlibrary{shapes,arrows,positioning} \\usepackage{xcolor} % Color definitions \\definecolor{urgentred}{RGB}{220,20,60} \\definecolor{actiongreen}{RGB}{0,153,76} \\definecolor{decisionyellow}{RGB}{255,193,7} \\definecolor{routineblue}{RGB}{100,181,246} \\definecolor{headerblue}{RGB}{0,102,204} % TikZ styles \\tikzstyle{startstop} = [rectangle, rounded corners=8pt, minimum width=3cm, minimum height=1cm, text centered, draw=black, fill=headerblue!20, font=\\small\\bfseries] \\tikzstyle{decision} = [diamond, minimum width=3cm, minimum height=1.2cm, text centered, draw=black, fill=decisionyellow!40, font=\\small, aspect=2, inner sep=0pt, text width=3.5cm] \\tikzstyle{process} = [rectangle, rounded corners=4pt, minimum width=3.5cm, minimum height=0.9cm, text centered, draw=black, fill=actiongreen!20, font=\\small] \\tikzstyle{urgent} = [rectangle, rounded corners=4pt, minimum width=3.5cm, minimum height=0.9cm, text centered, draw=urgentred, line width=1.5pt, fill=urgentred!15, font=\\small\\bfseries] \\tikzstyle{routine} = [rectangle, rounded corners=4pt, minimum width=3.5cm, minimum height=0.9cm, text centered, draw=black, fill=routineblue!20, font=\\small] \\tikzstyle{arrow} = [thick,->,>=stealth] \\tikzstyle{urgentarrow} = [ultra thick,->,>=stealth,color=urgentred] \\begin{document} \\begin{center} {\\Large\\bfseries Clinical Decision Algorithm}\\\\[10pt] {\\large [TITLE TO BE SPECIFIED]} \\end{center} \\vspace{10pt} \\begin{tikzpicture}[node distance=2.2cm and 3.5cm, auto] """ return tikz def generate_tikz_footer(): """Generate TikZ closing code.""" tikz = """ \\end{tikzpicture} \\end{document} """ return tikz def simple_algorithm_to_tikz(algorithm_text, output_file='algorithm.tex'): """ Convert simple text-based algorithm to TikZ flowchart. Input format (simple question-action pairs): START: Chief complaint Q1: High-risk criteria present? -> YES: Immediate action (URGENT) | NO: Continue Q2: Risk score >= 3? -> YES: Admit ICU | NO: Outpatient management (ROUTINE) END: Final outcome Parameters: algorithm_text: Multi-line string with algorithm output_file: Path to save .tex file """ tikz_code = generate_tikz_header() # Parse algorithm text lines = [line.strip() for line in algorithm_text.strip().split('\n') if line.strip()] node_defs = [] arrow_defs = [] previous_node = None node_counter = 0 for line in lines: if line.startswith('START:'): # Start node text = line.replace('START:', '').strip() node_id = 'start' node_defs.append(f"\\node [startstop] ({node_id}) {{{text}}};") previous_node = node_id node_counter += 1 elif line.startswith('END:'): # End node text = line.replace('END:', '').strip() node_id = 'end' # Position relative to previous if previous_node: node_defs.append(f"\\node [startstop, below=of {previous_node}] ({node_id}) {{{text}}};") arrow_defs.append(f"\\draw [arrow] ({previous_node}) -- ({node_id});") elif line.startswith('Q'): # Decision node parts = line.split(':', 1) if len(parts) < 2: continue question_part = parts[1].split('->')[0].strip() node_id = f'q{node_counter}' # Add decision node if previous_node: node_defs.append(f"\\node [decision, below=of {previous_node}] ({node_id}) {{{question_part}}};") arrow_defs.append(f"\\draw [arrow] ({previous_node}) -- ({node_id});") else: node_defs.append(f"\\node [decision] ({node_id}) {{{question_part}}};") # Parse YES and NO branches if '->' in line: branches = line.split('->')[1].split('|') for branch in branches: branch = branch.strip() if branch.startswith('YES:'): yes_action = branch.replace('YES:', '').strip() yes_id = f'yes{node_counter}' # Check urgency if '(URGENT)' in yes_action: style = 'urgent' yes_action = yes_action.replace('(URGENT)', '').strip() arrow_style = 'urgentarrow' elif '(ROUTINE)' in yes_action: style = 'routine' yes_action = yes_action.replace('(ROUTINE)', '').strip() arrow_style = 'arrow' else: style = 'process' arrow_style = 'arrow' node_defs.append(f"\\node [{style}, left=of {node_id}] ({yes_id}) {{{yes_action}}};") arrow_defs.append(f"\\draw [{arrow_style}] ({node_id}) -- node[above] {{Yes}} ({yes_id});") elif branch.startswith('NO:'): no_action = branch.replace('NO:', '').strip() no_id = f'no{node_counter}' # Check urgency if '(URGENT)' in no_action: style = 'urgent' no_action = no_action.replace('(URGENT)', '').strip() arrow_style = 'urgentarrow' elif '(ROUTINE)' in no_action: style = 'routine' no_action = no_action.replace('(ROUTINE)', '').strip() arrow_style = 'arrow' else: style = 'process' arrow_style = 'arrow' node_defs.append(f"\\node [{style}, right=of {node_id}] ({no_id}) {{{no_action}}};") arrow_defs.append(f"\\draw [{arrow_style}] ({node_id}) -- node[above] {{No}} ({no_id});") previous_node = node_id node_counter += 1 # Add all nodes and arrows to TikZ tikz_code += '\n'.join(node_defs) + '\n\n' tikz_code += '% Arrows\n' tikz_code += '\n'.join(arrow_defs) + '\n' tikz_code += generate_tikz_footer() # Save to file with open(output_file, 'w') as f: f.write(tikz_code) print(f"TikZ flowchart saved to: {output_file}") print(f"Compile with: pdflatex {output_file}") return tikz_code def json_to_tikz(json_file, output_file='algorithm.tex'): """ Convert JSON decision tree specification to TikZ flowchart. JSON format: { "title": "Algorithm Title", "nodes": { "start": {"type": "start", "text": "Patient presentation"}, "q1": {"type": "decision", "text": "Criteria met?", "yes": "action1", "no": "q2"}, "action1": {"type": "action", "text": "Immediate intervention", "urgency": "urgent"}, "q2": {"type": "decision", "text": "Score >= 3?", "yes": "action2", "no": "action3"}, "action2": {"type": "action", "text": "Admit ICU"}, "action3": {"type": "action", "text": "Outpatient", "urgency": "routine"} }, "start_node": "start" } """ with open(json_file, 'r') as f: spec = json.load(f) tikz_code = generate_tikz_header() # Replace title title = spec.get('title', 'Clinical Decision Algorithm') tikz_code = tikz_code.replace('[TITLE TO BE SPECIFIED]', title) nodes = spec['nodes'] start_node = spec.get('start_node', 'start') # Generate nodes (simplified layout - vertical) node_defs = [] arrow_defs = [] # Track positioning previous_node = None level = 0 def add_node(node_id, position_rel=None): """Recursively add nodes.""" if node_id not in nodes: return node = nodes[node_id] node_type = node['type'] text = node['text'] # Determine TikZ style if node_type == 'start' or node_type == 'end': style = 'startstop' elif node_type == 'decision': style = 'decision' elif node_type == 'action': urgency = node.get('urgency', 'normal') if urgency == 'urgent': style = 'urgent' elif urgency == 'routine': style = 'routine' else: style = 'process' else: style = 'process' # Position node if position_rel: node_def = f"\\node [{style}, {position_rel}] ({node_id}) {{{text}}};" else: node_def = f"\\node [{style}] ({node_id}) {{{text}}};" node_defs.append(node_def) # Add arrows for decision nodes if node_type == 'decision': yes_target = node.get('yes') no_target = node.get('no') if yes_target: # Determine arrow style based on target urgency target_node = nodes.get(yes_target, {}) arrow_style = 'urgentarrow' if target_node.get('urgency') == 'urgent' else 'arrow' arrow_defs.append(f"\\draw [{arrow_style}] ({node_id}) -| node[near start, above] {{Yes}} ({yes_target});") if no_target: target_node = nodes.get(no_target, {}) arrow_style = 'urgentarrow' if target_node.get('urgency') == 'urgent' else 'arrow' arrow_defs.append(f"\\draw [{arrow_style}] ({node_id}) -| node[near start, above] {{No}} ({no_target});") # Simple layout - just list nodes (manual positioning in JSON works better for complex trees) for node_id in nodes.keys(): add_node(node_id) tikz_code += '\n'.join(node_defs) + '\n\n' tikz_code += '% Arrows\n' tikz_code += '\n'.join(arrow_defs) + '\n' tikz_code += generate_tikz_footer() # Save with open(output_file, 'w') as f: f.write(tikz_code) print(f"TikZ flowchart saved to: {output_file}") return tikz_code def create_example_json(): """Create example JSON specification for testing.""" example = { "title": "Acute Chest Pain Management Algorithm", "nodes": { "start": { "type": "start", "text": "Patient with\\nchest pain" }, "q1": { "type": "decision", "text": "STEMI\\ncriteria?", "yes": "stemi_action", "no": "q2" }, "stemi_action": { "type": "action", "text": "Activate cath lab\\nAspirin, heparin\\nPrimary PCI", "urgency": "urgent" }, "q2": { "type": "decision", "text": "High-risk\\nfeatures?", "yes": "admit", "no": "q3" }, "admit": { "type": "action", "text": "Admit CCU\\nSerial troponins\\nEarly angiography" }, "q3": { "type": "decision", "text": "TIMI\\nscore 0-1?", "yes": "lowrisk", "no": "moderate" }, "lowrisk": { "type": "action", "text": "Observe 6-12h\\nStress test\\nOutpatient f/u", "urgency": "routine" }, "moderate": { "type": "action", "text": "Admit telemetry\\nMedical management\\nRisk stratification" } }, "start_node": "start" } return example def main(): parser = argparse.ArgumentParser(description='Build clinical decision tree flowcharts') parser.add_argument('-i', '--input', type=str, default=None, help='Input file (JSON format)') parser.add_argument('-o', '--output', type=str, default='clinical_algorithm.tex', help='Output .tex file') parser.add_argument('--example', action='store_true', help='Generate example algorithm') parser.add_argument('--text', type=str, default=None, help='Simple text algorithm (see format in docstring)') args = parser.parse_args() if args.example: print("Generating example algorithm...") example_spec = create_example_json() # Save example JSON with open('example_algorithm.json', 'w') as f: json.dump(example_spec, f, indent=2) print("Example JSON saved to: example_algorithm.json") # Generate TikZ from example json_to_tikz('example_algorithm.json', args.output) elif args.text: print("Generating algorithm from text...") simple_algorithm_to_tikz(args.text, args.output) elif args.input: print(f"Generating algorithm from {args.input}...") if args.input.endswith('.json'): json_to_tikz(args.input, args.output) else: with open(args.input, 'r') as f: text = f.read() simple_algorithm_to_tikz(text, args.output) else: print("No input provided. Use --example to generate example, --text for simple text, or -i for JSON input.") print("\nSimple text format:") print("START: Patient presentation") print("Q1: Criteria met? -> YES: Action (URGENT) | NO: Continue") print("Q2: Score >= 3? -> YES: Admit | NO: Outpatient (ROUTINE)") print("END: Follow-up") if __name__ == '__main__': main() # Example usage: # python build_decision_tree.py --example # python build_decision_tree.py -i algorithm_spec.json -o my_algorithm.tex # # Then compile: # pdflatex clinical_algorithm.tex
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/clinical-decision-support/scripts/build_decision_tree.py", "license": "MIT License", "lines": 351, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
davila7/claude-code-templates:cli-tool/components/skills/scientific/clinical-decision-support/scripts/generate_survival_analysis.py
#!/usr/bin/env python3 """ Generate Kaplan-Meier Survival Curves for Clinical Decision Support Documents This script creates publication-quality survival curves with: - Kaplan-Meier survival estimates - 95% confidence intervals - Log-rank test statistics - Hazard ratios with confidence intervals - Number at risk tables - Median survival annotations Dependencies: lifelines, matplotlib, pandas, numpy """ import pandas as pd import numpy as np import matplotlib.pyplot as plt from lifelines import KaplanMeierFitter from lifelines.statistics import logrank_test, multivariate_logrank_test from lifelines import CoxPHFitter import argparse from pathlib import Path def load_survival_data(filepath): """ Load survival data from CSV file. Expected columns: - patient_id: Unique patient identifier - time: Survival time (months or days) - event: Event indicator (1=event occurred, 0=censored) - group: Stratification variable (e.g., 'Biomarker+', 'Biomarker-') - Optional: Additional covariates for Cox regression Returns: pandas.DataFrame """ df = pd.read_csv(filepath) # Validate required columns required_cols = ['patient_id', 'time', 'event', 'group'] missing = [col for col in required_cols if col not in df.columns] if missing: raise ValueError(f"Missing required columns: {missing}") # Convert event to boolean if needed df['event'] = df['event'].astype(bool) return df def calculate_median_survival(kmf): """Calculate median survival with 95% CI.""" median = kmf.median_survival_time_ ci = kmf.confidence_interval_survival_function_ # Find time when survival crosses 0.5 if median == np.inf: return None, None, None # Get CI at median idx = np.argmin(np.abs(kmf.survival_function_.index - median)) lower_ci = ci.iloc[idx]['KM_estimate_lower_0.95'] upper_ci = ci.iloc[idx]['KM_estimate_upper_0.95'] return median, lower_ci, upper_ci def generate_kaplan_meier_plot(data, time_col='time', event_col='event', group_col='group', output_path='survival_curve.pdf', title='Kaplan-Meier Survival Curve', xlabel='Time (months)', ylabel='Survival Probability'): """ Generate Kaplan-Meier survival curve comparing groups. Parameters: data: DataFrame with survival data time_col: Column name for survival time event_col: Column name for event indicator group_col: Column name for stratification output_path: Path to save figure title: Plot title xlabel: X-axis label (specify units) ylabel: Y-axis label """ # Create figure and axis fig, ax = plt.subplots(figsize=(10, 6)) # Get unique groups groups = data[group_col].unique() # Colors for groups (colorblind-friendly) colors = ['#0173B2', '#DE8F05', '#029E73', '#CC78BC', '#CA9161'] kmf_models = {} median_survivals = {} # Plot each group for i, group in enumerate(groups): group_data = data[data[group_col] == group] # Fit Kaplan-Meier kmf = KaplanMeierFitter() kmf.fit(group_data[time_col], group_data[event_col], label=str(group)) # Plot survival curve kmf.plot_survival_function(ax=ax, ci_show=True, color=colors[i % len(colors)], linewidth=2, alpha=0.8) # Store model kmf_models[group] = kmf # Calculate median survival median, lower, upper = calculate_median_survival(kmf) median_survivals[group] = (median, lower, upper) # Log-rank test if len(groups) == 2: group1_data = data[data[group_col] == groups[0]] group2_data = data[data[group_col] == groups[1]] results = logrank_test( group1_data[time_col], group2_data[time_col], group1_data[event_col], group2_data[event_col] ) p_value = results.p_value test_statistic = results.test_statistic # Add log-rank test result to plot ax.text(0.02, 0.15, f'Log-rank test:\np = {p_value:.4f}', transform=ax.transAxes, fontsize=10, verticalalignment='top', bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5)) else: # Multivariate log-rank for >2 groups results = multivariate_logrank_test(data[time_col], data[group_col], data[event_col]) p_value = results.p_value test_statistic = results.test_statistic ax.text(0.02, 0.15, f'Log-rank test:\np = {p_value:.4f}\n({len(groups)} groups)', transform=ax.transAxes, fontsize=10, verticalalignment='top', bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5)) # Add median survival annotations y_pos = 0.95 for group, (median, lower, upper) in median_survivals.items(): if median is not None: ax.text(0.98, y_pos, f'{group}: {median:.1f} months (95% CI {lower:.1f}-{upper:.1f})', transform=ax.transAxes, fontsize=9, ha='right', verticalalignment='top') else: ax.text(0.98, y_pos, f'{group}: Not reached', transform=ax.transAxes, fontsize=9, ha='right', verticalalignment='top') y_pos -= 0.05 # Formatting ax.set_xlabel(xlabel, fontsize=12, fontweight='bold') ax.set_ylabel(ylabel, fontsize=12, fontweight='bold') ax.set_title(title, fontsize=14, fontweight='bold', pad=15) ax.legend(loc='lower left', frameon=True, fontsize=10) ax.grid(True, alpha=0.3, linestyle='--') ax.set_ylim([0, 1.05]) plt.tight_layout() # Save figure plt.savefig(output_path, dpi=300, bbox_inches='tight') print(f"Survival curve saved to: {output_path}") # Also save as PNG for easy viewing png_path = Path(output_path).with_suffix('.png') plt.savefig(png_path, dpi=300, bbox_inches='tight') print(f"PNG version saved to: {png_path}") plt.close() return kmf_models, p_value def generate_number_at_risk_table(data, time_col='time', event_col='event', group_col='group', time_points=None): """ Generate number at risk table for survival analysis. Parameters: data: DataFrame with survival data time_points: List of time points for risk table (if None, auto-generate) Returns: DataFrame with number at risk at each time point """ if time_points is None: # Auto-generate time points (every 6 months up to max time) max_time = data[time_col].max() time_points = np.arange(0, max_time + 6, 6) groups = data[group_col].unique() risk_table = pd.DataFrame(index=time_points, columns=groups) for group in groups: group_data = data[data[group_col] == group] for t in time_points: # Number at risk = patients who haven't had event and haven't been censored before time t at_risk = len(group_data[group_data[time_col] >= t]) risk_table.loc[t, group] = at_risk return risk_table def calculate_hazard_ratio(data, time_col='time', event_col='event', group_col='group', reference_group=None): """ Calculate hazard ratio using Cox proportional hazards regression. Parameters: data: DataFrame reference_group: Reference group for comparison (if None, uses first group) Returns: Hazard ratio, 95% CI, p-value """ # Encode group as binary for Cox regression groups = data[group_col].unique() if len(groups) != 2: print("Warning: Cox HR calculation assumes 2 groups. Using first 2 groups.") groups = groups[:2] if reference_group is None: reference_group = groups[0] # Create binary indicator (1 for comparison group, 0 for reference) data_cox = data.copy() data_cox['group_binary'] = (data_cox[group_col] != reference_group).astype(int) # Fit Cox model cph = CoxPHFitter() cph.fit(data_cox[[time_col, event_col, 'group_binary']], duration_col=time_col, event_col=event_col) # Extract results hr = np.exp(cph.params_['group_binary']) ci = np.exp(cph.confidence_intervals_.loc['group_binary'].values) p_value = cph.summary.loc['group_binary', 'p'] return hr, ci[0], ci[1], p_value def generate_report(data, output_dir, prefix='survival'): """ Generate comprehensive survival analysis report. Creates: - Kaplan-Meier curves (PDF and PNG) - Number at risk table (CSV) - Statistical summary (TXT) - LaTeX table code (TEX) """ output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) # Generate survival curve kmf_models, logrank_p = generate_kaplan_meier_plot( data, output_path=output_dir / f'{prefix}_kaplan_meier.pdf', title='Survival Analysis by Group' ) # Number at risk table risk_table = generate_number_at_risk_table(data) risk_table.to_csv(output_dir / f'{prefix}_number_at_risk.csv') # Calculate hazard ratio hr, ci_lower, ci_upper, hr_p = calculate_hazard_ratio(data) # Generate statistical summary with open(output_dir / f'{prefix}_statistics.txt', 'w') as f: f.write("SURVIVAL ANALYSIS STATISTICAL SUMMARY\n") f.write("=" * 60 + "\n\n") groups = data['group'].unique() for group in groups: kmf = kmf_models[group] median = kmf.median_survival_time_ # Calculate survival rates at common time points try: surv_12m = kmf.survival_function_at_times(12).values[0] surv_24m = kmf.survival_function_at_times(24).values[0] if data['time'].max() >= 24 else None except: surv_12m = None surv_24m = None f.write(f"Group: {group}\n") f.write(f" N = {len(data[data['group'] == group])}\n") f.write(f" Events = {data[data['group'] == group]['event'].sum()}\n") f.write(f" Median survival: {median:.1f} months\n" if median != np.inf else " Median survival: Not reached\n") if surv_12m is not None: f.write(f" 12-month survival rate: {surv_12m*100:.1f}%\n") if surv_24m is not None: f.write(f" 24-month survival rate: {surv_24m*100:.1f}%\n") f.write("\n") f.write(f"Log-Rank Test:\n") f.write(f" p-value = {logrank_p:.4f}\n") f.write(f" Interpretation: {'Significant' if logrank_p < 0.05 else 'Not significant'} difference in survival\n\n") if len(groups) == 2: f.write(f"Hazard Ratio ({groups[1]} vs {groups[0]}):\n") f.write(f" HR = {hr:.2f} (95% CI {ci_lower:.2f}-{ci_upper:.2f})\n") f.write(f" p-value = {hr_p:.4f}\n") f.write(f" Interpretation: {groups[1]} has {((1-hr)*100):.0f}% {'reduction' if hr < 1 else 'increase'} in risk\n") # Generate LaTeX table code with open(output_dir / f'{prefix}_latex_table.tex', 'w') as f: f.write("% LaTeX table code for survival outcomes\n") f.write("\\begin{table}[H]\n") f.write("\\centering\n") f.write("\\small\n") f.write("\\begin{tabular}{lcccc}\n") f.write("\\toprule\n") f.write("\\textbf{Endpoint} & \\textbf{Group A} & \\textbf{Group B} & \\textbf{HR (95\\% CI)} & \\textbf{p-value} \\\\\n") f.write("\\midrule\n") # Add median survival row for i, group in enumerate(groups): kmf = kmf_models[group] median = kmf.median_survival_time_ if i == 0: f.write(f"Median survival, months (95\\% CI) & ") if median != np.inf: f.write(f"{median:.1f} & ") else: f.write("NR & ") else: if median != np.inf: f.write(f"{median:.1f} & ") else: f.write("NR & ") f.write(f"{hr:.2f} ({ci_lower:.2f}-{ci_upper:.2f}) & {hr_p:.3f} \\\\\n") # Add 12-month survival rate f.write("12-month survival rate (\\%) & ") for group in groups: kmf = kmf_models[group] try: surv_12m = kmf.survival_function_at_times(12).values[0] f.write(f"{surv_12m*100:.0f}\\% & ") except: f.write("-- & ") f.write("-- & -- \\\\\n") f.write("\\bottomrule\n") f.write("\\end{tabular}\n") f.write(f"\\caption{{Survival outcomes by group (log-rank p={logrank_p:.3f})}}\n") f.write("\\end{table}\n") print(f"\nAnalysis complete! Files saved to {output_dir}/") print(f" - Survival curves: {prefix}_kaplan_meier.pdf/png") print(f" - Statistics: {prefix}_statistics.txt") print(f" - LaTeX table: {prefix}_latex_table.tex") print(f" - Risk table: {prefix}_number_at_risk.csv") def main(): parser = argparse.ArgumentParser(description='Generate Kaplan-Meier survival curves') parser.add_argument('input_file', type=str, help='CSV file with survival data') parser.add_argument('-o', '--output', type=str, default='survival_output', help='Output directory (default: survival_output)') parser.add_argument('-t', '--title', type=str, default='Kaplan-Meier Survival Curve', help='Plot title') parser.add_argument('-x', '--xlabel', type=str, default='Time (months)', help='X-axis label') parser.add_argument('-y', '--ylabel', type=str, default='Survival Probability', help='Y-axis label') parser.add_argument('--time-col', type=str, default='time', help='Column name for time variable') parser.add_argument('--event-col', type=str, default='event', help='Column name for event indicator') parser.add_argument('--group-col', type=str, default='group', help='Column name for grouping variable') args = parser.parse_args() # Load data print(f"Loading data from {args.input_file}...") data = load_survival_data(args.input_file) print(f"Loaded {len(data)} patients") print(f"Groups: {data[args.group_col].value_counts().to_dict()}") # Generate analysis generate_report( data, output_dir=args.output, prefix='survival' ) if __name__ == '__main__': main() # Example usage: # python generate_survival_analysis.py survival_data.csv -o figures/ -t "PFS by PD-L1 Status" # # Input CSV format: # patient_id,time,event,group # PT001,12.3,1,PD-L1+ # PT002,8.5,1,PD-L1- # PT003,18.2,0,PD-L1+ # ...
{ "repo_id": "davila7/claude-code-templates", "file_path": "cli-tool/components/skills/scientific/clinical-decision-support/scripts/generate_survival_analysis.py", "license": "MIT License", "lines": 335, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex