pomera-ai-commander 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +680 -0
  3. package/bin/pomera-ai-commander.js +62 -0
  4. package/core/__init__.py +66 -0
  5. package/core/__pycache__/__init__.cpython-313.pyc +0 -0
  6. package/core/__pycache__/app_context.cpython-313.pyc +0 -0
  7. package/core/__pycache__/async_text_processor.cpython-313.pyc +0 -0
  8. package/core/__pycache__/backup_manager.cpython-313.pyc +0 -0
  9. package/core/__pycache__/backup_recovery_manager.cpython-313.pyc +0 -0
  10. package/core/__pycache__/content_hash_cache.cpython-313.pyc +0 -0
  11. package/core/__pycache__/context_menu.cpython-313.pyc +0 -0
  12. package/core/__pycache__/data_validator.cpython-313.pyc +0 -0
  13. package/core/__pycache__/database_connection_manager.cpython-313.pyc +0 -0
  14. package/core/__pycache__/database_curl_settings_manager.cpython-313.pyc +0 -0
  15. package/core/__pycache__/database_promera_ai_settings_manager.cpython-313.pyc +0 -0
  16. package/core/__pycache__/database_schema.cpython-313.pyc +0 -0
  17. package/core/__pycache__/database_schema_manager.cpython-313.pyc +0 -0
  18. package/core/__pycache__/database_settings_manager.cpython-313.pyc +0 -0
  19. package/core/__pycache__/database_settings_manager_interface.cpython-313.pyc +0 -0
  20. package/core/__pycache__/dialog_manager.cpython-313.pyc +0 -0
  21. package/core/__pycache__/efficient_line_numbers.cpython-313.pyc +0 -0
  22. package/core/__pycache__/error_handler.cpython-313.pyc +0 -0
  23. package/core/__pycache__/error_service.cpython-313.pyc +0 -0
  24. package/core/__pycache__/event_consolidator.cpython-313.pyc +0 -0
  25. package/core/__pycache__/memory_efficient_text_widget.cpython-313.pyc +0 -0
  26. package/core/__pycache__/migration_manager.cpython-313.pyc +0 -0
  27. package/core/__pycache__/migration_test_suite.cpython-313.pyc +0 -0
  28. package/core/__pycache__/migration_validator.cpython-313.pyc +0 -0
  29. package/core/__pycache__/optimized_find_replace.cpython-313.pyc +0 -0
  30. package/core/__pycache__/optimized_pattern_engine.cpython-313.pyc +0 -0
  31. package/core/__pycache__/optimized_search_highlighter.cpython-313.pyc +0 -0
  32. package/core/__pycache__/performance_monitor.cpython-313.pyc +0 -0
  33. package/core/__pycache__/persistence_manager.cpython-313.pyc +0 -0
  34. package/core/__pycache__/progressive_stats_calculator.cpython-313.pyc +0 -0
  35. package/core/__pycache__/regex_pattern_cache.cpython-313.pyc +0 -0
  36. package/core/__pycache__/regex_pattern_library.cpython-313.pyc +0 -0
  37. package/core/__pycache__/search_operation_manager.cpython-313.pyc +0 -0
  38. package/core/__pycache__/settings_defaults_registry.cpython-313.pyc +0 -0
  39. package/core/__pycache__/settings_integrity_validator.cpython-313.pyc +0 -0
  40. package/core/__pycache__/settings_serializer.cpython-313.pyc +0 -0
  41. package/core/__pycache__/settings_validator.cpython-313.pyc +0 -0
  42. package/core/__pycache__/smart_stats_calculator.cpython-313.pyc +0 -0
  43. package/core/__pycache__/statistics_update_manager.cpython-313.pyc +0 -0
  44. package/core/__pycache__/stats_config_manager.cpython-313.pyc +0 -0
  45. package/core/__pycache__/streaming_text_handler.cpython-313.pyc +0 -0
  46. package/core/__pycache__/task_scheduler.cpython-313.pyc +0 -0
  47. package/core/__pycache__/visibility_monitor.cpython-313.pyc +0 -0
  48. package/core/__pycache__/widget_cache.cpython-313.pyc +0 -0
  49. package/core/app_context.py +482 -0
  50. package/core/async_text_processor.py +422 -0
  51. package/core/backup_manager.py +656 -0
  52. package/core/backup_recovery_manager.py +1034 -0
  53. package/core/content_hash_cache.py +509 -0
  54. package/core/context_menu.py +313 -0
  55. package/core/data_validator.py +1067 -0
  56. package/core/database_connection_manager.py +745 -0
  57. package/core/database_curl_settings_manager.py +609 -0
  58. package/core/database_promera_ai_settings_manager.py +447 -0
  59. package/core/database_schema.py +412 -0
  60. package/core/database_schema_manager.py +396 -0
  61. package/core/database_settings_manager.py +1508 -0
  62. package/core/database_settings_manager_interface.py +457 -0
  63. package/core/dialog_manager.py +735 -0
  64. package/core/efficient_line_numbers.py +511 -0
  65. package/core/error_handler.py +747 -0
  66. package/core/error_service.py +431 -0
  67. package/core/event_consolidator.py +512 -0
  68. package/core/mcp/__init__.py +43 -0
  69. package/core/mcp/__pycache__/__init__.cpython-313.pyc +0 -0
  70. package/core/mcp/__pycache__/protocol.cpython-313.pyc +0 -0
  71. package/core/mcp/__pycache__/schema.cpython-313.pyc +0 -0
  72. package/core/mcp/__pycache__/server_stdio.cpython-313.pyc +0 -0
  73. package/core/mcp/__pycache__/tool_registry.cpython-313.pyc +0 -0
  74. package/core/mcp/protocol.py +288 -0
  75. package/core/mcp/schema.py +251 -0
  76. package/core/mcp/server_stdio.py +299 -0
  77. package/core/mcp/tool_registry.py +2345 -0
  78. package/core/memory_efficient_text_widget.py +712 -0
  79. package/core/migration_manager.py +915 -0
  80. package/core/migration_test_suite.py +1086 -0
  81. package/core/migration_validator.py +1144 -0
  82. package/core/optimized_find_replace.py +715 -0
  83. package/core/optimized_pattern_engine.py +424 -0
  84. package/core/optimized_search_highlighter.py +553 -0
  85. package/core/performance_monitor.py +675 -0
  86. package/core/persistence_manager.py +713 -0
  87. package/core/progressive_stats_calculator.py +632 -0
  88. package/core/regex_pattern_cache.py +530 -0
  89. package/core/regex_pattern_library.py +351 -0
  90. package/core/search_operation_manager.py +435 -0
  91. package/core/settings_defaults_registry.py +1087 -0
  92. package/core/settings_integrity_validator.py +1112 -0
  93. package/core/settings_serializer.py +558 -0
  94. package/core/settings_validator.py +1824 -0
  95. package/core/smart_stats_calculator.py +710 -0
  96. package/core/statistics_update_manager.py +619 -0
  97. package/core/stats_config_manager.py +858 -0
  98. package/core/streaming_text_handler.py +723 -0
  99. package/core/task_scheduler.py +596 -0
  100. package/core/update_pattern_library.py +169 -0
  101. package/core/visibility_monitor.py +596 -0
  102. package/core/widget_cache.py +498 -0
  103. package/mcp.json +61 -0
  104. package/package.json +57 -0
  105. package/pomera.py +7483 -0
  106. package/pomera_mcp_server.py +144 -0
  107. package/tools/__init__.py +5 -0
  108. package/tools/__pycache__/__init__.cpython-313.pyc +0 -0
  109. package/tools/__pycache__/ai_tools.cpython-313.pyc +0 -0
  110. package/tools/__pycache__/ascii_art_generator.cpython-313.pyc +0 -0
  111. package/tools/__pycache__/base64_tools.cpython-313.pyc +0 -0
  112. package/tools/__pycache__/base_tool.cpython-313.pyc +0 -0
  113. package/tools/__pycache__/case_tool.cpython-313.pyc +0 -0
  114. package/tools/__pycache__/column_tools.cpython-313.pyc +0 -0
  115. package/tools/__pycache__/cron_tool.cpython-313.pyc +0 -0
  116. package/tools/__pycache__/curl_history.cpython-313.pyc +0 -0
  117. package/tools/__pycache__/curl_processor.cpython-313.pyc +0 -0
  118. package/tools/__pycache__/curl_settings.cpython-313.pyc +0 -0
  119. package/tools/__pycache__/curl_tool.cpython-313.pyc +0 -0
  120. package/tools/__pycache__/diff_viewer.cpython-313.pyc +0 -0
  121. package/tools/__pycache__/email_extraction_tool.cpython-313.pyc +0 -0
  122. package/tools/__pycache__/email_header_analyzer.cpython-313.pyc +0 -0
  123. package/tools/__pycache__/extraction_tools.cpython-313.pyc +0 -0
  124. package/tools/__pycache__/find_replace.cpython-313.pyc +0 -0
  125. package/tools/__pycache__/folder_file_reporter.cpython-313.pyc +0 -0
  126. package/tools/__pycache__/folder_file_reporter_adapter.cpython-313.pyc +0 -0
  127. package/tools/__pycache__/generator_tools.cpython-313.pyc +0 -0
  128. package/tools/__pycache__/hash_generator.cpython-313.pyc +0 -0
  129. package/tools/__pycache__/html_tool.cpython-313.pyc +0 -0
  130. package/tools/__pycache__/huggingface_helper.cpython-313.pyc +0 -0
  131. package/tools/__pycache__/jsonxml_tool.cpython-313.pyc +0 -0
  132. package/tools/__pycache__/line_tools.cpython-313.pyc +0 -0
  133. package/tools/__pycache__/list_comparator.cpython-313.pyc +0 -0
  134. package/tools/__pycache__/markdown_tools.cpython-313.pyc +0 -0
  135. package/tools/__pycache__/mcp_widget.cpython-313.pyc +0 -0
  136. package/tools/__pycache__/notes_widget.cpython-313.pyc +0 -0
  137. package/tools/__pycache__/number_base_converter.cpython-313.pyc +0 -0
  138. package/tools/__pycache__/regex_extractor.cpython-313.pyc +0 -0
  139. package/tools/__pycache__/slug_generator.cpython-313.pyc +0 -0
  140. package/tools/__pycache__/sorter_tools.cpython-313.pyc +0 -0
  141. package/tools/__pycache__/string_escape_tool.cpython-313.pyc +0 -0
  142. package/tools/__pycache__/text_statistics_tool.cpython-313.pyc +0 -0
  143. package/tools/__pycache__/text_wrapper.cpython-313.pyc +0 -0
  144. package/tools/__pycache__/timestamp_converter.cpython-313.pyc +0 -0
  145. package/tools/__pycache__/tool_loader.cpython-313.pyc +0 -0
  146. package/tools/__pycache__/translator_tools.cpython-313.pyc +0 -0
  147. package/tools/__pycache__/url_link_extractor.cpython-313.pyc +0 -0
  148. package/tools/__pycache__/url_parser.cpython-313.pyc +0 -0
  149. package/tools/__pycache__/whitespace_tools.cpython-313.pyc +0 -0
  150. package/tools/__pycache__/word_frequency_counter.cpython-313.pyc +0 -0
  151. package/tools/ai_tools.py +2892 -0
  152. package/tools/ascii_art_generator.py +353 -0
  153. package/tools/base64_tools.py +184 -0
  154. package/tools/base_tool.py +511 -0
  155. package/tools/case_tool.py +309 -0
  156. package/tools/column_tools.py +396 -0
  157. package/tools/cron_tool.py +885 -0
  158. package/tools/curl_history.py +601 -0
  159. package/tools/curl_processor.py +1208 -0
  160. package/tools/curl_settings.py +503 -0
  161. package/tools/curl_tool.py +5467 -0
  162. package/tools/diff_viewer.py +1072 -0
  163. package/tools/email_extraction_tool.py +249 -0
  164. package/tools/email_header_analyzer.py +426 -0
  165. package/tools/extraction_tools.py +250 -0
  166. package/tools/find_replace.py +1751 -0
  167. package/tools/folder_file_reporter.py +1463 -0
  168. package/tools/folder_file_reporter_adapter.py +480 -0
  169. package/tools/generator_tools.py +1217 -0
  170. package/tools/hash_generator.py +256 -0
  171. package/tools/html_tool.py +657 -0
  172. package/tools/huggingface_helper.py +449 -0
  173. package/tools/jsonxml_tool.py +730 -0
  174. package/tools/line_tools.py +419 -0
  175. package/tools/list_comparator.py +720 -0
  176. package/tools/markdown_tools.py +562 -0
  177. package/tools/mcp_widget.py +1417 -0
  178. package/tools/notes_widget.py +973 -0
  179. package/tools/number_base_converter.py +373 -0
  180. package/tools/regex_extractor.py +572 -0
  181. package/tools/slug_generator.py +311 -0
  182. package/tools/sorter_tools.py +459 -0
  183. package/tools/string_escape_tool.py +393 -0
  184. package/tools/text_statistics_tool.py +366 -0
  185. package/tools/text_wrapper.py +431 -0
  186. package/tools/timestamp_converter.py +422 -0
  187. package/tools/tool_loader.py +710 -0
  188. package/tools/translator_tools.py +523 -0
  189. package/tools/url_link_extractor.py +262 -0
  190. package/tools/url_parser.py +205 -0
  191. package/tools/whitespace_tools.py +356 -0
  192. package/tools/word_frequency_counter.py +147 -0
@@ -0,0 +1,730 @@
1
+ import tkinter as tk
2
+ from tkinter import ttk, messagebox
3
+ import json
4
+ import xml.etree.ElementTree as ET
5
+ import xml.dom.minidom
6
+ import re
7
+ from collections import OrderedDict
8
+
9
+ try:
10
+ import jsonpath_ng
11
+ JSONPATH_AVAILABLE = True
12
+ except ImportError:
13
+ JSONPATH_AVAILABLE = False
14
+
15
+ try:
16
+ import lxml.etree as lxml_ET
17
+ LXML_AVAILABLE = True
18
+ except ImportError:
19
+ LXML_AVAILABLE = False
20
+
21
+ class JSONXMLTool:
22
+ def __init__(self, parent_app):
23
+ self.app = parent_app
24
+ self.logger = parent_app.logger if hasattr(parent_app, 'logger') else None
25
+
26
+ def get_default_settings(self):
27
+ """Return default settings for the JSON/XML tool."""
28
+ return {
29
+ "operation": "json_to_xml",
30
+ "json_indent": 2,
31
+ "xml_indent": 2,
32
+ "preserve_attributes": True,
33
+ "sort_keys": False,
34
+ "array_wrapper": "item",
35
+ "root_element": "root",
36
+ "jsonpath_query": "$",
37
+ "xpath_query": "//*"
38
+ }
39
+
40
+ def create_widgets(self, parent, settings):
41
+ """Create the JSON/XML tool interface."""
42
+ main_frame = ttk.Frame(parent)
43
+ main_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
44
+
45
+ # Store reference for font application
46
+ self.main_frame = main_frame
47
+
48
+ # Top row: Operation and Settings side by side
49
+ top_row_frame = ttk.Frame(main_frame)
50
+ top_row_frame.pack(fill=tk.X, pady=(0, 10))
51
+
52
+ # Left side - Operation selection
53
+ operation_frame = ttk.LabelFrame(top_row_frame, text="Operation")
54
+ operation_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 5))
55
+
56
+ self.operation_var = tk.StringVar(value=settings.get("operation", "json_to_xml"))
57
+
58
+ operations = [
59
+ ("json_to_xml", "JSON to XML"),
60
+ ("xml_to_json", "XML to JSON"),
61
+ ("json_prettify", "JSON Prettify"),
62
+ ("xml_prettify", "XML Prettify"),
63
+ ("json_validate", "JSON Validate"),
64
+ ("xml_validate", "XML Validate"),
65
+ ("json_minify", "JSON Minify"),
66
+ ("xml_minify", "XML Minify"),
67
+ ("jsonpath_query", "JSONPath Query"),
68
+ ("xpath_query", "XPath Query")
69
+ ]
70
+
71
+ # Create operation buttons in a grid
72
+ for i, (value, text) in enumerate(operations):
73
+ row = i // 2
74
+ col = i % 2
75
+ ttk.Radiobutton(operation_frame, text=text, variable=self.operation_var,
76
+ value=value, command=self.on_operation_change).grid(
77
+ row=row, column=col, sticky="w", padx=5, pady=2)
78
+
79
+ # Right side - Settings frame
80
+ settings_frame = ttk.LabelFrame(top_row_frame, text="Settings")
81
+ settings_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(5, 0))
82
+
83
+ # JSON/XML formatting settings
84
+ format_frame = ttk.Frame(settings_frame)
85
+ format_frame.pack(fill=tk.X, padx=5, pady=5)
86
+
87
+ ttk.Label(format_frame, text="JSON Indent:").grid(row=0, column=0, sticky="w", padx=(0, 5))
88
+ self.json_indent_var = tk.StringVar(value=str(settings.get("json_indent", 2)))
89
+ ttk.Spinbox(format_frame, from_=0, to=8, width=5, textvariable=self.json_indent_var).grid(row=0, column=1, sticky="w", padx=(0, 10))
90
+
91
+ ttk.Label(format_frame, text="XML Indent:").grid(row=0, column=2, sticky="w", padx=(0, 5))
92
+ self.xml_indent_var = tk.StringVar(value=str(settings.get("xml_indent", 2)))
93
+ ttk.Spinbox(format_frame, from_=0, to=8, width=5, textvariable=self.xml_indent_var).grid(row=0, column=3, sticky="w")
94
+
95
+ # Element naming
96
+ naming_frame = ttk.Frame(settings_frame)
97
+ naming_frame.pack(fill=tk.X, padx=5, pady=5)
98
+
99
+ ttk.Label(naming_frame, text="Array Item Name:").grid(row=0, column=0, sticky="w", padx=(0, 5))
100
+ self.array_wrapper_var = tk.StringVar(value=settings.get("array_wrapper", "item"))
101
+ ttk.Entry(naming_frame, textvariable=self.array_wrapper_var, width=8).grid(row=0, column=1, sticky="w", padx=(0, 10))
102
+
103
+ ttk.Label(naming_frame, text="Root Element:").grid(row=0, column=2, sticky="w", padx=(0, 5))
104
+ self.root_element_var = tk.StringVar(value=settings.get("root_element", "root"))
105
+ ttk.Entry(naming_frame, textvariable=self.root_element_var, width=8).grid(row=0, column=3, sticky="w")
106
+
107
+ # Options frame (full width below)
108
+ options_frame = ttk.LabelFrame(main_frame, text="Options")
109
+ options_frame.pack(fill=tk.X, pady=(0, 10))
110
+
111
+ # Conversion options and AI generation buttons
112
+ options_content_frame = ttk.Frame(options_frame)
113
+ options_content_frame.pack(fill=tk.X, padx=5, pady=5)
114
+
115
+ # Left side - checkboxes
116
+ checkbox_frame = ttk.Frame(options_content_frame)
117
+ checkbox_frame.pack(side=tk.LEFT, fill=tk.Y)
118
+
119
+ self.preserve_attributes_var = tk.BooleanVar(value=settings.get("preserve_attributes", True))
120
+ ttk.Checkbutton(checkbox_frame, text="Preserve XML Attributes",
121
+ variable=self.preserve_attributes_var).pack(anchor="w", pady=2)
122
+
123
+ self.sort_keys_var = tk.BooleanVar(value=settings.get("sort_keys", False))
124
+ ttk.Checkbutton(checkbox_frame, text="Sort JSON Keys",
125
+ variable=self.sort_keys_var).pack(anchor="w", pady=2)
126
+
127
+ # Right side - AI generation buttons
128
+ ai_frame = ttk.Frame(options_content_frame)
129
+ ai_frame.pack(side=tk.RIGHT, fill=tk.Y)
130
+
131
+ ttk.Button(ai_frame, text="Generate JSON with AI",
132
+ command=self.generate_json_with_ai).pack(side=tk.LEFT, padx=(0, 5))
133
+ ttk.Button(ai_frame, text="Generate XML with AI",
134
+ command=self.generate_xml_with_ai).pack(side=tk.LEFT)
135
+
136
+ # Query frame (for JSONPath and XPath)
137
+ self.query_frame = ttk.LabelFrame(main_frame, text="Query")
138
+ self.query_frame.pack(fill=tk.X, pady=(0, 10))
139
+
140
+ ttk.Label(self.query_frame, text="JSONPath:").grid(row=0, column=0, sticky="w", padx=5, pady=2)
141
+ self.jsonpath_var = tk.StringVar(value=settings.get("jsonpath_query", "$"))
142
+ ttk.Entry(self.query_frame, textvariable=self.jsonpath_var, width=40).grid(row=0, column=1, sticky="ew", padx=5, pady=2)
143
+
144
+ ttk.Label(self.query_frame, text="XPath:").grid(row=1, column=0, sticky="w", padx=5, pady=2)
145
+ self.xpath_var = tk.StringVar(value=settings.get("xpath_query", "//*"))
146
+ ttk.Entry(self.query_frame, textvariable=self.xpath_var, width=40).grid(row=1, column=1, sticky="ew", padx=5, pady=2)
147
+
148
+ self.query_frame.columnconfigure(1, weight=1)
149
+
150
+ # Process button
151
+ process_frame = ttk.Frame(main_frame)
152
+ process_frame.pack(fill=tk.X, pady=(0, 5))
153
+
154
+ ttk.Button(process_frame, text="Process", command=self.process_data).pack(side=tk.LEFT)
155
+
156
+ # Status label
157
+ self.status_label = ttk.Label(process_frame, text="Ready", foreground="green")
158
+ self.status_label.pack(side=tk.LEFT, padx=(10, 0))
159
+
160
+ # Initially hide query frame
161
+ self.on_operation_change()
162
+
163
+ # Apply current font settings if available
164
+ try:
165
+ if hasattr(self.app, 'get_best_font'):
166
+ text_font_family, text_font_size = self.app.get_best_font("text")
167
+ font_tuple = (text_font_family, text_font_size)
168
+
169
+ # Apply to Entry widgets
170
+ for child in main_frame.winfo_children():
171
+ self._apply_font_to_children(child, font_tuple)
172
+ except:
173
+ pass # Use default font if font settings not available
174
+
175
+ return main_frame
176
+
177
+ def _apply_font_to_children(self, widget, font_tuple):
178
+ """Recursively apply font to Entry widgets."""
179
+ try:
180
+ if isinstance(widget, (tk.Entry, ttk.Entry)):
181
+ widget.configure(font=font_tuple)
182
+
183
+ # Recursively check children
184
+ if hasattr(widget, 'winfo_children'):
185
+ for child in widget.winfo_children():
186
+ self._apply_font_to_children(child, font_tuple)
187
+ except:
188
+ pass
189
+
190
+ def apply_font_to_widgets(self, font_tuple):
191
+ """Apply font to all Entry widgets in the tool."""
192
+ try:
193
+ # Apply to the main frame and all its children
194
+ if hasattr(self, 'main_frame'):
195
+ self._apply_font_to_children(self.main_frame, font_tuple)
196
+ except Exception as e:
197
+ if self.logger:
198
+ self.logger.debug(f"Error applying font to JSON/XML tool widgets: {e}")
199
+
200
+ def generate_json_with_ai(self):
201
+ """Switch to AI Tools and generate JSON with AI."""
202
+ try:
203
+ # Switch to AI Tools
204
+ self.app.tool_var.set("AI Tools")
205
+ self.app.on_tool_selected()
206
+
207
+ # Find next empty input tab
208
+ next_tab = self._find_next_empty_tab()
209
+ if next_tab is not None:
210
+ # Switch to the empty tab
211
+ self.app.input_notebook.select(next_tab)
212
+
213
+ # Insert the prompt
214
+ prompt = "Please generate Identity JSON file"
215
+ self.app.input_tabs[next_tab].text.delete("1.0", tk.END)
216
+ self.app.input_tabs[next_tab].text.insert("1.0", prompt)
217
+
218
+ if self.logger:
219
+ self.logger.info("Switched to AI Tools with JSON generation prompt")
220
+ else:
221
+ # Use current tab if no empty tab found
222
+ current_tab = self.app.input_notebook.index(self.app.input_notebook.select())
223
+ prompt = "Please generate Identity JSON file"
224
+ self.app.input_tabs[current_tab].text.delete("1.0", tk.END)
225
+ self.app.input_tabs[current_tab].text.insert("1.0", prompt)
226
+
227
+ except Exception as e:
228
+ if self.logger:
229
+ self.logger.error(f"Error switching to AI Tools for JSON generation: {e}")
230
+
231
+ def generate_xml_with_ai(self):
232
+ """Switch to AI Tools and generate XML with AI."""
233
+ try:
234
+ # Switch to AI Tools
235
+ self.app.tool_var.set("AI Tools")
236
+ self.app.on_tool_selected()
237
+
238
+ # Find next empty input tab
239
+ next_tab = self._find_next_empty_tab()
240
+ if next_tab is not None:
241
+ # Switch to the empty tab
242
+ self.app.input_notebook.select(next_tab)
243
+
244
+ # Insert the prompt
245
+ prompt = "Please generate Identity XML file"
246
+ self.app.input_tabs[next_tab].text.delete("1.0", tk.END)
247
+ self.app.input_tabs[next_tab].text.insert("1.0", prompt)
248
+
249
+ if self.logger:
250
+ self.logger.info("Switched to AI Tools with XML generation prompt")
251
+ else:
252
+ # Use current tab if no empty tab found
253
+ current_tab = self.app.input_notebook.index(self.app.input_notebook.select())
254
+ prompt = "Please generate Identity XML file"
255
+ self.app.input_tabs[current_tab].text.delete("1.0", tk.END)
256
+ self.app.input_tabs[current_tab].text.insert("1.0", prompt)
257
+
258
+ except Exception as e:
259
+ if self.logger:
260
+ self.logger.error(f"Error switching to AI Tools for XML generation: {e}")
261
+
262
+ def _find_next_empty_tab(self):
263
+ """Find the next empty input tab."""
264
+ try:
265
+ for i, tab in enumerate(self.app.input_tabs):
266
+ content = tab.text.get("1.0", tk.END).strip()
267
+ if not content:
268
+ return i
269
+ return None
270
+ except:
271
+ return None
272
+
273
+ def on_operation_change(self):
274
+ """Handle operation selection change."""
275
+ operation = self.operation_var.get()
276
+
277
+ # Show/hide query frame based on operation
278
+ if operation in ["jsonpath_query", "xpath_query"]:
279
+ self.query_frame.pack(fill=tk.X, pady=(0, 10))
280
+ else:
281
+ self.query_frame.pack_forget()
282
+
283
+ def process_data(self):
284
+ """Process the data based on selected operation."""
285
+ try:
286
+ # Get input text from current active input tab
287
+ current_input_tab = self.app.input_notebook.index(self.app.input_notebook.select())
288
+ input_text = self.app.input_tabs[current_input_tab].text.get("1.0", tk.END).strip()
289
+ if not input_text:
290
+ self.status_label.config(text="Error: No input text", foreground="red")
291
+ return
292
+
293
+ operation = self.operation_var.get()
294
+ result = ""
295
+
296
+ if operation == "json_to_xml":
297
+ result = self.json_to_xml(input_text)
298
+ elif operation == "xml_to_json":
299
+ result = self.xml_to_json(input_text)
300
+ elif operation == "json_prettify":
301
+ result = self.json_prettify(input_text)
302
+ elif operation == "xml_prettify":
303
+ result = self.xml_prettify(input_text)
304
+ elif operation == "json_validate":
305
+ result = self.json_validate(input_text)
306
+ elif operation == "xml_validate":
307
+ result = self.xml_validate(input_text)
308
+ elif operation == "json_minify":
309
+ result = self.json_minify(input_text)
310
+ elif operation == "xml_minify":
311
+ result = self.xml_minify(input_text)
312
+ elif operation == "jsonpath_query":
313
+ result = self.jsonpath_query(input_text)
314
+ elif operation == "xpath_query":
315
+ result = self.xpath_query(input_text)
316
+
317
+ # Set output text to current active output tab
318
+ current_output_tab = self.app.output_notebook.index(self.app.output_notebook.select())
319
+ self.app.output_tabs[current_output_tab].text.config(state="normal")
320
+ self.app.output_tabs[current_output_tab].text.delete("1.0", tk.END)
321
+ self.app.output_tabs[current_output_tab].text.insert("1.0", result)
322
+ self.app.output_tabs[current_output_tab].text.config(state="disabled")
323
+ self.status_label.config(text="Success", foreground="green")
324
+
325
+ except Exception as e:
326
+ error_msg = f"Error: {str(e)}"
327
+ # Set error message to output tab
328
+ current_output_tab = self.app.output_notebook.index(self.app.output_notebook.select())
329
+ self.app.output_tabs[current_output_tab].text.config(state="normal")
330
+ self.app.output_tabs[current_output_tab].text.delete("1.0", tk.END)
331
+ self.app.output_tabs[current_output_tab].text.insert("1.0", error_msg)
332
+ self.app.output_tabs[current_output_tab].text.config(state="disabled")
333
+ self.status_label.config(text="Error", foreground="red")
334
+ if self.logger:
335
+ self.logger.error(f"JSON/XML Tool error: {e}")
336
+
337
+ def json_to_xml(self, json_text):
338
+ """Convert JSON to XML."""
339
+ try:
340
+ data = json.loads(json_text)
341
+ root_name = self.root_element_var.get() or "root"
342
+
343
+ root = ET.Element(root_name)
344
+ self._dict_to_xml(data, root)
345
+
346
+ # Pretty print
347
+ rough_string = ET.tostring(root, encoding='unicode')
348
+ reparsed = xml.dom.minidom.parseString(rough_string)
349
+ indent = " " * int(self.xml_indent_var.get())
350
+ return reparsed.toprettyxml(indent=indent).split('\n', 1)[1] # Remove XML declaration
351
+
352
+ except json.JSONDecodeError as e:
353
+ raise Exception(f"Invalid JSON: {e}")
354
+ except Exception as e:
355
+ raise Exception(f"JSON to XML conversion failed: {e}")
356
+
357
+ def _dict_to_xml(self, data, parent):
358
+ """Recursively convert dictionary to XML elements."""
359
+ if isinstance(data, dict):
360
+ for key, value in data.items():
361
+ if key.startswith('@') and self.preserve_attributes_var.get():
362
+ # Handle attributes
363
+ parent.set(key[1:], str(value))
364
+ else:
365
+ element = ET.SubElement(parent, self._sanitize_xml_name(key))
366
+ self._dict_to_xml(value, element)
367
+ elif isinstance(data, list):
368
+ array_name = self.array_wrapper_var.get() or "item"
369
+ for item in data:
370
+ element = ET.SubElement(parent, array_name)
371
+ self._dict_to_xml(item, element)
372
+ else:
373
+ parent.text = str(data)
374
+
375
+ def _sanitize_xml_name(self, name):
376
+ """Sanitize name for XML element."""
377
+ # Replace invalid characters with underscores
378
+ name = re.sub(r'[^a-zA-Z0-9_-]', '_', str(name))
379
+ # Ensure it starts with a letter or underscore
380
+ if name and not name[0].isalpha() and name[0] != '_':
381
+ name = '_' + name
382
+ return name or 'element'
383
+
384
+ def xml_to_json(self, xml_text):
385
+ """Convert XML to JSON."""
386
+ try:
387
+ root = ET.fromstring(xml_text)
388
+ data = self._xml_to_dict(root)
389
+
390
+ indent = int(self.json_indent_var.get()) if self.json_indent_var.get() != "0" else None
391
+ sort_keys = self.sort_keys_var.get()
392
+
393
+ return json.dumps(data, indent=indent, sort_keys=sort_keys, ensure_ascii=False)
394
+
395
+ except ET.ParseError as e:
396
+ raise Exception(f"Invalid XML: {e}")
397
+ except Exception as e:
398
+ raise Exception(f"XML to JSON conversion failed: {e}")
399
+
400
+ def _xml_to_dict(self, element):
401
+ """Recursively convert XML element to dictionary."""
402
+ result = {}
403
+
404
+ # Add attributes with @ prefix if preserving attributes
405
+ if element.attrib and self.preserve_attributes_var.get():
406
+ for key, value in element.attrib.items():
407
+ result[f'@{key}'] = value
408
+
409
+ # Handle child elements
410
+ children = list(element)
411
+ if children:
412
+ child_dict = {}
413
+ for child in children:
414
+ child_data = self._xml_to_dict(child)
415
+ if child.tag in child_dict:
416
+ # Convert to array if multiple elements with same tag
417
+ if not isinstance(child_dict[child.tag], list):
418
+ child_dict[child.tag] = [child_dict[child.tag]]
419
+ child_dict[child.tag].append(child_data)
420
+ else:
421
+ child_dict[child.tag] = child_data
422
+ result.update(child_dict)
423
+
424
+ # Handle text content
425
+ if element.text and element.text.strip():
426
+ if result: # If we have attributes or children, use special key for text
427
+ result['#text'] = element.text.strip()
428
+ else: # If no attributes or children, return text directly
429
+ return element.text.strip()
430
+
431
+ return result if result else None
432
+
433
+ def json_prettify(self, json_text):
434
+ """Prettify JSON."""
435
+ try:
436
+ data = json.loads(json_text)
437
+ indent = int(self.json_indent_var.get()) if self.json_indent_var.get() != "0" else None
438
+ sort_keys = self.sort_keys_var.get()
439
+
440
+ return json.dumps(data, indent=indent, sort_keys=sort_keys, ensure_ascii=False)
441
+
442
+ except json.JSONDecodeError as e:
443
+ raise Exception(f"Invalid JSON: {e}")
444
+
445
+ def xml_prettify(self, xml_text):
446
+ """Prettify XML."""
447
+ try:
448
+ root = ET.fromstring(xml_text)
449
+ rough_string = ET.tostring(root, encoding='unicode')
450
+ reparsed = xml.dom.minidom.parseString(rough_string)
451
+ indent = " " * int(self.xml_indent_var.get())
452
+
453
+ pretty = reparsed.toprettyxml(indent=indent)
454
+ # Remove empty lines and clean up
455
+ lines = [line for line in pretty.split('\n') if line.strip()]
456
+ return '\n'.join(lines)
457
+
458
+ except ET.ParseError as e:
459
+ raise Exception(f"Invalid XML: {e}")
460
+
461
+ def json_validate(self, json_text):
462
+ """Validate JSON and return detailed results."""
463
+ try:
464
+ data = json.loads(json_text)
465
+
466
+ # Basic validation info
467
+ result = "✅ JSON is valid!\n\n"
468
+ result += f"Type: {type(data).__name__}\n"
469
+
470
+ if isinstance(data, dict):
471
+ result += f"Keys: {len(data)}\n"
472
+ result += f"Top-level keys: {list(data.keys())[:10]}" # Show first 10 keys
473
+ if len(data) > 10:
474
+ result += f" ... and {len(data) - 10} more"
475
+ elif isinstance(data, list):
476
+ result += f"Items: {len(data)}\n"
477
+ if data:
478
+ result += f"First item type: {type(data[0]).__name__}"
479
+
480
+ result += f"\n\nFormatted JSON:\n{json.dumps(data, indent=2, ensure_ascii=False)}"
481
+
482
+ return result
483
+
484
+ except json.JSONDecodeError as e:
485
+ return f"❌ Invalid JSON!\n\nError: {e}\n\nLine {e.lineno}, Column {e.colno}\n\nTip: Check for missing quotes, commas, or brackets around the error location."
486
+
487
+ def xml_validate(self, xml_text):
488
+ """Validate XML and return detailed results."""
489
+ try:
490
+ root = ET.fromstring(xml_text)
491
+
492
+ result = "✅ XML is valid!\n\n"
493
+ result += f"Root element: <{root.tag}>\n"
494
+ result += f"Attributes: {len(root.attrib)}\n"
495
+ result += f"Child elements: {len(list(root))}\n"
496
+
497
+ # Count all elements
498
+ all_elements = root.findall('.//*')
499
+ result += f"Total elements: {len(all_elements) + 1}\n" # +1 for root
500
+
501
+ # Show element types
502
+ element_types = {}
503
+ for elem in [root] + all_elements:
504
+ element_types[elem.tag] = element_types.get(elem.tag, 0) + 1
505
+
506
+ result += f"\nElement types:\n"
507
+ for tag, count in sorted(element_types.items()):
508
+ result += f" <{tag}>: {count}\n"
509
+
510
+ return result
511
+
512
+ except ET.ParseError as e:
513
+ return f"❌ Invalid XML!\n\nError: {e}\n\nSuggestions:\n- Check for unclosed tags\n- Ensure proper nesting\n- Verify attribute quotes\n- Check for invalid characters in element names"
514
+
515
+ def json_minify(self, json_text):
516
+ """Minify JSON by removing whitespace."""
517
+ try:
518
+ data = json.loads(json_text)
519
+ return json.dumps(data, separators=(',', ':'), ensure_ascii=False)
520
+
521
+ except json.JSONDecodeError as e:
522
+ raise Exception(f"Invalid JSON: {e}")
523
+
524
+ def xml_minify(self, xml_text):
525
+ """Minify XML by removing whitespace."""
526
+ try:
527
+ root = ET.fromstring(xml_text)
528
+
529
+ # Remove whitespace from all elements
530
+ for elem in root.iter():
531
+ if elem.text:
532
+ elem.text = elem.text.strip() or None
533
+ if elem.tail:
534
+ elem.tail = elem.tail.strip() or None
535
+
536
+ return ET.tostring(root, encoding='unicode')
537
+
538
+ except ET.ParseError as e:
539
+ raise Exception(f"Invalid XML: {e}")
540
+
541
+ def jsonpath_query(self, json_text):
542
+ """Execute JSONPath query."""
543
+ if not JSONPATH_AVAILABLE:
544
+ return "❌ JSONPath not available. Install with: pip install jsonpath-ng"
545
+
546
+ try:
547
+ data = json.loads(json_text)
548
+ query = self.jsonpath_var.get() or "$"
549
+
550
+ from jsonpath_ng import parse
551
+ jsonpath_expr = parse(query)
552
+ matches = jsonpath_expr.find(data)
553
+
554
+ result = f"JSONPath Query: {query}\n"
555
+ result += f"Matches found: {len(matches)}\n\n"
556
+
557
+ if matches:
558
+ for i, match in enumerate(matches):
559
+ result += f"Match {i + 1}:\n"
560
+ result += f" Path: {match.full_path}\n"
561
+ result += f" Value: {json.dumps(match.value, indent=2, ensure_ascii=False)}\n\n"
562
+ else:
563
+ result += "No matches found."
564
+
565
+ return result
566
+
567
+ except json.JSONDecodeError as e:
568
+ raise Exception(f"Invalid JSON: {e}")
569
+ except Exception as e:
570
+ raise Exception(f"JSONPath query failed: {e}")
571
+
572
+ def xpath_query(self, xml_text):
573
+ """Execute XPath query."""
574
+ try:
575
+ if LXML_AVAILABLE:
576
+ # Use lxml for better XPath support
577
+ root = lxml_ET.fromstring(xml_text.encode())
578
+ query = self.xpath_var.get() or "//*"
579
+ matches = root.xpath(query)
580
+ else:
581
+ # Fallback to basic ElementTree (limited XPath support)
582
+ root = ET.fromstring(xml_text)
583
+ query = self.xpath_var.get() or ".//*"
584
+ matches = root.findall(query)
585
+
586
+ result = f"XPath Query: {query}\n"
587
+ result += f"Matches found: {len(matches)}\n\n"
588
+
589
+ if matches:
590
+ for i, match in enumerate(matches):
591
+ result += f"Match {i + 1}:\n"
592
+ if hasattr(match, 'tag'):
593
+ result += f" Element: <{match.tag}>\n"
594
+ if match.attrib:
595
+ result += f" Attributes: {match.attrib}\n"
596
+ if match.text and match.text.strip():
597
+ result += f" Text: {match.text.strip()}\n"
598
+ else:
599
+ result += f" Value: {match}\n"
600
+ result += "\n"
601
+ else:
602
+ result += "No matches found."
603
+
604
+ if not LXML_AVAILABLE:
605
+ result += "\n\nNote: Using basic XPath support. Install lxml for advanced XPath features: pip install lxml"
606
+
607
+ return result
608
+
609
+ except ET.ParseError as e:
610
+ raise Exception(f"Invalid XML: {e}")
611
+ except Exception as e:
612
+ raise Exception(f"XPath query failed: {e}")
613
+
614
+ def get_settings(self):
615
+ """Get current settings."""
616
+ return {
617
+ "operation": self.operation_var.get(),
618
+ "json_indent": self.json_indent_var.get(),
619
+ "xml_indent": self.xml_indent_var.get(),
620
+ "preserve_attributes": self.preserve_attributes_var.get(),
621
+ "sort_keys": self.sort_keys_var.get(),
622
+ "array_wrapper": self.array_wrapper_var.get(),
623
+ "root_element": self.root_element_var.get(),
624
+ "jsonpath_query": self.jsonpath_var.get(),
625
+ "xpath_query": self.xpath_var.get()
626
+ }
627
+
628
+
629
+ # Static utility functions for BaseTool
630
+ def _json_prettify_static(text, indent=2):
631
+ """Prettify JSON without UI dependencies."""
632
+ try:
633
+ data = json.loads(text)
634
+ return json.dumps(data, indent=indent, ensure_ascii=False)
635
+ except json.JSONDecodeError as e:
636
+ return f"Invalid JSON: {e}"
637
+
638
+ def _json_minify_static(text):
639
+ """Minify JSON without UI dependencies."""
640
+ try:
641
+ data = json.loads(text)
642
+ return json.dumps(data, separators=(',', ':'), ensure_ascii=False)
643
+ except json.JSONDecodeError as e:
644
+ return f"Invalid JSON: {e}"
645
+
646
+ def _json_validate_static(text):
647
+ """Validate JSON without UI dependencies."""
648
+ try:
649
+ json.loads(text)
650
+ return "✓ Valid JSON"
651
+ except json.JSONDecodeError as e:
652
+ return f"✗ Invalid JSON: {e}"
653
+
654
+ def _xml_prettify_static(text, indent=2):
655
+ """Prettify XML without UI dependencies."""
656
+ try:
657
+ root = ET.fromstring(text)
658
+ rough_string = ET.tostring(root, encoding='unicode')
659
+ reparsed = xml.dom.minidom.parseString(rough_string)
660
+ pretty = reparsed.toprettyxml(indent=" " * indent)
661
+ lines = [line for line in pretty.split('\n') if line.strip()]
662
+ return '\n'.join(lines)
663
+ except ET.ParseError as e:
664
+ return f"Invalid XML: {e}"
665
+
666
+ def _xml_minify_static(text):
667
+ """Minify XML without UI dependencies."""
668
+ try:
669
+ root = ET.fromstring(text)
670
+ return ET.tostring(root, encoding='unicode')
671
+ except ET.ParseError as e:
672
+ return f"Invalid XML: {e}"
673
+
674
+ def _xml_validate_static(text):
675
+ """Validate XML without UI dependencies."""
676
+ try:
677
+ ET.fromstring(text)
678
+ return "✓ Valid XML"
679
+ except ET.ParseError as e:
680
+ return f"✗ Invalid XML: {e}"
681
+
682
+
683
+ # BaseTool-compatible wrapper
684
+ try:
685
+ from tools.base_tool import ToolWithOptions
686
+ from typing import Dict, Any
687
+
688
+ class JSONXMLToolV2(ToolWithOptions):
689
+ """
690
+ BaseTool-compatible version of JSONXMLTool.
691
+ """
692
+
693
+ TOOL_NAME = "JSON/XML Tool"
694
+ TOOL_DESCRIPTION = "Convert, prettify, minify, and validate JSON/XML"
695
+ TOOL_VERSION = "2.0.0"
696
+
697
+ OPTIONS = [
698
+ ("JSON Prettify", "json_prettify"),
699
+ ("JSON Minify", "json_minify"),
700
+ ("JSON Validate", "json_validate"),
701
+ ("XML Prettify", "xml_prettify"),
702
+ ("XML Minify", "xml_minify"),
703
+ ("XML Validate", "xml_validate"),
704
+ ]
705
+ OPTIONS_LABEL = "Operation"
706
+ USE_DROPDOWN = True
707
+ DEFAULT_OPTION = "json_prettify"
708
+
709
+ def process_text(self, input_text: str, settings: Dict[str, Any]) -> str:
710
+ """Process text using the specified JSON/XML operation."""
711
+ mode = settings.get("mode", "json_prettify")
712
+ indent = settings.get("indent", 2)
713
+
714
+ if mode == "json_prettify":
715
+ return _json_prettify_static(input_text, indent)
716
+ elif mode == "json_minify":
717
+ return _json_minify_static(input_text)
718
+ elif mode == "json_validate":
719
+ return _json_validate_static(input_text)
720
+ elif mode == "xml_prettify":
721
+ return _xml_prettify_static(input_text, indent)
722
+ elif mode == "xml_minify":
723
+ return _xml_minify_static(input_text)
724
+ elif mode == "xml_validate":
725
+ return _xml_validate_static(input_text)
726
+ else:
727
+ return input_text
728
+
729
+ except ImportError:
730
+ pass