Human-AII / ai /code_fingerprint.py
swayamshetkar
Updated backend with new logic
b946ba0
# ai/code_fingerprint.py
"""
Analyzes user code to extract behavioral coding patterns (code fingerprint).
These reflect how a person logically structures programs.
"""
import ast
from typing import Dict, Any
def analyze_fingerprint(code: str) -> Dict[str, Any]:
try:
tree = ast.parse(code)
except Exception:
return {
"abstraction": 0.0,
"data_structure_pref": "unknown",
"control_density": 0.0,
"refactor_tendency": 0.5
}
loops, conditionals, func_defs, classes = 0, 0, 0, 0
data_structures = {"list": 0, "dict": 0, "set": 0, "tuple": 0}
for node in ast.walk(tree):
if isinstance(node, (ast.For, ast.While)):
loops += 1
elif isinstance(node, ast.If):
conditionals += 1
elif isinstance(node, ast.FunctionDef):
func_defs += 1
elif isinstance(node, ast.ClassDef):
classes += 1
elif isinstance(node, ast.List):
data_structures["list"] += 1
elif isinstance(node, ast.Dict):
data_structures["dict"] += 1
elif isinstance(node, ast.Set):
data_structures["set"] += 1
elif isinstance(node, ast.Tuple):
data_structures["tuple"] += 1
total_nodes = max(1, len(list(ast.walk(tree))))
control_density = (loops + conditionals) / total_nodes
abstraction = (classes + func_defs) / total_nodes
data_pref = max(data_structures, key=data_structures.get, default="unknown")
return {
"abstraction": round(abstraction, 2),
"data_structure_pref": data_pref,
"control_density": round(control_density, 2),
"refactor_tendency": 0.5 + (abstraction * 0.5)
}