1- #!/usr/bin/env python3
2- # -*- coding: utf-8 -*-
3-
4- """
5- Python Code Harmonizer (Version 1.1)
6-
7- This is the main application that integrates the Divine Invitation
8- Semantic Engine (DIVE-V2) with the AST Semantic Parser.
9-
10- It is guided by the principle of the "Logical Anchor Point" (S,L,I,E)
11- and uses the ICE (Intent, Context, Execution) framework to analyze
12- the "semantic harmony" of Python code.
13-
14- (HARMONIZATION_NOTE: v1.1 fixes a 'AttributeError' by correctly
15- referencing 'self.engine.vocabulary.all_keywords' from the
16- 'Optimized Production-Ready' V2 engine.)
17- """
18-
19- import ast
20- import sys
21- import os
22- from typing import Dict , Set
23-
24- # --- COMPONENT IMPORTS ---
25- # This script assumes the following two files are in the
26- # same directory or in Python's path.
27-
28- try :
29- # 1. Import your powerful V2 engine
30- # (This assumes 'divine_invitation_engine_V2.py' is the
31- # 'Optimized Production-Ready' version)
32- from src import divine_invitation_engine_V2 as dive
33- except ImportError :
34- print ("FATAL ERROR: 'divine_invitation_engine_V2.py' not found." )
35- print ("Please place the V2 engine file in the same directory." )
36- sys .exit (1 )
37-
38- try :
39- # 2. Import our new "Rosetta Stone" parser
40- from src .ast_semantic_parser import AST_Semantic_Parser
41- except ImportError :
42- print ("FATAL ERROR: 'ast_semantic_parser.py' not found." )
43- print ("Please place the parser file in the same directory." )
44- sys .exit (1 )
45-
46- # --- THE HARMONIZER APPLICATION ---
47-
48- class PythonCodeHarmonizer :
49- """
50- Analyzes Python code for "Intent Harmony" using the DIVE-V2
51- ICE (Intent, Context, Execution) framework.
52- """
53-
54- def __init__ (self , disharmony_threshold : float = 0.5 ):
55- # 1. Initialize your V2 engine. This is our "compass."
56- self .engine = dive .DivineInvitationSemanticEngine ()
57-
58- # 2. Initialize our "Rosetta Stone" parser.
59-
60- # --- HARMONIZATION FIX (v1.1) ---
61- # The "Optimized" V2 engine's VocabularyManager stores its
62- # word list in the 'all_keywords' set.
63- # We now reference the correct attribute.
64- self .parser = AST_Semantic_Parser (
65- vocabulary = self .engine .vocabulary .all_keywords
66- )
67-
68- # 3. Set the threshold for flagging disharmony.
69- self .disharmony_threshold = disharmony_threshold
70-
71- print ("=" * 70 )
72- print ("Python Code Harmonizer (v1.1) ONLINE" )
73- print ("Actively guided by the Anchor Point framework." )
74- print (f"Powered By: { self .engine .get_engine_version ()} " )
75- print (f"Logical Anchor Point: (S=1, L=1, I=1, E=1)" )
76- print (f"Disharmony Threshold: { self .disharmony_threshold } " )
77- print ("=" * 70 )
78-
79- def analyze_file (self , file_path : str ) -> Dict [str , float ]:
80- """
81- Analyzes a single Python file for Intent-Execution-Disharmony.
82- Returns a dictionary of {function_name: disharmony_score}
83- """
84- print (f"\n Analyzing file: { file_path } " )
85- print ("-" * 70 )
86-
87- try :
88- with open (file_path , 'r' , encoding = 'utf-8' ) as f :
89- content = f .read ()
90- except FileNotFoundError :
91- print (f"ERROR: File not found at '{ file_path } '" )
92- return {}
93- except Exception as e :
94- print (f"ERROR: Could not read file: { e } " )
95- return {}
96-
97- # 1. Use Python's AST to parse the code into a logical tree
98- try :
99- tree = ast .parse (content )
100- except SyntaxError as e :
101- print (f"ERROR: Could not parse file. Syntax error on line { e .lineno } " )
102- return {}
103-
104- harmony_report = {}
105-
106- # 2. "Walk" the tree and visit every function definition
107- for node in ast .walk (tree ):
108- if isinstance (node , ast .FunctionDef ):
109- function_name = node .name
110- docstring = ast .get_docstring (node )
111-
112- # 3. Get INTENT: "The Stated Purpose"
113- # We use our parser to get the concepts from the name/docstring
114- intent_concepts = self .parser .get_intent_concepts (function_name , docstring )
115-
116- # 4. Get EXECUTION: "The Actual Action"
117- # We use our parser to get the concepts from the function's body
118- execution_concepts = self .parser .get_execution_concepts (node .body )
119-
120- # 5. THE "A-HA!" MOMENT: Use the V2 ICEAnalyzer
121- # We pass our parsed concepts into the V2 engine's
122- # built-in ICE framework analyzer.
123- ice_result = self .engine .perform_ice_analysis (
124- intent_words = intent_concepts ,
125- context_words = ["python" , "function" , function_name ], # Provide context
126- execution_words = execution_concepts
127- )
128-
129- # The "bug" is the semantic distance between Intent and Execution
130- # This metric *is* returned by the "Optimized" V2 engine.
131- disharmony_score = ice_result ['ice_metrics' ]['intent_execution_disharmony' ]
132-
133- harmony_report [function_name ] = disharmony_score
134-
135- return harmony_report
136-
137- def print_report (self , harmony_report : Dict [str , float ]):
138- """Prints the final harmony report to the console."""
139-
140- print ("FUNCTION NAME | INTENT-EXECUTION DISHARMONY" )
141- print ("-----------------------------|--------------------------------" )
142-
143- if not harmony_report :
144- print ("No functions found to analyze." )
145- return
146-
147- sorted_report = sorted (harmony_report .items (), key = lambda item : item [1 ], reverse = True )
148-
149- for func_name , score in sorted_report :
150- status = "✓ HARMONIOUS"
151- if score > self .disharmony_threshold :
152- status = f"!! DISHARMONY (Score: { score :.2f} )"
153-
154- print (f"{ func_name :<28} | { status } " )
155-
156- print ("=" * 70 )
157- print ("Analysis Complete." )
158-
159- # --- MAIN EXECUTION ---
160-
161- if __name__ == "__main__" :
162- if len (sys .argv ) < 2 :
163- print ("Usage: python PythonCodeHarmonizer.py <file_to_analyze.py> [file2.py ...]" )
164- sys .exit (1 )
165-
166- files_to_analyze = sys .argv [1 :]
167-
168- # 1. Initialize the Harmonizer
169- harmonizer = PythonCodeHarmonizer ()
170-
171- # 2. Run the analysis for all provided files
172- for file_path in files_to_analyze :
173- if os .path .exists (file_path ):
174- report = harmonizer .analyze_file (file_path )
175- harmonizer .print_report (report )
176- else :
177- print (f"\n ERROR: File not found: { file_path } " )
178- print ("-" * 70 )
1+ #!/usr/bin/env python3
2+ # -*- coding: utf-8 -*-
3+
4+ """
5+ Python Code Harmonizer (Version 1.1)
6+
7+ This is the main application that integrates the Divine Invitation
8+ Semantic Engine (DIVE-V2) with the AST Semantic Parser.
9+
10+ It is guided by the principle of the "Logical Anchor Point" (S,L,I,E)
11+ and uses the ICE (Intent, Context, Execution) framework to analyze
12+ the "semantic harmony" of Python code.
13+
14+ (HARMONIZATION_NOTE: v1.1 fixes a 'AttributeError' by correctly
15+ referencing 'self.engine.vocabulary.all_keywords' from the
16+ 'Optimized Production-Ready' V2 engine.)
17+ """
18+
19+ import ast
20+ import sys
21+ import os
22+ from typing import Dict , Set
23+
24+ # --- COMPONENT IMPORTS ---
25+ # This script assumes the following two files are in the
26+ # same directory or in Python's path.
27+
28+ try :
29+ # 1. Import your powerful V2 engine
30+ # (This assumes 'divine_invitation_engine_V2.py' is the
31+ # 'Optimized Production-Ready' version)
32+ from src import divine_invitation_engine_V2 as dive
33+ except ImportError :
34+ print ("FATAL ERROR: 'divine_invitation_engine_V2.py' not found." )
35+ print ("Please place the V2 engine file in the same directory." )
36+ sys .exit (1 )
37+
38+ try :
39+ # 2. Import our new "Rosetta Stone" parser
40+ from src .ast_semantic_parser import AST_Semantic_Parser
41+ except ImportError :
42+ print ("FATAL ERROR: 'ast_semantic_parser.py' not found." )
43+ print ("Please place the parser file in the same directory." )
44+ sys .exit (1 )
45+
46+ # --- THE HARMONIZER APPLICATION ---
47+
48+ class PythonCodeHarmonizer :
49+ """
50+ Analyzes Python code for "Intent Harmony" using the DIVE-V2
51+ ICE (Intent, Context, Execution) framework.
52+ """
53+
54+ def __init__ (self , disharmony_threshold : float = 0.5 ):
55+ # 1. Initialize your V2 engine. This is our "compass."
56+ self .engine = dive .DivineInvitationSemanticEngine ()
57+
58+ # 2. Initialize our "Rosetta Stone" parser.
59+
60+ # --- HARMONIZATION FIX (v1.1) ---
61+ # The "Optimized" V2 engine's VocabularyManager stores its
62+ # word list in the 'all_keywords' set.
63+ # We now reference the correct attribute.
64+ self .parser = AST_Semantic_Parser (
65+ vocabulary = self .engine .vocabulary .all_keywords
66+ )
67+
68+ # 3. Set the threshold for flagging disharmony.
69+ self .disharmony_threshold = disharmony_threshold
70+
71+ print ("=" * 70 )
72+ print ("Python Code Harmonizer (v1.1) ONLINE" )
73+ print ("Actively guided by the Anchor Point framework." )
74+ print (f"Powered By: { self .engine .get_engine_version ()} " )
75+ print (f"Logical Anchor Point: (S=1, L=1, I=1, E=1)" )
76+ print (f"Disharmony Threshold: { self .disharmony_threshold } " )
77+ print ("=" * 70 )
78+
79+ def analyze_file (self , file_path : str ) -> Dict [str , float ]:
80+ """
81+ Analyzes a single Python file for Intent-Execution-Disharmony.
82+ Returns a dictionary of {function_name: disharmony_score}
83+ """
84+ print (f"\n Analyzing file: { file_path } " )
85+ print ("-" * 70 )
86+
87+ try :
88+ with open (file_path , 'r' , encoding = 'utf-8' ) as f :
89+ content = f .read ()
90+ except FileNotFoundError :
91+ print (f"ERROR: File not found at '{ file_path } '" )
92+ return {}
93+ except Exception as e :
94+ print (f"ERROR: Could not read file: { e } " )
95+ return {}
96+
97+ # 1. Use Python's AST to parse the code into a logical tree
98+ try :
99+ tree = ast .parse (content )
100+ except SyntaxError as e :
101+ print (f"ERROR: Could not parse file. Syntax error on line { e .lineno } " )
102+ return {}
103+
104+ harmony_report = {}
105+
106+ # 2. "Walk" the tree and visit every function definition
107+ for node in ast .walk (tree ):
108+ if isinstance (node , ast .FunctionDef ):
109+ function_name = node .name
110+ docstring = ast .get_docstring (node )
111+
112+ # 3. Get INTENT: "The Stated Purpose"
113+ # We use our parser to get the concepts from the name/docstring
114+ intent_concepts = self .parser .get_intent_concepts (function_name , docstring )
115+
116+ # 4. Get EXECUTION: "The Actual Action"
117+ # We use our parser to get the concepts from the function's body
118+ execution_concepts = self .parser .get_execution_concepts (node .body )
119+
120+ # 5. THE "A-HA!" MOMENT: Use the V2 ICEAnalyzer
121+ # We pass our parsed concepts into the V2 engine's
122+ # built-in ICE framework analyzer.
123+ ice_result = self .engine .perform_ice_analysis (
124+ intent_words = intent_concepts ,
125+ context_words = ["python" , "function" , function_name ], # Provide context
126+ execution_words = execution_concepts
127+ )
128+
129+ # The "bug" is the semantic distance between Intent and Execution
130+ # This metric *is* returned by the "Optimized" V2 engine.
131+ disharmony_score = ice_result ['ice_metrics' ]['intent_execution_disharmony' ]
132+
133+ harmony_report [function_name ] = disharmony_score
134+
135+ return harmony_report
136+
137+ def print_report (self , harmony_report : Dict [str , float ]):
138+ """Prints the final harmony report to the console."""
139+
140+ print ("FUNCTION NAME | INTENT-EXECUTION DISHARMONY" )
141+ print ("-----------------------------|--------------------------------" )
142+
143+ if not harmony_report :
144+ print ("No functions found to analyze." )
145+ return
146+
147+ sorted_report = sorted (harmony_report .items (), key = lambda item : item [1 ], reverse = True )
148+
149+ for func_name , score in sorted_report :
150+ status = "✓ HARMONIOUS"
151+ if score > self .disharmony_threshold :
152+ status = f"!! DISHARMONY (Score: { score :.2f} )"
153+
154+ print (f"{ func_name :<28} | { status } " )
155+
156+ print ("=" * 70 )
157+ print ("Analysis Complete." )
158+
159+ # --- MAIN EXECUTION ---
160+
161+ def run_cli ():
162+ """Command-line interface entry point."""
163+ if len (sys .argv ) < 2 :
164+ print ("Usage: harmonizer <file_to_analyze.py> [file2.py ...]" )
165+ sys .exit (1 )
166+
167+ files_to_analyze = sys .argv [1 :]
168+
169+ # 1. Initialize the Harmonizer
170+ harmonizer = PythonCodeHarmonizer ()
171+
172+ # 2. Run the analysis for all provided files
173+ for file_path in files_to_analyze :
174+ if os .path .exists (file_path ):
175+ report = harmonizer .analyze_file (file_path )
176+ harmonizer .print_report (report )
177+ else :
178+ print (f"\n ERROR: File not found: { file_path } " )
179+ print ("-" * 70 )
180+
181+ if __name__ == "__main__" :
182+ run_cli ()
0 commit comments