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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
import os
from dotenv import load_dotenv
import uuid
import matplotlib.pyplot as plt
from pathlib import Path
from typing import Dict, Any, List, Optional
import pandas as pd
import numpy as np
import json
import io
import contextlib
import traceback
import time
from datetime import datetime, timedelta
import seaborn as sns
import scipy.stats as stats
from pydantic import BaseModel

from supabase_service import upload_file_to_supabase

# Load environment variables from .env file
load_dotenv()

class CodeResponse(BaseModel):
    """Container for code-related responses"""
    language: str = "python"
    code: str


class ChartSpecification(BaseModel):
    """Details about requested charts"""
    image_description: str
    code: Optional[str] = None


class AnalysisOperation(BaseModel):
    """Container for a single analysis operation with its code and result"""
    code: CodeResponse
    description: str


class CsvChatResult(BaseModel):
    """Structured response for CSV-related AI interactions"""
    response_type: str  # Literal["casual", "data_analysis", "visualization", "mixed"]
    casual_response: str
    analysis_operations: List[AnalysisOperation]
    charts: Optional[List[ChartSpecification]] = None


class PythonExecutor:
    """Handles execution of Python code with comprehensive data analysis libraries"""
    
    def __init__(self, df: pd.DataFrame, charts_folder: str = "generated_charts"):
        """
        Initialize the PythonExecutor with a DataFrame
        
        Args:
            df (pd.DataFrame): The DataFrame to operate on
            charts_folder (str): Folder to save charts in
        """
        self.df = df
        self.charts_folder = Path(charts_folder)
        self.charts_folder.mkdir(exist_ok=True)
        
    def execute_code(self, code: str) -> Dict[str, Any]:
        """
        Execute Python code with full data analysis context and return results
        
        Args:
            code (str): Python code to execute
            
        Returns:
            dict: Dictionary containing execution results and any generated plots
        """
        output = ""
        error = None
        plots = []
        
        # Capture stdout
        stdout = io.StringIO()
        
        # Monkey patch plt.show() to save figures
        original_show = plt.show
        
        def custom_show():
            """Custom show function that saves plots instead of displaying them"""
            for i, fig in enumerate(plt.get_fignums()):
                figure = plt.figure(fig)
                # Save plot to bytes buffer
                buf = io.BytesIO()
                figure.savefig(buf, format='png', bbox_inches='tight')
                buf.seek(0)
                plots.append(buf.read())
            plt.close('all')
        
        try:
            # Create comprehensive execution context with data analysis libraries
            exec_globals = {
                # Core data analysis
                'pd': pd,
                'np': np,
                'df': self.df,
                
                # Visualization
                'plt': plt,
                'sns': sns,
                
                # Statistics
                'stats': stats,
                
                # Date/time
                'datetime': datetime,
                'timedelta': timedelta,
                'time': time,
                
                # Utilities
                'json': json,
                '__builtins__': __builtins__,
            }
            
            # Replace plt.show with custom implementation
            plt.show = custom_show
            
            # Execute code and capture output
            with contextlib.redirect_stdout(stdout):
                exec(code, exec_globals)
            
            output = stdout.getvalue()
            
        except Exception as e:
            error = {
                "message": str(e),
                "traceback": traceback.format_exc()
            }
        finally:
            # Restore original plt.show
            plt.show = original_show
            
        return {
            'output': output,
            'error': error,
            'plots': plots
        }
    
    async def save_plot_to_supabase(self, plot_data: bytes, description: str, chat_id: str) -> str:
        """
        Save plot to Supabase storage and return the public URL
        
        Args:
            plot_data (bytes): Image data in bytes
            description (str): Description of the plot
            chat_id (str): ID of the chat session
            
        Returns:
            str: Public URL of the uploaded chart
        """
        # Generate unique filename
        filename = f"chart_{uuid.uuid4().hex}.png"
        filepath = self.charts_folder / filename
        
        # Save the plot locally first
        with open(filepath, 'wb') as f:
            f.write(plot_data)
            
        try:
            # Upload to Supabase
            public_url = await upload_file_to_supabase(
                file_path=str(filepath),
                file_name=filename,
                chat_id=chat_id
            )
            
            # Remove the local file after upload
            os.remove(filepath)
            
            return public_url
        except Exception as e:
            # Clean up local file if upload fails
            if os.path.exists(filepath):
                os.remove(filepath)
            raise Exception(f"Failed to upload plot to Supabase: {e}")
    
    def _looks_like_structured_data(self, output: str) -> bool:
        """Helper to detect JSON-like or array-like output"""
        output = output.strip()
        return (
            output.startswith('{') and output.endswith('}') or  # JSON object
            output.startswith('[') and output.endswith(']') or  # Array
            '\n' in output and '=' in output  # Python console output
        )
    
    async def process_response(self, response: CsvChatResult, chat_id: str) -> str:
        """
        Process the CsvChatResult response and generate formatted output
        with markdown code blocks for structured data.
        
        Args:
            response (CsvChatResult): Response from CSV analysis
            chat_id (str): ID of the chat session
            
        Returns:
            str: Formatted output with results and image URLs
        """
        output_parts = []
        
        # Add casual response
        output_parts.append(response.casual_response)
        
        # Process analysis operations
        for operation in response.analysis_operations:
            # Execute the code
            result = self.execute_code(operation.code.code)
            
            # Add operation description
            output_parts.append(f"\n{operation.description}:")
            
            # Add output or error with markdown wrapping
            if result['error']:
                output_parts.append("```python\n" + f"Error: {result['error']['message']}" + "\n```")
            else:
                output = result['output'].strip()
                if self._looks_like_structured_data(output):
                    output_parts.append("```python\n" + output + "\n```")
                else:
                    output_parts.append(output)
        
        # Process charts
        if response.charts:
            output_parts.append("\nVisualizations:")
            for chart in response.charts:
                if chart.code:
                    result = self.execute_code(chart.code)
                    if result['plots']:
                        for plot_data in result['plots']:
                            try:
                                public_url = await self.save_plot_to_supabase(
                                    plot_data=plot_data,
                                    description=chart.image_description,
                                    chat_id=chat_id
                                )
                                output_parts.append(f"\n{chart.image_description}")
                                output_parts.append(f"![{chart.image_description}]({public_url})")
                            except Exception as e:
                                output_parts.append(f"\nError uploading chart: {str(e)}")
                    elif result['error']:
                        output_parts.append("```python\n" + f"Error generating {chart.image_description}: {result['error']['message']}" + "\n```")
        
        return "\n".join(output_parts)







# Table formatter

# import os
# from dotenv import load_dotenv
# import uuid
# import matplotlib.pyplot as plt
# from pathlib import Path
# from typing import Dict, Any, List, Optional
# import pandas as pd
# import numpy as np
# import json
# import io
# import contextlib
# import traceback
# import time
# from datetime import datetime, timedelta
# import seaborn as sns
# import scipy.stats as stats
# from pydantic import BaseModel

# from supabase_service import upload_file_to_supabase

# # Load environment variables from .env file
# load_dotenv()

# class CodeResponse(BaseModel):
#     """Container for code-related responses"""
#     language: str = "python"
#     code: str


# class ChartSpecification(BaseModel):
#     """Details about requested charts"""
#     image_description: str
#     code: Optional[str] = None


# class AnalysisOperation(BaseModel):
#     """Container for a single analysis operation with its code and result"""
#     code: CodeResponse
#     description: str


# class CsvChatResult(BaseModel):
#     """Structured response for CSV-related AI interactions"""
#     response_type: str  # Literal["casual", "data_analysis", "visualization", "mixed"]
#     casual_response: str
#     analysis_operations: List[AnalysisOperation]
#     charts: Optional[List[ChartSpecification]] = None


# class PythonExecutor:
#     """Handles execution of Python code with comprehensive data analysis libraries"""
    
#     def __init__(self, df: pd.DataFrame, charts_folder: str = "generated_charts"):
#         """
#         Initialize the PythonExecutor with a DataFrame
        
#         Args:
#             df (pd.DataFrame): The DataFrame to operate on
#             charts_folder (str): Folder to save charts in
#         """
#         self.df = df
#         self.charts_folder = Path(charts_folder)
#         self.charts_folder.mkdir(exist_ok=True)
        
#     def execute_code(self, code: str) -> Dict[str, Any]:
#         """
#         Execute Python code with full data analysis context and return results
        
#         Args:
#             code (str): Python code to execute
            
#         Returns:
#             dict: Dictionary containing execution results and any generated plots
#         """
#         output = ""
#         error = None
#         plots = []
        
#         # Capture stdout
#         stdout = io.StringIO()
        
#         # Monkey patch plt.show() to save figures
#         original_show = plt.show
        
#         def custom_show():
#             """Custom show function that saves plots instead of displaying them"""
#             for i, fig in enumerate(plt.get_fignums()):
#                 figure = plt.figure(fig)
#                 # Save plot to bytes buffer
#                 buf = io.BytesIO()
#                 figure.savefig(buf, format='png', bbox_inches='tight')
#                 buf.seek(0)
#                 plots.append(buf.read())
#             plt.close('all')
        
#         try:
#             # Create comprehensive execution context with data analysis libraries
#             exec_globals = {
#                 # Core data analysis
#                 'pd': pd,
#                 'np': np,
#                 'df': self.df,
                
#                 # Visualization
#                 'plt': plt,
#                 'sns': sns,
                
#                 # Statistics
#                 'stats': stats,
                
#                 # Date/time
#                 'datetime': datetime,
#                 'timedelta': timedelta,
#                 'time': time,
                
#                 # Utilities
#                 'json': json,
#                 '__builtins__': __builtins__,
#             }
            
#             # Replace plt.show with custom implementation
#             plt.show = custom_show
            
#             # Execute code and capture output
#             with contextlib.redirect_stdout(stdout):
#                 exec(code, exec_globals)
            
#             output = stdout.getvalue()
            
#         except Exception as e:
#             error = {
#                 "message": str(e),
#                 "traceback": traceback.format_exc()
#             }
#         finally:
#             # Restore original plt.show
#             plt.show = original_show
            
#         return {
#             'output': output,
#             'error': error,
#             'plots': plots
#         }
    
#     def _convert_dataframe_to_text(self, df: pd.DataFrame) -> str:
#         """
#         Convert pandas DataFrame to a text format that can be easily rendered
#         in the frontend using the ScrollableTableRenderer component.
        
#         Args:
#             df (pd.DataFrame): DataFrame to convert
            
#         Returns:
#             str: Text representation of the DataFrame
#         """
#         # Convert DataFrame to string with proper formatting
#         df_str = df.to_string(index=True)
        
#         # Split into lines and clean up
#         lines = df_str.split('\n')
        
#         # Remove any trailing whitespace from each line
#         cleaned_lines = [line.rstrip() for line in lines]
        
#         # Join back with newlines
#         return '\n'.join(cleaned_lines)
    
#     async def save_plot_to_supabase(self, plot_data: bytes, description: str, chat_id: str) -> str:
#         """
#         Save plot to Supabase storage and return the public URL
        
#         Args:
#             plot_data (bytes): Image data in bytes
#             description (str): Description of the plot
#             chat_id (str): ID of the chat session
            
#         Returns:
#             str: Public URL of the uploaded chart
#         """
#         # Generate unique filename
#         filename = f"chart_{uuid.uuid4().hex}.png"
#         filepath = self.charts_folder / filename
        
#         # Save the plot locally first
#         with open(filepath, 'wb') as f:
#             f.write(plot_data)
            
#         try:
#             # Upload to Supabase
#             public_url = await upload_file_to_supabase(
#                 file_path=str(filepath),
#                 file_name=filename,
#                 chat_id=chat_id
#             )
            
#             # Remove the local file after upload
#             os.remove(filepath)
            
#             return public_url
#         except Exception as e:
#             # Clean up local file if upload fails
#             if os.path.exists(filepath):
#                 os.remove(filepath)
#             raise Exception(f"Failed to upload plot to Supabase: {e}")
    
#     def _looks_like_structured_data(self, output: str) -> bool:
#         """Helper to detect JSON-like or array-like output"""
#         output = output.strip()
#         return (
#             output.startswith('{') and output.endswith('}') or  # JSON object
#             output.startswith('[') and output.endswith(']') or  # Array
#             '\n' in output and '=' in output  # Python console output
#         )
    
#     def _is_dataframe_output(self, output: str) -> bool:
#         """Helper to detect if output looks like a pandas DataFrame"""
#         lines = output.strip().split('\n')
#         if len(lines) < 2:
#             return False
        
#         # Check for typical DataFrame header pattern
#         first_line = lines[0].strip()
#         second_line = lines[1].strip()
        
#         # Look for column headers and separator line
#         if not first_line or not second_line:
#             return False
            
#         # Check if the first line contains column names
#         # and the second line has some alignment characters
#         return True
    
#     async def process_response(self, response: CsvChatResult, chat_id: str) -> str:
#         """
#         Process the CsvChatResult response and generate formatted output
#         with markdown code blocks for structured data.
        
#         Args:
#             response (CsvChatResult): Response from CSV analysis
#             chat_id (str): ID of the chat session
            
#         Returns:
#             str: Formatted output with results and image URLs
#         """
#         output_parts = []
        
#         # Add casual response
#         output_parts.append(response.casual_response)
        
#         # Process analysis operations
#         for operation in response.analysis_operations:
#             # Execute the code
#             result = self.execute_code(operation.code.code)
            
#             # Add operation description
#             output_parts.append(f"\n{operation.description}:")
            
#             # Add output or error with markdown wrapping
#             if result['error']:
#                 output_parts.append("```python\n" + f"Error: {result['error']['message']}" + "\n```")
#             else:
#                 output = result['output'].strip()
                
#                 # Check if the output is a DataFrame-like structure
#                 if self._is_dataframe_output(output):
#                     # Convert to a clean text format for frontend rendering
#                     try:
#                         # Get the last evaluated expression which might be the DataFrame
#                         # This is a simple approach - in practice you might need a more robust way
#                         # to capture the actual DataFrame from the execution context
#                         df_output = self._convert_dataframe_to_text(eval(operation.code.code.split('\n')[-1], globals(), locals()))
#                         output_parts.append("```text\n" + df_output + "\n```")
#                     except:
#                         # Fall back to regular output if we can't convert it
#                         output_parts.append("```text\n" + output + "\n```")
#                 elif self._looks_like_structured_data(output):
#                     output_parts.append("```python\n" + output + "\n```")
#                 else:
#                     output_parts.append(output)
        
#         # Process charts
#         if response.charts:
#             output_parts.append("\nVisualizations:")
#             for chart in response.charts:
#                 if chart.code:
#                     result = self.execute_code(chart.code)
#                     if result['plots']:
#                         for plot_data in result['plots']:
#                             try:
#                                 public_url = await self.save_plot_to_supabase(
#                                     plot_data=plot_data,
#                                     description=chart.image_description,
#                                     chat_id=chat_id
#                                 )
#                                 output_parts.append(f"\n{chart.image_description}")
#                                 output_parts.append(f"![{chart.image_description}]({public_url})")
#                             except Exception as e:
#                                 output_parts.append(f"\nError uploading chart: {str(e)}")
#                     elif result['error']:
#                         output_parts.append("```python\n" + f"Error generating {chart.image_description}: {result['error']['message']}" + "\n```")
        
#         return "\n".join(output_parts)