-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
216 lines (179 loc) · 7.49 KB
/
Copy pathcli.py
File metadata and controls
216 lines (179 loc) · 7.49 KB
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
#!/usr/bin/env python3
import json
import os
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from core.database import AnalystDB
from core.models import DataSource, Session, Query
from core.loader import load_data, infer_schema, get_preview
from core.executor import analyze
def cmd_load(args):
db = AnalystDB()
df, meta = load_data(
path=Path(args.file) if args.file else None,
source_type=args.type,
raw_text=args.text or "",
table_name=args.table or "",
)
schema = infer_schema(df)
preview = get_preview(df, 5)
src = DataSource(
name=meta.get("filename", args.file or "pasted"),
source_type=meta["source_type"],
filename=meta.get("filename", ""),
table_name=meta.get("table", ""),
row_count=schema["row_count"],
column_count=schema["column_count"],
size_bytes=int(schema.get("memory_bytes", 0)),
schema_json=json.dumps(schema),
preview_json=json.dumps(preview),
)
src_id = db.add_source(src)
print(f" Source ID: {src_id}")
print(f" {schema['row_count']} rows x {schema['column_count']} columns")
print(f" Columns: {', '.join(c['name'] for c in schema['columns'])}")
db.close()
def cmd_ask(args):
api_key = args.api_key or os.getenv("GROQ_API_KEY", "")
if not api_key:
print(" Error: GROQ_API_KEY not set")
return
db = AnalystDB()
src = db.get_source(args.source)
if not src:
print(f" Source {args.source} not found")
return
# Rebuild DataFrame from preview (for small analysis) or from file
schema = json.loads(src["schema_json"])
df, _ = load_data(
path=Path(src["filename"]) if src["filename"] and Path(src["filename"]).exists() else None,
source_type=src["source_type"],
)
# Create/get session
ses = Session(source_id=args.source, title=args.question[:100])
ses_id = db.add_session(ses)
# Get conversation history
history = []
if args.session:
for q in db.get_queries(args.session):
history.append({"question": q["question"], "code": q["code"]})
elif args.continuous:
existing = db.get_queries(db.get_sessions(args.source)[0]["id"] if db.get_sessions(args.source) else 0)
for q in existing:
history.append({"question": q["question"], "code": q["code"]})
print(f" Analyzing: {args.question}")
result = analyze(args.question, df, schema, api_key, history if history else None)
query = Query(
session_id=ses_id,
question=args.question,
code=result.get("code", ""),
result_text=result.get("result_text", ""),
error=result.get("error", ""),
chart_b64=result.get("chart_b64", ""),
execution_time_ms=result.get("execution_time_ms", 0),
tokens_used=result.get("tokens_used", 0),
)
db.add_query(query)
db.close()
if result.get("error"):
print(f" Error: {result['error'][:200]}")
if result.get("result_text"):
print(f"\n{result['result_text']}\n")
if result.get("chart_b64"):
print(f" [Chart generated: {len(result['chart_b64'])} bytes base64]")
print(f" [{result.get('execution_time_ms', 0)}ms, {result.get('tokens_used', 0)} tokens, {result.get('retries', 0)} retries]")
def cmd_list(args):
db = AnalystDB()
if args.type == "sources":
for r in db.get_sources():
print(f" [{r['id']}] {r['name'][:40]:40s} | {r['source_type']:8s} | {r['row_count']}r x {r['column_count']}c | {r['created_at'][:16]}")
elif args.type == "sessions":
for r in db.get_sessions():
print(f" [{r['id']}] src#{r['source_id']} | {r['title'][:50]:50s} | {r['query_count']}q | {r['created_at'][:16]}")
db.close()
def cmd_interactive(args):
import readline
api_key = args.api_key or os.getenv("GROQ_API_KEY", "")
if not api_key:
print(" Error: GROQ_API_KEY not set")
return
db = AnalystDB()
src = db.get_source(args.source)
if not src:
print(f" Source {args.source} not found")
return
schema = json.loads(src["schema_json"])
df, _ = load_data(
path=Path(src["filename"]) if src["filename"] and Path(src["filename"]).exists() else None,
source_type=src["source_type"],
)
ses = Session(source_id=args.source, title="Interactive session")
ses_id = db.add_session(ses)
history = []
print(f" Data: {schema['row_count']} rows x {schema['column_count']} columns")
print(f" Columns: {', '.join(c['name'] for c in schema['columns'])}")
print(" Type 'exit' to quit, 'schema' to see schema\n")
while True:
try:
q = input(" >>> ").strip()
except (EOFError, KeyboardInterrupt):
print()
break
if not q:
continue
if q.lower() in ("exit", "quit", "q"):
break
if q.lower() == "schema":
for c in schema["columns"]:
print(f" {c['name']:25s} {c['dtype']:12s} {c['non_null']} non-null, {c.get('unique','?')} unique")
continue
result = analyze(q, df, schema, api_key, history)
q_obj = Query(session_id=ses_id, question=q, code=result.get("code",""),
result_text=result.get("result_text",""), error=result.get("error",""),
chart_b64=result.get("chart_b64",""),
execution_time_ms=result.get("execution_time_ms",0),
tokens_used=result.get("tokens_used",0))
db.add_query(q_obj)
history.append({"question": q, "code": result.get("code","")})
if result.get("error"):
print(f" Error: {result['error'][:200]}")
if result.get("result_text"):
print(f"\n{result['result_text']}")
if result.get("chart_b64"):
print(f" [Chart: {len(result['chart_b64'])} bytes]")
print(f" [{result.get('execution_time_ms',0)}ms]")
db.close()
def main():
import argparse
parser = argparse.ArgumentParser(prog="analyst", description="AI Data Analyst - Chat with your data")
sub = parser.add_subparsers(dest="command")
p_load = sub.add_parser("load", help="Load a data source")
p_load.add_argument("--file", help="File path")
p_load.add_argument("--type", default="csv", choices=["csv", "excel", "json", "sqlite"])
p_load.add_argument("--text", help="Raw CSV/JSON text")
p_load.add_argument("--table", help="Table name for SQLite")
p_ask = sub.add_parser("ask", help="Ask a question about loaded data")
p_ask.add_argument("source", type=int, help="Source ID")
p_ask.add_argument("question", help="Your question")
p_ask.add_argument("--session", type=int, help="Session ID for context")
p_ask.add_argument("--continuous", action="store_true", help="Continue last session")
p_ask.add_argument("--api-key", help="Groq API key")
p_interactive = sub.add_parser("chat", help="Interactive chat mode")
p_interactive.add_argument("source", type=int, help="Source ID")
p_interactive.add_argument("--api-key", help="Groq API key")
p_list = sub.add_parser("list", help="List sources or sessions")
p_list.add_argument("type", choices=["sources", "sessions"])
args = parser.parse_args()
if not args.command:
parser.print_help()
return
cmds = {
"load": cmd_load,
"ask": cmd_ask,
"chat": cmd_interactive,
"list": cmd_list,
}
cmds[args.command](args)
if __name__ == "__main__":
main()