ProfessionalMario commited on
Commit
0887425
·
verified ·
1 Parent(s): 42ba1a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -162
app.py CHANGED
@@ -1,170 +1,162 @@
1
- import os
2
- import io
3
- import sys
4
- import gradio as gr
5
- from pathlib import Path
6
- from rich.console import Console
7
-
8
- # Import your custom modules
9
- from cli_app.command_handler import handle_command
10
- import cli_app.command_handler as handler
11
- from utils.logger import logger
12
- from vector_store.instruction_embedder import embed_analyze_instructions
13
-
14
- # Global console for local CLI use
15
- console = Console()
16
-
17
- def terminal_logic(command):
18
- """
19
- Captures Rich console output and detects if an image was generated.
20
- Returns: (text_output, image_path)
21
- """
22
- output_buffer = io.StringIO()
23
- temp_console = Console(
24
- file=output_buffer,
25
- force_terminal=True,
26
- width=100,
27
- color_system=None,
28
- legacy_windows=False
29
- )
30
 
31
- old_console = getattr(handler, 'console', None)
32
- handler.console = temp_console
33
 
34
- try:
35
- if not command:
36
- return "Enter a command.", None
37
 
38
- if command.lower() == "exit":
39
- return "Session ended. Refresh to restart.", None
40
-
41
- # Execute logic
42
- result = handle_command(command)
43
- captured = output_buffer.getvalue()
44
-
45
- # --- PLOT DETECTION LOGIC ---
46
- image_path = None
47
- combined_output = f"{captured}\n{result if result else ''}"
48
 
49
- if ".png" in combined_output:
50
- words = combined_output.split()
51
- for word in words:
52
- clean_path = word.strip(".,![]'\"")
53
- if clean_path.endswith(".png") and os.path.exists(clean_path):
54
- image_path = clean_path
55
- break
56
-
57
- full_text = combined_output.strip()
58
- return full_text or "Command executed.", image_path
59
-
60
- except Exception as e:
61
- logger.error(f"Space Terminal Error: {e}")
62
- return f"Error: {str(e)}", None
63
- finally:
64
- if old_console:
65
- handler.console = old_console
66
-
67
- def run_space_interface():
68
- # 1. Initialize Vector Store instructions
69
- embed_analyze_instructions()
70
-
71
- # 2. AUTO-HYDRATE DATA (Detects Parquet and Pickles)
72
- data_dir = Path("data/datasets")
73
- found_data = False
74
-
75
- if data_dir.exists():
76
- for file in os.listdir(data_dir):
77
- if file.endswith((".parquet", ".pkl")) and "embeddings" not in file:
78
- try:
79
- handler.handle_command(f"load {data_dir / file}")
80
- found_data = True
81
- except:
82
- pass
83
-
84
- # 3. Generate Help Table for Welcome Screen
85
- help_buffer = io.StringIO()
86
- help_console = Console(file=help_buffer, force_terminal=True, width=100, color_system=None)
 
 
 
 
 
 
87
 
88
- old_console = getattr(handler, 'console', None)
89
- handler.console = help_console
90
- handler.handle_command("help")
91
- welcome_table = help_buffer.getvalue()
92
- handler.console = old_console
93
-
94
- status_msg = "✅ Datasets Ready" if found_data else "⚠️ No Datasets Found. Use 'load <path>'"
95
- welcome_text = f"WELCOME TO EDA EXPLORER\n{status_msg}\n{'='*25}\n{welcome_table}"
96
-
97
- # 4. Build the Modern Terminal UI
98
- # analytics_enabled=False and show_api=False are the key fixes for the TypeError
99
- with gr.Blocks(
100
- title="EDA Explorer Terminal",
101
- theme=gr.themes.Monochrome(),
102
- analytics_enabled=False
103
- ) as demo:
104
-
105
- gr.Markdown("# 📊 EDA Explorer Terminal")
106
 
107
- with gr.Row():
108
- with gr.Column(scale=3):
109
- # FIX: Removed language="markdown" as it sometimes conflicts with raw text schema
110
- output_box = gr.Textbox(
111
- value=welcome_text,
112
- label="Console Output",
113
- lines=25,
114
- max_lines=25,
115
- interactive=False
116
- )
117
- with gr.Column(scale=2):
118
- # FIX: Removed interactive=False as it's the #1 cause of the 'bool' iterable error
119
- plot_output = gr.Image(
120
- label="Visual Analysis",
121
- type="filepath"
122
- )
123
 
124
- input_box = gr.Textbox(
125
- label="Command Line",
126
- placeholder="e.g., analyze titanic or histogram Age in titanic",
127
- autofocus=True
128
- )
129
-
130
- gr.Examples(
131
- examples=[
132
- ["list"],
133
- ["NL: show top 10 rows in titanic"],
134
- ["NL: average Age in titanic"],
135
- ["NL: histogram of Age in titanic"],
136
- ["NL: bar chart of Gender in Customer_Churn"]
137
- ],
138
- inputs=input_box,
139
- label="Quick Actions"
140
- )
141
-
142
- # FIX: Added api_name=None to stop the schema generator from touching this function
143
- input_box.submit(
144
- fn=terminal_logic,
145
- inputs=input_box,
146
- outputs=[output_box, plot_output],
147
- api_name=None
148
- )
149
 
150
- # FIX: show_api=False kills the background process that triggers the error
151
- demo.launch(server_name="0.0.0.0", server_port=7860, show_api=False)
152
-
153
- def run_cli():
154
- """Standard local terminal loop."""
155
- embed_analyze_instructions()
156
- console.print("\n[bold cyan]EDA Explorer CLI[/bold cyan]")
157
- while True:
158
- try:
159
- cmd = console.input("[bold yellow]> [/bold yellow]")
160
- if cmd.lower() == "exit": break
161
- result = handle_command(cmd)
162
- if result: console.print(result)
163
- except (KeyboardInterrupt, EOFError): break
164
- except Exception as e: console.print(f"[red]Error:[/red] {e}")
165
-
166
- if __name__ == "__main__":
167
- if "SPACE_ID" in os.environ:
168
- run_space_interface()
169
- else:
170
- run_cli()
 
 
 
 
1
+ # import os
2
+ # import io
3
+ # import sys
4
+ # import gradio as gr
5
+ # from pathlib import Path
6
+ # from rich.console import Console
7
+
8
+ # # Import your custom modules
9
+ # from cli_app.command_handler import handle_command
10
+ # import cli_app.command_handler as handler
11
+ # from utils.logger import logger
12
+ # from vector_store.instruction_embedder import embed_analyze_instructions
13
+
14
+ # # Global console for local CLI use
15
+ # console = Console()
16
+
17
+ # def terminal_logic(command):
18
+ # """
19
+ # Captures Rich console output and detects if an image was generated.
20
+ # Returns: (text_output, image_path)
21
+ # """
22
+ # output_buffer = io.StringIO()
23
+ # temp_console = Console(
24
+ # file=output_buffer,
25
+ # force_terminal=True,
26
+ # width=100,
27
+ # color_system=None,
28
+ # legacy_windows=False
29
+ # )
30
 
31
+ # old_console = getattr(handler, 'console', None)
32
+ # handler.console = temp_console
33
 
34
+ # try:
35
+ # if command.lower() == "exit":
36
+ # return "Session ended. Refresh to restart.", None
37
 
38
+ # # Execute logic
39
+ # result = handle_command(command)
40
+ # captured = output_buffer.getvalue()
 
 
 
 
 
 
 
41
 
42
+ # # --- PLOT DETECTION LOGIC ---
43
+ # # Look for a path in the result or captured text (e.g., "output/plot.png")
44
+ # # Adjust the 'output' string to match where your tool saves PNGs
45
+ # image_path = None
46
+ # if ".png" in captured or (result and ".png" in result):
47
+ # # Simple heuristic: find a word ending in .png
48
+ # words = (captured + (result or "")).split()
49
+ # for word in words:
50
+ # if word.endswith(".png") and os.path.exists(word):
51
+ # image_path = word
52
+ # break
53
+
54
+ # full_text = f"{captured}\n{result if result else ''}".strip()
55
+ # return full_text or "Command executed.", image_path
56
+
57
+ # except Exception as e:
58
+ # logger.error(f"Space Terminal Error: {e}")
59
+ # return f"Error: {str(e)}", None
60
+ # finally:
61
+ # if old_console:
62
+ # handler.console = old_console
63
+
64
+ # def run_space_interface():
65
+ # # 1. Initialize Vector Store instructions
66
+ # embed_analyze_instructions()
67
+
68
+ # # 2. AUTO-HYDRATE DATA (Detects Parquet and Pickles)
69
+ # # Looking in data/datasets/ because that's where your sync folder puts them
70
+ # data_dir = Path("data/datasets")
71
+ # found_data = False
72
+
73
+ # if data_dir.exists():
74
+ # for file in os.listdir(data_dir):
75
+ # if file.endswith((".parquet", ".pkl")) and "embeddings" not in file:
76
+ # try:
77
+ # # Simulates 'load data/datasets/filename'
78
+ # handler.handle_command(f"load {data_dir / file}")
79
+ # found_data = True
80
+ # except:
81
+ # pass
82
+
83
+ # # 3. Generate Help Table for Welcome Screen
84
+ # help_buffer = io.StringIO()
85
+ # help_console = Console(file=help_buffer, force_terminal=True, width=100, color_system=None)
86
 
87
+ # old_console = getattr(handler, 'console', None)
88
+ # handler.console = help_console
89
+ # handler.handle_command("help")
90
+ # welcome_table = help_buffer.getvalue()
91
+ # handler.console = old_console
92
+
93
+ # status_msg = "✅ Datasets Ready" if found_data else "⚠️ No Datasets Found. Use 'load <path>'"
94
+ # welcome_text = f"WELCOME TO EDA EXPLORER\n{status_msg}\n{'='*25}\n{welcome_table}"
95
+
96
+ # # 4. Build the Modern Terminal UI
97
+ # with gr.Blocks(title="EDA Explorer Terminal", theme="monochrome") as demo:
98
+ # gr.Markdown("# 📊 EDA Explorer Terminal")
 
 
 
 
 
 
99
 
100
+ # with gr.Row():
101
+ # with gr.Column(scale=3):
102
+ # output_box = gr.Code(
103
+ # value=welcome_text,
104
+ # label="Console Output",
105
+ # language="markdown",
106
+ # lines=25
107
+ # )
108
+ # with gr.Column(scale=2):
109
+ # plot_output = gr.Image(
110
+ # label="Visual Analysis",
111
+ # type="filepath",
112
+ # interactive=False
113
+ # )
 
 
114
 
115
+ # input_box = gr.Textbox(
116
+ # label="Command Line",
117
+ # placeholder="e.g., analyze titanic or histogram Age in titanic",
118
+ # autofocus=True
119
+ # )
120
+
121
+ # gr.Examples(
122
+ # examples=[
123
+ # ["list"],
124
+ # ["analyze titanic"],
125
+ # ["histogram Age in titanic"],
126
+ # ["info Customer_Churn"]
127
+ # ],
128
+ # inputs=input_box,
129
+ # label="Quick Actions"
130
+ # )
131
+
132
+ # # Submit triggers the logic and updates BOTH the text and the image
133
+ # input_box.submit(
134
+ # fn=terminal_logic,
135
+ # inputs=input_box,
136
+ # outputs=[output_box, plot_output]
137
+ # )
 
 
138
 
139
+ # demo.launch(server_name="0.0.0.0", server_port=7860)
140
+
141
+ # def run_cli():
142
+ # """Standard local terminal loop."""
143
+ # embed_analyze_instructions()
144
+ # console.print("\n[bold cyan]EDA Explorer CLI[/bold cyan]")
145
+ # while True:
146
+ # try:
147
+ # cmd = console.input("[bold yellow]> [/bold yellow]")
148
+ # if cmd.lower() == "exit": break
149
+ # result = handle_command(cmd)
150
+ # if result: console.print(result)
151
+ # except (KeyboardInterrupt, EOFError): break
152
+ # except Exception as e: console.print(f"[red]Error:[/red] {e}")
153
+
154
+ # if __name__ == "__main__":
155
+ # if "SPACE_ID" in os.environ:
156
+ # run_space_interface()
157
+ # else:
158
+ # run_cli()
159
+
160
+
161
+
162
+