Spaces:
Configuration error
Configuration error
Update app.py
Browse files
app.py
CHANGED
|
@@ -14,7 +14,8 @@ class DataAnalyzer:
|
|
| 14 |
def __init__(self):
|
| 15 |
self.data: Optional[pd.DataFrame] = None
|
| 16 |
|
| 17 |
-
def create_plot(self, plot_type: str, **kwargs) ->
|
|
|
|
| 18 |
if self.data is None:
|
| 19 |
raise ValueError("No data loaded")
|
| 20 |
|
|
@@ -55,8 +56,9 @@ class DataAnalyzer:
|
|
| 55 |
)
|
| 56 |
else:
|
| 57 |
raise ValueError(f"Unknown plot type: {plot_type}")
|
| 58 |
-
|
| 59 |
-
|
|
|
|
| 60 |
|
| 61 |
class ChatAnalyzer:
|
| 62 |
def __init__(self):
|
|
@@ -83,12 +85,12 @@ class ChatAnalyzer:
|
|
| 83 |
self.history = [("System", f"Error loading file: {str(e)}")]
|
| 84 |
return self.history
|
| 85 |
|
| 86 |
-
def chat(self, message: str, api_key: str) -> Tuple[List[Tuple[str, str]],
|
| 87 |
if self.analyzer.data is None:
|
| 88 |
-
return [(message, "Please upload a data file first.")],
|
| 89 |
|
| 90 |
if not api_key:
|
| 91 |
-
return [(message, "Please provide an OpenAI API key.")],
|
| 92 |
|
| 93 |
try:
|
| 94 |
os.environ["OPENAI_API_KEY"] = api_key
|
|
@@ -109,7 +111,7 @@ class ChatAnalyzer:
|
|
| 109 |
analysis = completion_response.choices[0].message.content
|
| 110 |
|
| 111 |
# Create visualizations
|
| 112 |
-
|
| 113 |
try:
|
| 114 |
# Execute any visualization commands in the analysis
|
| 115 |
exec_globals = {
|
|
@@ -117,7 +119,7 @@ class ChatAnalyzer:
|
|
| 117 |
'df': self.analyzer.data,
|
| 118 |
'px': px,
|
| 119 |
'go': go,
|
| 120 |
-
'print': lambda x:
|
| 121 |
}
|
| 122 |
|
| 123 |
# Extract code blocks
|
|
@@ -125,7 +127,9 @@ class ChatAnalyzer:
|
|
| 125 |
code_blocks = re.findall(r'```python\n(.*?)```', analysis, re.DOTALL)
|
| 126 |
|
| 127 |
for code in code_blocks:
|
| 128 |
-
exec(code, exec_globals)
|
|
|
|
|
|
|
| 129 |
|
| 130 |
except Exception as e:
|
| 131 |
analysis += f"\n\nError creating visualization: {str(e)}"
|
|
@@ -133,14 +137,11 @@ class ChatAnalyzer:
|
|
| 133 |
# Update chat history
|
| 134 |
self.history.append((message, analysis))
|
| 135 |
|
| 136 |
-
|
| 137 |
-
plots = [gr.Plot(fig) for fig in figures]
|
| 138 |
-
|
| 139 |
-
return self.history, plots
|
| 140 |
|
| 141 |
except Exception as e:
|
| 142 |
self.history.append((message, f"Error: {str(e)}"))
|
| 143 |
-
return self.history,
|
| 144 |
|
| 145 |
def _get_data_context(self) -> str:
|
| 146 |
df = self.analyzer.data
|
|
@@ -161,11 +162,11 @@ Example commands:
|
|
| 161 |
```python
|
| 162 |
# Create scatter plot
|
| 163 |
fig = px.scatter(df, x='column1', y='column2', title='Analysis')
|
| 164 |
-
|
| 165 |
|
| 166 |
# Create histogram
|
| 167 |
fig = px.histogram(df, x='column', title='Distribution')
|
| 168 |
-
|
| 169 |
```
|
| 170 |
|
| 171 |
Provide analysis and insights along with visualizations."""
|
|
@@ -173,7 +174,7 @@ Provide analysis and insights along with visualizations."""
|
|
| 173 |
def create_interface():
|
| 174 |
analyzer = ChatAnalyzer()
|
| 175 |
|
| 176 |
-
with gr.Blocks() as demo:
|
| 177 |
gr.Markdown("""
|
| 178 |
# Interactive Data Analysis Chat
|
| 179 |
Upload your data and chat with AI to analyze it!
|
|
@@ -196,8 +197,8 @@ def create_interface():
|
|
| 196 |
)
|
| 197 |
send = gr.Button("Send")
|
| 198 |
|
| 199 |
-
# Plot output area
|
| 200 |
-
plot_output = gr.
|
| 201 |
|
| 202 |
# Event handlers
|
| 203 |
file.change(
|
|
|
|
| 14 |
def __init__(self):
|
| 15 |
self.data: Optional[pd.DataFrame] = None
|
| 16 |
|
| 17 |
+
def create_plot(self, plot_type: str, **kwargs) -> str:
|
| 18 |
+
"""Create plot and return HTML string"""
|
| 19 |
if self.data is None:
|
| 20 |
raise ValueError("No data loaded")
|
| 21 |
|
|
|
|
| 56 |
)
|
| 57 |
else:
|
| 58 |
raise ValueError(f"Unknown plot type: {plot_type}")
|
| 59 |
+
|
| 60 |
+
# Convert plot to HTML string
|
| 61 |
+
return fig.to_html(include_plotlyjs=True, full_html=False)
|
| 62 |
|
| 63 |
class ChatAnalyzer:
|
| 64 |
def __init__(self):
|
|
|
|
| 85 |
self.history = [("System", f"Error loading file: {str(e)}")]
|
| 86 |
return self.history
|
| 87 |
|
| 88 |
+
def chat(self, message: str, api_key: str) -> Tuple[List[Tuple[str, str]], str]:
|
| 89 |
if self.analyzer.data is None:
|
| 90 |
+
return [(message, "Please upload a data file first.")], ""
|
| 91 |
|
| 92 |
if not api_key:
|
| 93 |
+
return [(message, "Please provide an OpenAI API key.")], ""
|
| 94 |
|
| 95 |
try:
|
| 96 |
os.environ["OPENAI_API_KEY"] = api_key
|
|
|
|
| 111 |
analysis = completion_response.choices[0].message.content
|
| 112 |
|
| 113 |
# Create visualizations
|
| 114 |
+
plot_html = ""
|
| 115 |
try:
|
| 116 |
# Execute any visualization commands in the analysis
|
| 117 |
exec_globals = {
|
|
|
|
| 119 |
'df': self.analyzer.data,
|
| 120 |
'px': px,
|
| 121 |
'go': go,
|
| 122 |
+
'print': lambda x: x # Will be used to capture plot output
|
| 123 |
}
|
| 124 |
|
| 125 |
# Extract code blocks
|
|
|
|
| 127 |
code_blocks = re.findall(r'```python\n(.*?)```', analysis, re.DOTALL)
|
| 128 |
|
| 129 |
for code in code_blocks:
|
| 130 |
+
result = exec(code, exec_globals)
|
| 131 |
+
if isinstance(result, (go.Figure, px.Figure)):
|
| 132 |
+
plot_html += result.to_html(include_plotlyjs=True, full_html=False)
|
| 133 |
|
| 134 |
except Exception as e:
|
| 135 |
analysis += f"\n\nError creating visualization: {str(e)}"
|
|
|
|
| 137 |
# Update chat history
|
| 138 |
self.history.append((message, analysis))
|
| 139 |
|
| 140 |
+
return self.history, plot_html
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
except Exception as e:
|
| 143 |
self.history.append((message, f"Error: {str(e)}"))
|
| 144 |
+
return self.history, ""
|
| 145 |
|
| 146 |
def _get_data_context(self) -> str:
|
| 147 |
df = self.analyzer.data
|
|
|
|
| 162 |
```python
|
| 163 |
# Create scatter plot
|
| 164 |
fig = px.scatter(df, x='column1', y='column2', title='Analysis')
|
| 165 |
+
fig # Return the figure object
|
| 166 |
|
| 167 |
# Create histogram
|
| 168 |
fig = px.histogram(df, x='column', title='Distribution')
|
| 169 |
+
fig # Return the figure object
|
| 170 |
```
|
| 171 |
|
| 172 |
Provide analysis and insights along with visualizations."""
|
|
|
|
| 174 |
def create_interface():
|
| 175 |
analyzer = ChatAnalyzer()
|
| 176 |
|
| 177 |
+
with gr.Blocks(css="footer {visibility: hidden}") as demo:
|
| 178 |
gr.Markdown("""
|
| 179 |
# Interactive Data Analysis Chat
|
| 180 |
Upload your data and chat with AI to analyze it!
|
|
|
|
| 197 |
)
|
| 198 |
send = gr.Button("Send")
|
| 199 |
|
| 200 |
+
# Plot output area (using HTML for interactive plots)
|
| 201 |
+
plot_output = gr.HTML(label="Visualization")
|
| 202 |
|
| 203 |
# Event handlers
|
| 204 |
file.change(
|