Chamin09 commited on
Commit
66777c5
·
verified ·
1 Parent(s): 78601ed

Create export.py

Browse files
Files changed (1) hide show
  1. tools/export.py +155 -0
tools/export.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any, Optional, Union
2
+ import pandas as pd
3
+ import smtplib
4
+ from email.mime.multipart import MIMEMultipart
5
+ from email.mime.text import MIMEText
6
+ from email.mime.image import MIMEImage
7
+ import base64
8
+ import io
9
+ from pathlib import Path
10
+ import json
11
+ import datetime
12
+
13
+ class ExportTools:
14
+ """Tools for exporting data, generating reports, and sending emails."""
15
+
16
+ def __init__(self, output_directory: str = "./exports"):
17
+ """Initialize with directory for saved exports."""
18
+ self.output_directory = Path(output_directory)
19
+ self.output_directory.mkdir(exist_ok=True, parents=True)
20
+
21
+ def get_tools(self) -> List[Dict[str, Any]]:
22
+ """Get all available export tools."""
23
+ tools = [
24
+ {
25
+ "name": "generate_report",
26
+ "description": "Generate a report from conversation and results",
27
+ "function": self.generate_report
28
+ },
29
+ {
30
+ "name": "save_results_to_csv",
31
+ "description": "Save query results to a CSV file",
32
+ "function": self.save_results_to_csv
33
+ },
34
+ {
35
+ "name": "send_email",
36
+ "description": "Send results via email",
37
+ "function": self.send_email
38
+ }
39
+ ]
40
+ return tools
41
+
42
+ def generate_report(self, title: str, content: str,
43
+ images: List[str] = None) -> Dict[str, Any]:
44
+ """Generate HTML report from content and images."""
45
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
46
+ filename = f"{title.replace(' ', '_')}_{timestamp}.html"
47
+ file_path = self.output_directory / filename
48
+
49
+ # Basic HTML template
50
+ html = f"""
51
+ <!DOCTYPE html>
52
+ <html>
53
+ <head>
54
+ <title>{title}</title>
55
+ <style>
56
+ body {{ font-family: Arial, sans-serif; margin: 40px; line-height: 1.6; }}
57
+ h1 {{ color: #333366; }}
58
+ .report-container {{ max-width: 800px; margin: 0 auto; }}
59
+ .timestamp {{ color: #666; font-size: 0.8em; }}
60
+ img {{ max-width: 100%; height: auto; margin: 20px 0; }}
61
+ </style>
62
+ </head>
63
+ <body>
64
+ <div class="report-container">
65
+ <h1>{title}</h1>
66
+ <div class="timestamp">Generated on: {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}</div>
67
+ <div class="content">
68
+ {content.replace(chr(10), '<br>')}
69
+ </div>
70
+ """
71
+
72
+ # Add images if provided
73
+ if images and len(images) > 0:
74
+ html += "<div class='images'>"
75
+ for i, img_base64 in enumerate(images):
76
+ html += f"<img src='data:image/png;base64,{img_base64}' alt='Figure {i+1}'>"
77
+ html += "</div>"
78
+
79
+ html += """
80
+ </div>
81
+ </body>
82
+ </html>
83
+ """
84
+
85
+ # Write to file
86
+ with open(file_path, "w", encoding="utf-8") as f:
87
+ f.write(html)
88
+
89
+ return {
90
+ "success": True,
91
+ "report_path": str(file_path),
92
+ "title": title,
93
+ "timestamp": timestamp
94
+ }
95
+
96
+ def save_results_to_csv(self, data: List[Dict[str, Any]],
97
+ filename: str = None) -> Dict[str, Any]:
98
+ """Save query results to a CSV file."""
99
+ if not data or len(data) == 0:
100
+ return {"success": False, "error": "No data provided"}
101
+
102
+ # Create DataFrame from data
103
+ df = pd.DataFrame(data)
104
+
105
+ # Generate filename if not provided
106
+ if not filename:
107
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
108
+ filename = f"query_results_{timestamp}.csv"
109
+
110
+ # Ensure filename has .csv extension
111
+ if not filename.lower().endswith('.csv'):
112
+ filename += '.csv'
113
+
114
+ file_path = self.output_directory / filename
115
+
116
+ # Save to CSV
117
+ df.to_csv(file_path, index=False)
118
+
119
+ return {
120
+ "success": True,
121
+ "file_path": str(file_path),
122
+ "row_count": len(df),
123
+ "column_count": len(df.columns)
124
+ }
125
+
126
+ def send_email(self, to_email: str, subject: str, body: str,
127
+ from_email: str = None, smtp_server: str = None,
128
+ smtp_port: int = 587, username: str = None,
129
+ password: str = None, images: List[str] = None) -> Dict[str, Any]:
130
+ """
131
+ Send email with results.
132
+ Note: In production, credentials should be securely managed.
133
+ For demo purposes, this will log the email content instead.
134
+ """
135
+ # For safety in a demo app, don't actually send emails
136
+ # Just log what would be sent and return success
137
+
138
+ email_content = {
139
+ "to": to_email,
140
+ "subject": subject,
141
+ "body": body[:100] + "..." if len(body) > 100 else body,
142
+ "images": f"{len(images) if images else 0} images would be attached",
143
+ "note": "Email sending is simulated for demo purposes"
144
+ }
145
+
146
+ # Log the email content
147
+ print(f"SIMULATED EMAIL: {json.dumps(email_content, indent=2)}")
148
+
149
+ return {
150
+ "success": True,
151
+ "to": to_email,
152
+ "subject": subject,
153
+ "simulated": True,
154
+ "timestamp": datetime.datetime.now().isoformat()
155
+ }