1+ #!/usr/bin/env python3
2+ """
3+ AI Import Hallucination Healer
4+ ================================
5+ Detects and removes the dumbest AI mistakes: placeholder imports.
6+
7+ This intercepts code before execution and removes lines like:
8+ from your_file_name import calculate
9+ from my_script import function
10+ from app import main
11+
12+ Because the AI is supposed to run everything in ONE FILE but keeps
13+ hallucinating module imports like a drunk programmer.
14+ """
15+
16+ import re
17+ import sys
18+ from pathlib import Path
19+ from typing import Tuple , List
20+
21+
22+ class AIImportHealer :
23+ """Heals AI-generated code that hallucinates placeholder imports."""
24+
25+ # Common placeholder names that AI models hallucinate
26+ PLACEHOLDER_PATTERNS = [
27+ r'your_file_name' ,
28+ r'your_module' ,
29+ r'my_script' ,
30+ r'my_module' ,
31+ r'your_file' ,
32+ r'main_file' ,
33+ r'app_file' ,
34+ r'module_name' ,
35+ r'file_name' ,
36+ r'script_name' ,
37+ r'code_file' ,
38+ r'test_file' ,
39+ r'example' ,
40+ r'calculator' , # specific to your case
41+ r'calc' ,
42+ ]
43+
44+ def __init__ (self , verbose : bool = True ):
45+ self .verbose = verbose
46+ self .healed_count = 0
47+ self .removed_lines : List [str ] = []
48+
49+ def _build_pattern (self ) -> re .Pattern :
50+ """Build regex pattern to match all placeholder imports."""
51+ # Match: from <placeholder> import ...
52+ placeholders = '|' .join (self .PLACEHOLDER_PATTERNS )
53+ pattern = rf'^\s*from\s+({ placeholders } )\s+import\s+.*$'
54+ return re .compile (pattern , re .MULTILINE | re .IGNORECASE )
55+
56+ def _log (self , msg : str ):
57+ """Log message if verbose mode is on."""
58+ if self .verbose :
59+ safe_print (f"🔧 { msg } " , file = sys .stderr )
60+
61+ def detect_hallucinated_imports (self , code : str ) -> List [str ]:
62+ """Find all hallucinated import lines."""
63+ pattern = self ._build_pattern ()
64+ matches = pattern .findall (code )
65+ return matches
66+
67+ def heal (self , code : str ) -> Tuple [str , bool ]:
68+ """
69+ Remove hallucinated imports from code.
70+
71+ Returns:
72+ (healed_code, was_healed) tuple
73+ """
74+ pattern = self ._build_pattern ()
75+
76+ # Find all matches first for logging
77+ matches = list (pattern .finditer (code ))
78+
79+ if not matches :
80+ return code , False
81+
82+ # Log what we're removing
83+ self ._log ("🚨 DETECTED AI HALLUCINATION!" )
84+ for match in matches :
85+ line = match .group (0 ).strip ()
86+ self .removed_lines .append (line )
87+ self ._log (f" Removing: { line } " )
88+
89+ # Remove the imports
90+ healed_code = pattern .sub ('' , code )
91+ self .healed_count += len (matches )
92+
93+ self ._log (f"✅ Healed { len (matches )} hallucinated import(s)" )
94+
95+ return healed_code , True
96+
97+ def heal_file (self , filepath : Path ) -> bool :
98+ """
99+ Heal a file in-place.
100+
101+ Returns:
102+ True if file was modified, False otherwise
103+ """
104+ self ._log (f"📄 Scanning: { filepath } " )
105+
106+ code = filepath .read_text ()
107+ healed_code , was_healed = self .heal (code )
108+
109+ if was_healed :
110+ filepath .write_text (healed_code )
111+ self ._log (f"💾 Saved healed code to: { filepath } " )
112+ return True
113+ else :
114+ self ._log ("✨ No hallucinations detected" )
115+ return False
116+
117+ def get_report (self ) -> str :
118+ """Get a summary report of healing operations."""
119+ if self .healed_count == 0 :
120+ return "✅ No AI hallucinations detected"
121+
122+ report = f"🔧 AI Import Healer Report\n "
123+ report += f"{ '=' * 50 } \n "
124+ report += f"Total hallucinations healed: { self .healed_count } \n "
125+ report += f"\n Removed lines:\n "
126+ for line in self .removed_lines :
127+ report += f" ❌ { line } \n "
128+ return report
129+
130+
131+ def heal_code_string (code : str , verbose : bool = True ) -> str :
132+ """
133+ Quick function to heal a code string.
134+
135+ Usage:
136+ healed = heal_code_string(ai_generated_code)
137+ """
138+ healer = AIImportHealer (verbose = verbose )
139+ healed_code , _ = healer .heal (code )
140+ return healed_code
141+
142+
143+ def heal_file (filepath : str , verbose : bool = True ) -> bool :
144+ """
145+ Quick function to heal a file.
146+
147+ Usage:
148+ was_healed = heal_file("/tmp/test.py")
149+ """
150+ healer = AIImportHealer (verbose = verbose )
151+ return healer .heal_file (Path (filepath ))
152+
153+
154+ # ============================================================================
155+ # DEMO: Self-healing test example
156+ # ============================================================================
157+
158+ if __name__ == "__main__" :
159+ # Example of broken AI-generated code
160+ broken_code = """
161+ import pytest
162+ from your_file_name import calculate # <-- AI HALLUCINATION!
163+
164+ def add(x, y):
165+ return float(x + y)
166+
167+ def subtract(x, y):
168+ return float(x - y)
169+
170+ def test_addition():
171+ assert add(5, 3) == 8
172+
173+ def test_subtraction():
174+ assert subtract(5, 3) == 2
175+
176+ if __name__ == "__main__":
177+ pytest.main(["-v", "--tb=short", __file__])
178+ """
179+
180+ safe_print ("=" * 60 )
181+ safe_print ("🤖 AI IMPORT HALLUCINATION HEALER - DEMO" )
182+ safe_print ("=" * 60 )
183+ safe_print ("\n 📋 Original (broken) code:" )
184+ safe_print ("-" * 60 )
185+ safe_print (broken_code )
186+ safe_print ("-" * 60 )
187+
188+ # Heal it!
189+ healer = AIImportHealer (verbose = True )
190+ healed_code , was_healed = healer .heal (broken_code )
191+
192+ safe_print ("\n " + "=" * 60 )
193+ safe_print ("💊 Healed code:" )
194+ safe_print ("-" * 60 )
195+ safe_print (healed_code )
196+ safe_print ("-" * 60 )
197+
198+ safe_print ("\n " + healer .get_report ())
199+
200+ # Show usage for omnipkg integration
201+ safe_print ("\n " + "=" * 60 )
202+ safe_print ("🔌 OMNIPKG INTEGRATION EXAMPLE:" )
203+ safe_print ("=" * 60 )
204+ safe_print ("""
205+ # In omnipkg/commands/run.py, add this before execution:
206+
207+ from omnipkg.utils.ai_sanitizers import heal_code_string
208+
209+ def execute_python_code(code: str, ...):
210+ # ... existing code ...
211+
212+ # Auto-heal AI hallucinations
213+ code = heal_code_string(code, verbose=True)
214+
215+ # ... continue with execution ...
216+ """ )
0 commit comments