File size: 7,048 Bytes
6759906 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
#!/usr/bin/env python3
"""
License Detection Benchmark for CodeReality-1T Dataset
Evaluates automated license classification systems
"""
import json
import os
from typing import Dict, List, Tuple
from collections import defaultdict
import random
def load_dataset_sample(data_dir: str, sample_size: int = 1000) -> List[Dict]:
"""Load random sample of repositories from dataset."""
print(f"🔍 Loading sample of {sample_size} repositories...")
repositories = []
# Get available files
files = [f for f in os.listdir(data_dir) if f.endswith('.jsonl')]
random.shuffle(files)
for filename in files[:10]: # Sample from first 10 files
file_path = os.path.join(data_dir, filename)
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
for line in f:
if len(repositories) >= sample_size:
break
try:
repo_data = json.loads(line)
repositories.append(repo_data)
except json.JSONDecodeError:
continue
except Exception as e:
print(f"⚠️ Error reading {filename}: {e}")
continue
if len(repositories) >= sample_size:
break
print(f"✅ Loaded {len(repositories)} repositories")
return repositories
def extract_license_features(repo: Dict) -> Dict:
"""Extract features that could indicate license presence."""
features = {
'has_license_file': False,
'has_readme': False,
'license_keywords_count': 0,
'copyright_mentions': 0,
'file_count': 0,
'detected_license': repo.get('license', 'Unknown')
}
files = repo.get('files', [])
features['file_count'] = len(files)
license_keywords = ['license', 'mit', 'apache', 'gpl', 'bsd', 'copyright']
for file_obj in files:
if isinstance(file_obj, dict):
file_path = file_obj.get('path', '').lower()
content = file_obj.get('content', '').lower()
# Check for license files
if any(keyword in file_path for keyword in ['license', 'copying', 'legal']):
features['has_license_file'] = True
# Check for README
if 'readme' in file_path:
features['has_readme'] = True
# Count license keywords
for keyword in license_keywords:
features['license_keywords_count'] += content.count(keyword)
# Count copyright mentions
features['copyright_mentions'] += content.count('copyright')
return features
def simple_license_classifier(features: Dict) -> str:
"""Simple rule-based license classifier for demonstration."""
# Rule-based classification
if features['has_license_file']:
if features['license_keywords_count'] > 10:
return 'MIT' # Most common
elif features['copyright_mentions'] > 5:
return 'Apache-2.0'
else:
return 'GPL-3.0'
elif features['has_readme'] and features['license_keywords_count'] > 3:
return 'MIT'
elif features['file_count'] > 50 and features['copyright_mentions'] > 2:
return 'Apache-2.0'
else:
return 'Unknown'
def evaluate_license_detection(repositories: List[Dict]) -> Dict:
"""Evaluate license detection performance."""
print("🧮 Evaluating license detection...")
results = {
'total_repos': len(repositories),
'predictions': [],
'ground_truth': [],
'accuracy': 0.0,
'license_distribution': defaultdict(int),
'prediction_distribution': defaultdict(int)
}
for repo in repositories:
features = extract_license_features(repo)
predicted_license = simple_license_classifier(features)
actual_license = features['detected_license']
results['predictions'].append(predicted_license)
results['ground_truth'].append(actual_license)
results['license_distribution'][actual_license] += 1
results['prediction_distribution'][predicted_license] += 1
# Calculate accuracy (note: actual dataset has mostly 'Unknown' licenses)
correct = sum(1 for p, a in zip(results['predictions'], results['ground_truth']) if p == a)
results['accuracy'] = correct / len(repositories) if repositories else 0
return results
def print_benchmark_results(results: Dict):
"""Print formatted benchmark results."""
print("=" * 60)
print("📊 LICENSE DETECTION BENCHMARK RESULTS")
print("=" * 60)
print(f"Total repositories evaluated: {results['total_repos']}")
print(f"Overall accuracy: {results['accuracy']:.3f}")
print("\n📈 Ground Truth Distribution:")
for license_type, count in sorted(results['license_distribution'].items(), key=lambda x: x[1], reverse=True)[:10]:
percentage = (count / results['total_repos']) * 100
print(f" {license_type}: {count} ({percentage:.1f}%)")
print("\n🎯 Prediction Distribution:")
for license_type, count in sorted(results['prediction_distribution'].items(), key=lambda x: x[1], reverse=True):
percentage = (count / results['total_repos']) * 100
print(f" {license_type}: {count} ({percentage:.1f}%)")
print("\n💡 Insights:")
print("- CodeReality-1T is deliberately noisy with 0% license detection")
print("- This benchmark demonstrates the challenge of license classification")
print("- Most repositories lack clear licensing information")
print("- Perfect for testing robustness of license detection systems")
def main():
"""Run license detection benchmark."""
print("🚀 CodeReality-1T License Detection Benchmark")
print("=" * 60)
# Configuration
data_dir = "/mnt/z/CodeReality_Final/unified_dataset"
sample_size = 500
if not os.path.exists(data_dir):
print(f"❌ Dataset directory not found: {data_dir}")
print("Please update the data_dir path to point to your CodeReality-1T dataset")
return
# Load dataset sample
repositories = load_dataset_sample(data_dir, sample_size)
if not repositories:
print("❌ No repositories loaded. Check dataset path.")
return
# Run evaluation
results = evaluate_license_detection(repositories)
# Print results
print_benchmark_results(results)
# Save results
output_file = "license_detection_results.json"
with open(output_file, 'w') as f:
# Convert defaultdict to regular dict for JSON serialization
results_json = {
'total_repos': results['total_repos'],
'accuracy': results['accuracy'],
'license_distribution': dict(results['license_distribution']),
'prediction_distribution': dict(results['prediction_distribution'])
}
json.dump(results_json, f, indent=2)
print(f"\n💾 Results saved to: {output_file}")
if __name__ == "__main__":
main() |