Skip to content

Commit c9886e3

Browse files
committed
format
1 parent 8fa7eb3 commit c9886e3

File tree

3 files changed

+138
-57
lines changed

3 files changed

+138
-57
lines changed

examples/docker/chat-with-csv-solara/app.py

Lines changed: 129 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99

1010
from sql import inspect
1111
from sql.run import run
12-
from sql.connection import ConnectionManager
12+
from sqlalchemy import create_engine
13+
from sql.connection import SQLAlchemyConnection
1314
from sql.magic import SqlMagic, load_ipython_extension
1415
from IPython.core.interactiveshell import InteractiveShell
1516
from sql.plot import boxplot, histogram
@@ -18,6 +19,7 @@
1819
from chat import *
1920

2021
from matplotlib import pyplot as plt
22+
2123
plt.switch_backend("agg")
2224

2325
css = """
@@ -51,34 +53,30 @@
5153

5254

5355
def gen_name():
54-
return str(uuid.uuid4())[:8] + '.csv'
56+
return str(uuid.uuid4())[:8] + ".csv"
5557

5658

5759
def load_data(name):
5860
run.run_statements(conn, "drop table if exists my_data", sqlmagic)
59-
run.run_statements(conn, f"create table my_data as (select * from '{name}')", sqlmagic)
61+
run.run_statements(
62+
conn, f"create table my_data as (select * from '{name}')", sqlmagic
63+
)
6064
cols = inspect.get_columns("my_data")
6165
return cols
6266

6367

6468
def delete_data():
6569
run.run_statements(conn, "drop table if exists my_data", sqlmagic)
6670

71+
6772
ip = InteractiveShell()
6873

6974
sqlmagic = SqlMagic(shell=ip)
7075
sqlmagic.feedback = 1
7176
sqlmagic.autopandas = True
7277
load_ipython_extension(ip)
7378

74-
conn = ConnectionManager.set(
75-
"duckdb://",
76-
displaycon=True,
77-
connect_args={},
78-
creator=None,
79-
alias=None,
80-
config=sqlmagic,
81-
)
79+
conn = SQLAlchemyConnection(create_engine("duckdb://"), config=sqlmagic)
8280

8381

8482
class State:
@@ -95,7 +93,9 @@ def load_sample():
9593
State.reset()
9694
name = gen_name()
9795
State.loading_data.value = True
98-
url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv"
96+
url = (
97+
"https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv"
98+
)
9999
response = requests.get(url)
100100
if response.status_code == 200:
101101
with open(name, "wb") as f:
@@ -118,7 +118,7 @@ def load_from_file(file):
118118
try:
119119
df = pd.read_csv(file["file_obj"])
120120
df.columns = df.columns.str.strip()
121-
df.columns = df.columns.str.replace(' ', '_')
121+
df.columns = df.columns.str.replace(" ", "_")
122122
df.to_csv(name, index=False)
123123
cols = load_data(name)
124124
State.upload_data.value = True
@@ -145,33 +145,38 @@ def chat_with_gpt3(prompts):
145145
{"role": "system", "content": State.initial_prompt.value},
146146
{"role": "user", "content": "Show me the first 5 rows"},
147147
{"role": "assistant", "content": "SELECT * FROM my_data LIMIT 5"},
148-
] + [{"role": prompt.role, "content": prompt.content} for prompt in prompts],
148+
]
149+
+ [{"role": prompt.role, "content": prompt.content} for prompt in prompts],
149150
temperature=0.1,
150-
stream=True
151+
stream=True,
151152
)
152153

153154
total = ""
154155
for chunk in response:
155-
part = chunk['choices'][0]['delta'].get("content", "")
156+
part = chunk["choices"][0]["delta"].get("content", "")
156157
total += part
157158
yield total
158159

159160

160161
@solara.component
161162
def Chat() -> None:
162-
solara.Style("""
163+
solara.Style(
164+
"""
163165
.chat-input {
164166
max-width: 800px;
165167
})
166-
""")
167-
168-
messages, set_messages = solara.use_state([
169-
Message(
170-
role="assistant",
171-
content=f"Welcome. Please post your queries!",
172-
df=None,
173-
fig=None)
174-
]
168+
"""
169+
)
170+
171+
messages, set_messages = solara.use_state(
172+
[
173+
Message(
174+
role="assistant",
175+
content=f"Welcome. Please post your queries!",
176+
df=None,
177+
fig=None,
178+
)
179+
]
175180
)
176181
input, set_input = solara.use_state("")
177182

@@ -184,46 +189,91 @@ def ask_chatgpt():
184189
set_messages(_messages)
185190
if State.initial_prompt.value:
186191
final = None
187-
for command in State.chat_with_gpt3([Message(role="user", content=user_input, df=None, fig=None)]):
192+
for command in State.chat_with_gpt3(
193+
[Message(role="user", content=user_input, df=None, fig=None)]
194+
):
188195
final = command
189196

190197
if final.startswith("%sqlplot"):
191198
try:
192199
_, name, column = final.split(" ")
193200
except Exception as e:
194-
error_message = "Sorry, we couldn't run your query on the data. " \
195-
"Please ensure you specify a relevant column."
196-
set_messages(_messages + [Message(role="assistant", content=error_message, df=None, fig=None)])
201+
error_message = (
202+
"Sorry, we couldn't run your query on the data. "
203+
"Please ensure you specify a relevant column."
204+
)
205+
set_messages(
206+
_messages
207+
+ [
208+
Message(
209+
role="assistant",
210+
content=error_message,
211+
df=None,
212+
fig=None,
213+
)
214+
]
215+
)
197216
return
198217

199218
fig = Figure()
200219
ax = fig.subplots()
201220

202-
fn_map = {"histogram": partial(histogram, bins=50),
203-
"boxplot": boxplot}
221+
fn_map = {"histogram": partial(histogram, bins=50), "boxplot": boxplot}
204222

205223
fn = fn_map[name]
206224
try:
207225
ax = fn("my_data", column, ax=ax)
208-
set_messages(_messages + [Message(role="assistant", content="", df=None, fig=fig)])
226+
set_messages(
227+
_messages
228+
+ [Message(role="assistant", content="", df=None, fig=fig)]
229+
)
209230
except Exception as e:
210-
set_messages(_messages + [
211-
Message(role="assistant", content="Please pass relevant columns", df=None, fig=None)])
231+
set_messages(
232+
_messages
233+
+ [
234+
Message(
235+
role="assistant",
236+
content="Please pass relevant columns",
237+
df=None,
238+
fig=None,
239+
)
240+
]
241+
)
212242
else:
213243
error = "Sorry, we couldn't run your query on the data"
214244
try:
215245
query_result = run.run_statements(conn, final, sqlmagic)
216-
set_messages(_messages + [Message(role="assistant", content="", df=query_result, fig=None)])
246+
set_messages(
247+
_messages
248+
+ [
249+
Message(
250+
role="assistant", content="", df=query_result, fig=None
251+
)
252+
]
253+
)
217254
except ProgrammingError as e:
218-
set_messages(_messages + [
219-
Message(role="assistant", content=error, df=None, fig=None)])
255+
set_messages(
256+
_messages
257+
+ [Message(role="assistant", content=error, df=None, fig=None)]
258+
)
220259
except Exception as e:
221-
set_messages(_messages + [
222-
Message(role="assistant", content=error, df=None, fig=None)])
260+
set_messages(
261+
_messages
262+
+ [Message(role="assistant", content=error, df=None, fig=None)]
263+
)
223264

224265
else:
225-
set_messages(_messages + [Message(role="assistant",
226-
content="Please load some data first!", df=None, fig=None)])
266+
set_messages(
267+
_messages
268+
+ [
269+
Message(
270+
role="assistant",
271+
content="Please load some data first!",
272+
df=None,
273+
fig=None,
274+
)
275+
]
276+
)
227277

228278
with solara.VBox():
229279
for message in messages:
@@ -249,40 +299,64 @@ def Page():
249299
solara.Text("Data Querying and Visualisation App")
250300

251301
with solara.Card(title="About", elevation=6, style="background-color: #f5f5f5;"):
252-
solara.Markdown("""
302+
solara.Markdown(
303+
"""
253304
Interact with your data using natural language.
254305
255306
Examples: <br>
256307
- show me the unique values of column {column name} <br>
257308
- create a histogram of {column name} <br>
258-
- create a boxplot of {column name}""")
309+
- create a boxplot of {column name}"""
310+
)
259311

260312
with solara.Sidebar():
261313
with solara.Card("Controls", margin=0, elevation=0):
262314
with solara.Column():
263315
with solara.Row():
264-
solara.Button("Sample dataset", color="primary", text=True, outlined=True,
265-
on_click=State.load_sample)
266-
solara.Button("Clear dataset", color="primary", text=True, outlined=True, on_click=State.reset)
267-
FileDrop(on_file=State.load_from_file, on_total_progress=lambda *args: None,
268-
label="Drag a .csv file here")
316+
solara.Button(
317+
"Sample dataset",
318+
color="primary",
319+
text=True,
320+
outlined=True,
321+
on_click=State.load_sample,
322+
)
323+
solara.Button(
324+
"Clear dataset",
325+
color="primary",
326+
text=True,
327+
outlined=True,
328+
on_click=State.reset,
329+
)
330+
FileDrop(
331+
on_file=State.load_from_file,
332+
on_total_progress=lambda *args: None,
333+
label="Drag a .csv file here",
334+
)
269335
if State.loading_data.value:
270336
with solara.Div():
271337
solara.Text("Loading csv...")
272338
solara.ProgressLinear(True)
273339
if initial_prompt:
274-
solara.InputInt("Number of preview rows", value=State.results, continuous_update=True)
340+
solara.InputInt(
341+
"Number of preview rows",
342+
value=State.results,
343+
continuous_update=True,
344+
)
275345

276346
solara.Markdown("Hosted in [Ploomber Cloud](https://ploomber.io/)")
277347

278348
if sample_data_loaded:
279349
solara.Info("Sample data is loaded")
280-
sql_output = run.run_statements(conn, f"select * from my_data limit {results}", sqlmagic)
350+
sql_output = run.run_statements(
351+
conn, f"select * from my_data limit {results}", sqlmagic
352+
)
281353
solara.DataFrame(sql_output, items_per_page=10)
282354

283355
if upload_data:
284356
solara.Info("Data is successfully uploaded")
285-
sql_output = run.run_statements(conn, f"select * from my_data limit {results}", sqlmagic)
357+
sql_output = run.run_statements(
358+
conn, f"select * from my_data limit {results}", sqlmagic
359+
)
286360
solara.DataFrame(sql_output, items_per_page=10)
287361

288362
if upload_data_error:
@@ -293,7 +367,9 @@ def Page():
293367

294368
solara.Style(css)
295369
with solara.VBox(classes=["main"]):
296-
solara.HTML(tag="h3", style="margin: auto;", unsafe_innerHTML="Chat with your data")
370+
solara.HTML(
371+
tag="h3", style="margin: auto;", unsafe_innerHTML="Chat with your data"
372+
)
297373

298374
Chat()
299375

@@ -302,4 +378,3 @@ def Page():
302378
def Layout(children):
303379
route, routes = solara.use_route()
304380
return solara.AppLayout(children=children)
305-
109 Bytes
Binary file not shown.

examples/docker/chat-with-csv-solara/chat.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,19 +62,25 @@ def ChatBox(message: Message) -> None:
6262
with sl.Card():
6363
sl.DataFrame(message.df)
6464
with sl.Card():
65-
sl.FileDownload(message.df.to_csv(index=False), filename="data.csv", label="Download file")
65+
sl.FileDownload(
66+
message.df.to_csv(index=False),
67+
filename="data.csv",
68+
label="Download file",
69+
)
6670
elif message.fig is not None:
6771
with sl.Card():
6872
sl.FigureMatplotlib(message.fig)
6973
with sl.Card():
7074
buf = io.BytesIO()
7175
message.fig.savefig(buf, format="jpg")
7276
fp = tempfile.NamedTemporaryFile()
73-
with open(f"{fp.name}.jpg", 'wb') as ff:
77+
with open(f"{fp.name}.jpg", "wb") as ff:
7478
ff.write(buf.getvalue())
7579
buf.close()
7680
file_object = sl.use_memo(lambda: open(f"{fp.name}.jpg", "rb"), [])
77-
sl.FileDownload(file_object, mime_type="image/jpeg", close_file=False)
81+
sl.FileDownload(
82+
file_object, mime_type="image/jpeg", close_file=False
83+
)
7884

7985
# Image reference: https://www.flaticon.com/free-icons/bot;
8086
# https://www.flaticon.com/free-icons/use

0 commit comments

Comments
 (0)