Spaces:
Sleeping
Sleeping
File size: 9,631 Bytes
1abade4 b78ec70 fa045d5 b78ec70 fa045d5 b78ec70 1abade4 b78ec70 fa045d5 b78ec70 fa045d5 b78ec70 fa045d5 b78ec70 fa045d5 b78ec70 fa045d5 b78ec70 1abade4 b78ec70 fa045d5 b78ec70 fa045d5 b78ec70 fa045d5 b78ec70 fa045d5 b78ec70 fa045d5 b78ec70 fa045d5 b78ec70 fa045d5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 |
# src/utils.py
import re
import datetime
import pandas as pd
from typing import Dict, List, Tuple, Set, Optional
from config import ALL_UG40_LANGUAGES, LANGUAGE_NAMES, GOOGLE_SUPPORTED_LANGUAGES, DISPLAY_CONFIG
def get_all_language_pairs() -> List[Tuple[str, str]]:
"""Get all possible UG40 language pairs."""
pairs = []
for src in ALL_UG40_LANGUAGES:
for tgt in ALL_UG40_LANGUAGES:
if src != tgt:
pairs.append((src, tgt))
return pairs
def get_google_comparable_pairs() -> List[Tuple[str, str]]:
"""Get language pairs that can be compared with Google Translate."""
pairs = []
for src in GOOGLE_SUPPORTED_LANGUAGES:
for tgt in GOOGLE_SUPPORTED_LANGUAGES:
if src != tgt:
pairs.append((src, tgt))
return pairs
def format_language_pair(src: str, tgt: str) -> str:
"""Format language pair for display."""
src_name = LANGUAGE_NAMES.get(src, src.upper())
tgt_name = LANGUAGE_NAMES.get(tgt, tgt.upper())
return f"{src_name} → {tgt_name}"
def validate_language_code(lang: str) -> bool:
"""Validate if language code is supported."""
return lang in ALL_UG40_LANGUAGES
def create_submission_id() -> str:
"""Create unique submission ID."""
return datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-3]
def sanitize_model_name(name: str) -> str:
"""Sanitize model name for display and storage."""
if not name or not isinstance(name, str):
return "Anonymous_Model"
# Remove special characters, limit length
name = re.sub(r'[^\w\-.]', '_', name.strip())
# Remove multiple consecutive underscores
name = re.sub(r'_+', '_', name)
# Remove leading/trailing underscores
name = name.strip('_')
# Ensure minimum length
if len(name) < 3:
name = f"Model_{name}"
return name[:50] # Limit to 50 characters
def format_metric_value(value: float, metric: str) -> str:
"""Format metric value for display with appropriate precision."""
if pd.isna(value) or value is None:
return "N/A"
try:
precision = DISPLAY_CONFIG['decimal_places'].get(metric, 4)
if metric == 'coverage_rate':
return f"{value:.{precision}%}"
elif metric in ['bleu']:
return f"{value:.{precision}f}"
elif metric in ['cer', 'wer'] and value > 1:
# Cap error rates at 1.0 for display
return f"{min(value, 1.0):.{precision}f}"
else:
return f"{value:.{precision}f}"
except (ValueError, TypeError):
return str(value)
def get_language_pair_stats(test_data: pd.DataFrame) -> Dict[str, Dict]:
"""Get statistics about language pair coverage in test data."""
if test_data.empty:
return {}
stats = {}
try:
for src in ALL_UG40_LANGUAGES:
for tgt in ALL_UG40_LANGUAGES:
if src != tgt:
pair_data = test_data[
(test_data['source_language'] == src) &
(test_data['target_language'] == tgt)
]
stats[f"{src}_{tgt}"] = {
'count': len(pair_data),
'google_comparable': src in GOOGLE_SUPPORTED_LANGUAGES and tgt in GOOGLE_SUPPORTED_LANGUAGES,
'display_name': format_language_pair(src, tgt),
'source_language': src,
'target_language': tgt
}
except Exception as e:
print(f"Error calculating language pair stats: {e}")
return {}
return stats
def validate_submission_completeness(predictions: pd.DataFrame, test_set: pd.DataFrame) -> Dict:
"""Validate that submission covers all required samples."""
if predictions.empty or test_set.empty:
return {
'is_complete': False,
'missing_count': len(test_set) if not test_set.empty else 0,
'extra_count': len(predictions) if not predictions.empty else 0,
'missing_ids': [],
'coverage': 0.0
}
try:
required_ids = set(test_set['sample_id'].astype(str))
provided_ids = set(predictions['sample_id'].astype(str))
missing_ids = required_ids - provided_ids
extra_ids = provided_ids - required_ids
return {
'is_complete': len(missing_ids) == 0,
'missing_count': len(missing_ids),
'extra_count': len(extra_ids),
'missing_ids': list(missing_ids)[:10], # First 10 for display
'coverage': len(provided_ids & required_ids) / len(required_ids) if required_ids else 0.0
}
except Exception as e:
print(f"Error validating submission completeness: {e}")
return {
'is_complete': False,
'missing_count': 0,
'extra_count': 0,
'missing_ids': [],
'coverage': 0.0
}
def calculate_language_pair_coverage(predictions: pd.DataFrame, test_set: pd.DataFrame) -> Dict:
"""Calculate coverage by language pair."""
if predictions.empty or test_set.empty:
return {}
try:
# Merge to get language info
merged = test_set.merge(predictions, on='sample_id', how='left', suffixes=('', '_pred'))
coverage = {}
for src in ALL_UG40_LANGUAGES:
for tgt in ALL_UG40_LANGUAGES:
if src != tgt:
pair_data = merged[
(merged['source_language'] == src) &
(merged['target_language'] == tgt)
]
if len(pair_data) > 0:
predicted_count = pair_data['prediction'].notna().sum()
coverage[f"{src}_{tgt}"] = {
'total': len(pair_data),
'predicted': predicted_count,
'coverage': predicted_count / len(pair_data),
'display_name': format_language_pair(src, tgt)
}
return coverage
except Exception as e:
print(f"Error calculating language pair coverage: {e}")
return {}
def safe_divide(numerator: float, denominator: float, default: float = 0.0) -> float:
"""Safely divide two numbers, handling edge cases."""
try:
if denominator == 0 or pd.isna(denominator) or pd.isna(numerator):
return default
result = numerator / denominator
if pd.isna(result) or not pd.isfinite(result):
return default
return float(result)
except (TypeError, ValueError, ZeroDivisionError):
return default
def clean_text_for_evaluation(text: str) -> str:
"""Clean text for evaluation, handling common encoding issues."""
if not isinstance(text, str):
return str(text) if text is not None else ""
# Remove extra whitespace
text = re.sub(r'\s+', ' ', text.strip())
# Handle common encoding issues
text = text.replace('\u00a0', ' ') # Non-breaking space
text = text.replace('\u2019', "'") # Right single quotation mark
text = text.replace('\u201c', '"') # Left double quotation mark
text = text.replace('\u201d', '"') # Right double quotation mark
return text
def get_model_summary_stats(model_results: Dict) -> Dict:
"""Extract summary statistics from model evaluation results."""
if not model_results or 'averages' not in model_results:
return {}
averages = model_results.get('averages', {})
summary = model_results.get('summary', {})
return {
'quality_score': averages.get('quality_score', 0.0),
'bleu': averages.get('bleu', 0.0),
'chrf': averages.get('chrf', 0.0),
'rouge1': averages.get('rouge1', 0.0),
'rougeL': averages.get('rougeL', 0.0),
'total_samples': summary.get('total_samples', 0),
'language_pairs': summary.get('language_pairs_covered', 0),
'google_pairs': summary.get('google_comparable_pairs', 0)
}
def generate_model_identifier(model_name: str, author: str) -> str:
"""Generate a unique identifier for a model."""
clean_name = sanitize_model_name(model_name)
clean_author = re.sub(r'[^\w\-]', '_', author.strip())[:20] if author else "Anonymous"
timestamp = datetime.datetime.now().strftime("%m%d_%H%M")
return f"{clean_name}_{clean_author}_{timestamp}"
def validate_dataframe_structure(df: pd.DataFrame, required_columns: List[str]) -> Tuple[bool, List[str]]:
"""Validate that a DataFrame has the required structure."""
if df.empty:
return False, ["DataFrame is empty"]
missing_columns = [col for col in required_columns if col not in df.columns]
if missing_columns:
return False, [f"Missing columns: {', '.join(missing_columns)}"]
return True, []
def format_duration(seconds: float) -> str:
"""Format duration in seconds to human-readable format."""
if seconds < 60:
return f"{seconds:.1f}s"
elif seconds < 3600:
return f"{seconds/60:.1f}m"
else:
return f"{seconds/3600:.1f}h"
def truncate_text(text: str, max_length: int = 100, suffix: str = "...") -> str:
"""Truncate text to specified length with suffix."""
if not isinstance(text, str):
text = str(text)
if len(text) <= max_length:
return text
return text[:max_length - len(suffix)] + suffix |