Spaces:
Sleeping
Sleeping
| """Language Detection Utility""" | |
| import re | |
| from typing import Optional | |
| def detect_language(code: str) -> str: | |
| """ | |
| Auto-detect programming language from code content. | |
| Args: | |
| code: Source code string | |
| Returns: | |
| str: Detected language (python, javascript, typescript, or unknown) | |
| """ | |
| # Python indicators | |
| python_patterns = [ | |
| r'\bdef\s+\w+\s*\(', | |
| r'\bclass\s+\w+\s*:', | |
| r'\bimport\s+\w+', | |
| r'\bfrom\s+\w+\s+import', | |
| r'__init__', | |
| r'self\.', | |
| ] | |
| # JavaScript indicators | |
| js_patterns = [ | |
| r'\bfunction\s+\w+\s*\(', | |
| r'\bconst\s+\w+\s*=', | |
| r'\blet\s+\w+\s*=', | |
| r'\bvar\s+\w+\s*=', | |
| r'=>', | |
| r'console\.log', | |
| ] | |
| # TypeScript indicators | |
| ts_patterns = [ | |
| r':\s*(string|number|boolean|any|void)', | |
| r'\binterface\s+\w+', | |
| r'\btype\s+\w+\s*=', | |
| r'<\w+>', | |
| ] | |
| # Count matches | |
| python_score = sum(1 for pattern in python_patterns if re.search(pattern, code)) | |
| js_score = sum(1 for pattern in js_patterns if re.search(pattern, code)) | |
| ts_score = sum(1 for pattern in ts_patterns if re.search(pattern, code)) | |
| # TypeScript is superset of JavaScript, so add JS score | |
| if ts_score > 0: | |
| ts_score += js_score | |
| # Determine winner | |
| scores = { | |
| "python": python_score, | |
| "javascript": js_score, | |
| "typescript": ts_score | |
| } | |
| max_score = max(scores.values()) | |
| if max_score == 0: | |
| return "unknown" | |
| return max(scores, key=scores.get) | |