-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
845 lines (742 loc) · 31.3 KB
/
Copy pathapp.py
File metadata and controls
845 lines (742 loc) · 31.3 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
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
from __future__ import annotations
import csv
import io
import json
import logging
import os
import re
import sys
import threading
import uuid
import webbrowser
from datetime import datetime
from pathlib import Path
from typing import Any
RESOURCE_DIR = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent))
APP_DIR = Path(sys.executable).resolve().parent if getattr(sys, "frozen", False) else Path(__file__).resolve().parent
os.environ.setdefault("MPLCONFIGDIR", str(APP_DIR / ".matplotlib"))
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import FancyBboxPatch
from flask import (
Flask,
Response,
flash,
redirect,
render_template,
request,
send_from_directory,
url_for,
)
from werkzeug.utils import secure_filename
DATA_DIR = APP_DIR / "data" / "charts"
UPLOAD_DIR = APP_DIR / "uploads"
GENERATED_DIR = APP_DIR / "static" / "generated"
ALLOWED_UPLOADS = {".csv", ".txt", ".tsv", ".xlsx"}
CHART_TYPES = {
"line": "Line",
"bar": "Bar",
"scatter": "Scatter",
"pie": "Pie",
"histogram": "Histogram",
"area": "Area",
}
DEFAULT_COLORS = ["#2563eb", "#0f9f8f", "#f59e0b", "#ef4444", "#7c3aed", "#14b8a6", "#f97316", "#64748b"]
app = Flask(
__name__,
template_folder=str(RESOURCE_DIR / "templates"),
static_folder=str(RESOURCE_DIR / "static"),
)
app.config["SECRET_KEY"] = "plotty-dev-secret-change-me"
app.config["MAX_CONTENT_LENGTH"] = 8 * 1024 * 1024
logging.getLogger("werkzeug").setLevel(logging.WARNING)
for directory in (DATA_DIR, UPLOAD_DIR, GENERATED_DIR):
directory.mkdir(parents=True, exist_ok=True)
def ensure_runtime_dirs() -> None:
for directory in (DATA_DIR, UPLOAD_DIR, GENERATED_DIR):
directory.mkdir(parents=True, exist_ok=True)
def slugify(value: str) -> str:
value = re.sub(r"[^a-zA-Z0-9]+", "-", value.strip().lower()).strip("-")
return value or "untitled-chart"
def parse_number(value: Any) -> float | None:
if value is None:
return None
cleaned = str(value).strip().replace(",", "")
if cleaned == "":
return None
cleaned = cleaned.replace("$", "").replace("£", "").replace("€", "")
cleaned = cleaned.replace("%", "")
if cleaned.startswith("(") and cleaned.endswith(")"):
cleaned = f"-{cleaned[1:-1]}"
try:
return float(cleaned)
except ValueError:
return None
def apply_casing(value: str, casing: str) -> str:
value = str(value).strip()
if casing == "title":
return value.title()
if casing == "upper":
return value.upper()
if casing == "lower":
return value.lower()
return value
def clean_color(value: str, fallback: str) -> str:
value = str(value).strip()
if re.fullmatch(r"#[0-9a-fA-F]{6}", value):
return value
return fallback
def parse_delimited_text(text: str, delimiter: str | None = None) -> list[list[str]]:
text = text.strip()
if not text:
return []
sample = text[:2048]
if delimiter is None:
try:
dialect = csv.Sniffer().sniff(sample, delimiters=",\t;|")
delimiter = dialect.delimiter
except csv.Error:
delimiter = ","
reader = csv.reader(io.StringIO(text), delimiter=delimiter)
return [[cell.strip() for cell in row] for row in reader if any(cell.strip() for cell in row)]
def read_upload(file_storage) -> tuple[list[list[str]], str]:
ensure_runtime_dirs()
filename = secure_filename(file_storage.filename or "")
suffix = Path(filename).suffix.lower()
if suffix not in ALLOWED_UPLOADS:
raise ValueError("Upload a CSV, TSV, TXT, or XLSX file.")
saved_name = f"{uuid.uuid4().hex}-{filename}"
saved_path = UPLOAD_DIR / saved_name
file_storage.save(saved_path)
if suffix == ".xlsx":
try:
from openpyxl import load_workbook
except ImportError as exc:
raise ValueError("Excel upload needs openpyxl. Run: pip install -r requirements.txt") from exc
workbook = load_workbook(saved_path, data_only=True)
sheet = workbook.active
rows = [
["" if cell is None else str(cell).strip() for cell in row]
for row in sheet.iter_rows(values_only=True)
]
return [row for row in rows if any(row)], filename
text = saved_path.read_text(encoding="utf-8-sig")
delimiter = "\t" if suffix == ".tsv" else None
return parse_delimited_text(text, delimiter), filename
def normalize_table(rows: list[list[str]], casing: str = "preserve") -> dict[str, Any]:
if not rows:
raise ValueError("Add at least one row of data.")
width = max(len(row) for row in rows)
padded = [row + [""] * (width - len(row)) for row in rows]
first_row_numbers = sum(parse_number(cell) is not None for cell in padded[0])
has_header = first_row_numbers < max(1, len(padded[0]) // 2)
headers = padded[0] if has_header else [f"Column {index + 1}" for index in range(width)]
headers = [apply_casing(header, casing) for header in headers]
body = padded[1:] if has_header else padded
if not body:
raise ValueError("Add at least one data row below the headers.")
body = [[apply_casing(cell, casing) if index == 0 else str(cell).strip() for index, cell in enumerate(row)] for row in body]
labels = [apply_casing(row[0] if row[0] else str(index + 1), casing) for index, row in enumerate(body)]
numeric_columns: list[dict[str, Any]] = []
for column_index in range(1 if width > 1 else 0, width):
values = [parse_number(row[column_index]) for row in body]
if any(value is not None for value in values):
numeric_columns.append(
{
"name": headers[column_index] or f"Series {column_index}",
"values": [0 if value is None else value for value in values],
}
)
if not numeric_columns and width == 1:
values = [parse_number(row[0]) for row in body]
if any(value is not None for value in values):
numeric_columns.append({"name": headers[0] or "Values", "values": [0 if value is None else value for value in values]})
labels = [str(index + 1) for index in range(len(body))]
if not numeric_columns:
raise ValueError("Plotty needs at least one numeric column to build a chart.")
return {"headers": headers, "rows": body, "labels": labels, "series": numeric_columns}
def rows_from_request() -> list[list[str]]:
table_json = request.form.get("table_json", "").strip()
if table_json:
try:
rows = json.loads(table_json)
except json.JSONDecodeError as exc:
raise ValueError("The editable table could not be read.") from exc
if not isinstance(rows, list):
raise ValueError("The editable table is not valid.")
return [[str(cell).strip() for cell in row] for row in rows if isinstance(row, list) and any(str(cell).strip() for cell in row)]
return parse_delimited_text(request.form.get("data_text", ""))
def rows_from_request_or(default_rows: list[list[str]]) -> list[list[str]]:
try:
return rows_from_request()
except ValueError:
return default_rows
def project_options(existing: dict[str, Any] | None = None) -> dict[str, Any]:
chart_type = request.form.get("chart_type", "line")
legend = request.form.get("legend", "auto")
if legend not in {"auto", "show", "hide"}:
legend = "auto"
legend_position = request.form.get("legend_position", "best")
if legend_position not in {"best", "upper right", "upper left", "lower right", "lower left"}:
legend_position = "best"
y_format = request.form.get("y_format", "general")
if y_format not in {"general", "currency", "percent"}:
y_format = "general"
casing = request.form.get("casing", "preserve")
if casing not in {"preserve", "title", "upper", "lower"}:
casing = "preserve"
try:
series_colors = json.loads(request.form.get("series_colors_json", "[]"))
except json.JSONDecodeError:
series_colors = []
if not isinstance(series_colors, list):
series_colors = []
series_colors = [
clean_color(color, DEFAULT_COLORS[index % len(DEFAULT_COLORS)])
for index, color in enumerate(series_colors)
]
try:
corner_radius = int(request.form.get("corner_radius", "8"))
except ValueError:
corner_radius = 8
corner_radius = max(0, min(corner_radius, 24))
show_x_axis = request.form.get("show_x_axis") == "on"
show_y_axis = request.form.get("show_y_axis") == "on"
rounded_corners = request.form.get("rounded_corners") == "on"
if chart_type == "pie":
show_x_axis = False
show_y_axis = False
y_format = "general"
if chart_type != "bar":
rounded_corners = False
corner_radius = 0
return {
"legend": legend,
"legend_position": legend_position,
"show_x_axis": show_x_axis,
"show_y_axis": show_y_axis,
"y_format": y_format,
"casing": casing,
"series_colors": series_colors,
"rounded_corners": rounded_corners,
"corner_radius": corner_radius,
"display_mode": "static",
"interactive": False,
}
def chart_page_style_options(project: dict[str, Any]) -> dict[str, Any]:
colors = []
for index, _series in enumerate(project["table"]["series"]):
colors.append(clean_color(request.form.get(f"series_color_{index}", ""), DEFAULT_COLORS[index % len(DEFAULT_COLORS)]))
return {
"series_colors": colors,
}
def project_colors(project: dict[str, Any], count: int) -> list[str]:
saved_colors = project.get("series_colors") or []
return [
clean_color(saved_colors[index], DEFAULT_COLORS[index % len(DEFAULT_COLORS)])
if index < len(saved_colors)
else DEFAULT_COLORS[index % len(DEFAULT_COLORS)]
for index in range(count)
]
def round_bar_patches(ax, radius: int) -> None:
if radius <= 0:
return
for patch in list(ax.patches):
x, y = patch.get_xy()
width = patch.get_width()
height = patch.get_height()
color = patch.get_facecolor()
patch.remove()
rounded = FancyBboxPatch(
(x, y),
width,
height,
boxstyle=f"round,pad=0,rounding_size={radius / 90}",
linewidth=0,
facecolor=color,
mutation_aspect=1,
)
ax.add_patch(rounded)
def render_chart(project: dict[str, Any]) -> str:
ensure_runtime_dirs()
chart_type = project["chart_type"]
table = project["table"]
labels = table["labels"]
series = table["series"]
title = project.get("title") or "Untitled chart"
x_label = project.get("x_label") or ""
y_label = project.get("y_label") or ""
show_x_axis = project.get("show_x_axis", True)
show_y_axis = project.get("show_y_axis", True)
legend = project.get("legend", "auto")
legend_position = project.get("legend_position", "best")
y_format = project.get("y_format", "general")
colors = project_colors(project, len(series))
rounded_corners = project.get("rounded_corners", False)
corner_radius = project.get("corner_radius", 8)
plt.style.use("seaborn-v0_8-whitegrid")
fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True)
if chart_type == "pie":
first = series[0]
ax.pie(first["values"], labels=labels, autopct="%1.1f%%", startangle=90, colors=colors)
ax.axis("equal")
elif chart_type == "histogram":
ax.hist(series[0]["values"], bins=min(12, max(3, len(labels))), color=colors[0], edgecolor="#ffffff")
elif chart_type == "scatter":
x_values = list(range(1, len(labels) + 1))
for index, item in enumerate(series):
ax.scatter(x_values, item["values"], label=item["name"], s=72, color=colors[index])
ax.set_xticks(x_values, labels, rotation=35, ha="right")
elif chart_type == "bar":
x_values = list(range(len(labels)))
width = 0.8 / max(1, len(series))
for index, item in enumerate(series):
offsets = [x + (index * width) - (width * (len(series) - 1) / 2) for x in x_values]
ax.bar(offsets, item["values"], width=width, label=item["name"], color=colors[index])
if rounded_corners:
round_bar_patches(ax, corner_radius)
ax.set_xticks(x_values, labels, rotation=35, ha="right")
elif chart_type == "area":
x_values = list(range(1, len(labels) + 1))
for index, item in enumerate(series):
ax.fill_between(x_values, item["values"], alpha=0.28, label=item["name"], color=colors[index])
ax.plot(x_values, item["values"], color=colors[index])
ax.set_xticks(x_values, labels, rotation=35, ha="right")
else:
x_values = list(range(1, len(labels) + 1))
for index, item in enumerate(series):
ax.plot(x_values, item["values"], marker="o", linewidth=2.5, label=item["name"], color=colors[index])
ax.set_xticks(x_values, labels, rotation=35, ha="right")
ax.set_title(title, fontsize=18, pad=16)
if chart_type != "pie":
ax.set_xlabel(x_label if show_x_axis else "")
ax.set_ylabel(y_label if show_y_axis else "")
if not show_x_axis:
ax.tick_params(axis="x", labelbottom=False, bottom=False)
ax.spines["bottom"].set_visible(False)
if not show_y_axis:
ax.tick_params(axis="y", labelleft=False, left=False)
ax.spines["left"].set_visible(False)
if y_format == "currency":
ax.yaxis.set_major_formatter("${x:,.0f}")
elif y_format == "percent":
ax.yaxis.set_major_formatter("{x:,.0f}%")
should_show_legend = legend == "show" or (legend == "auto" and len(series) > 1)
if should_show_legend:
ax.legend(loc=legend_position)
fig.patch.set_facecolor("#ffffff")
image_name = f"{project['id']}.png"
fig.savefig(GENERATED_DIR / image_name, dpi=150)
plt.close(fig)
return image_name
def interactive_spec(project: dict[str, Any]) -> dict[str, Any]:
chart_type = project["chart_type"]
table = project["table"]
labels = table["labels"]
series = table["series"]
colors = project_colors(project, len(series))
all_values = [value for item in series for value in item["values"]]
y_min = min(all_values) if all_values else 0
y_max = max(all_values) if all_values else 1
y_padding = max((y_max - y_min) * 0.12, 1)
y_bounds = [y_min - y_padding, y_max + y_padding]
x_positions = list(range(len(labels)))
x_bounds = [-0.5, max(len(labels) - 0.5, 0.5)]
traces = []
if chart_type == "pie":
traces.append({"type": "pie", "labels": labels, "values": series[0]["values"], "marker": {"colors": colors}})
elif chart_type == "histogram":
traces.append({"type": "histogram", "x": series[0]["values"], "name": series[0]["name"], "marker": {"color": colors[0]}})
else:
plotly_type = "bar" if chart_type == "bar" else "scatter"
mode = "markers" if chart_type == "scatter" else "lines+markers"
if chart_type == "area":
mode = "lines"
for index, item in enumerate(series):
trace = {
"type": plotly_type,
"x": x_positions,
"y": item["values"],
"name": item["name"],
"customdata": labels,
"marker": {"color": colors[index]},
"hoverinfo": "none",
}
if plotly_type == "scatter":
trace["mode"] = mode
if chart_type == "area":
trace["fill"] = "tozeroy"
trace["line"] = {"color": colors[index]}
traces.append(trace)
return {
"data": traces,
"layout": {
"title": project.get("title", "Untitled chart"),
"xaxis": {
"title": project.get("x_label", ""),
"visible": project.get("show_x_axis", True),
"tickmode": "array",
"tickvals": x_positions,
"ticktext": labels,
"range": x_bounds,
},
"yaxis": {"title": project.get("y_label", ""), "visible": project.get("show_y_axis", True), "range": y_bounds},
"showlegend": project.get("legend") != "hide",
"bargap": 0.2,
"margin": {"t": 64, "r": 24, "b": 64, "l": 64},
},
"bounds": {"x": x_bounds, "y": y_bounds},
}
def code_snippets(project: dict[str, Any]) -> dict[str, str]:
labels = project["table"]["labels"]
series = project["table"]["series"]
colors = project_colors(project, len(series))
spec = interactive_spec(project)
chart_type = project["chart_type"]
title = project.get("title", "Untitled chart")
x_label = project.get("x_label", "")
y_label = project.get("y_label", "")
matplotlib_lines = [
"import matplotlib.pyplot as plt",
f"labels = {labels!r}",
f"series = {[(item['name'], item['values']) for item in series]!r}",
f"colors = {colors!r}",
"fig, ax = plt.subplots(figsize=(10, 6))",
]
if chart_type == "pie":
matplotlib_lines += [
"name, values = series[0]",
"ax.pie(values, labels=labels, autopct='%1.1f%%', startangle=90, colors=colors)",
"ax.axis('equal')",
]
elif chart_type == "histogram":
matplotlib_lines += [
"name, values = series[0]",
"ax.hist(values, bins=min(12, max(3, len(values))), color=colors[0], edgecolor='white')",
]
elif chart_type == "bar":
matplotlib_lines += [
"x = range(len(labels))",
"width = 0.8 / max(1, len(series))",
"for index, (name, values) in enumerate(series):",
" offsets = [item + (index * width) - (width * (len(series) - 1) / 2) for item in x]",
" ax.bar(offsets, values, width=width, label=name, color=colors[index])",
"ax.set_xticks(list(x), labels, rotation=35, ha='right')",
]
elif chart_type == "scatter":
matplotlib_lines += [
"x = range(len(labels))",
"for index, (name, values) in enumerate(series):",
" ax.scatter(x, values, label=name, color=colors[index], s=72)",
"ax.set_xticks(list(x), labels, rotation=35, ha='right')",
]
elif chart_type == "area":
matplotlib_lines += [
"x = range(len(labels))",
"for index, (name, values) in enumerate(series):",
" ax.fill_between(x, values, alpha=0.28, label=name, color=colors[index])",
" ax.plot(x, values, color=colors[index])",
"ax.set_xticks(list(x), labels, rotation=35, ha='right')",
]
else:
matplotlib_lines += [
"x = range(len(labels))",
"for index, (name, values) in enumerate(series):",
" ax.plot(x, values, marker='o', linewidth=2.5, label=name, color=colors[index])",
"ax.set_xticks(list(x), labels, rotation=35, ha='right')",
]
matplotlib_lines.append(f"ax.set_title({title!r})")
if chart_type != "pie":
matplotlib_lines += [
f"ax.set_xlabel({x_label!r})",
f"ax.set_ylabel({y_label!r})",
"ax.legend()",
]
matplotlib_lines += ["fig.tight_layout()", "plt.show()"]
if chart_type == "histogram":
r_lines = [
"library(ggplot2)",
f"values <- c({', '.join(str(value) for value in series[0]['values'])})",
"df <- data.frame(value = values)",
"ggplot(df, aes(x = value)) +",
" geom_histogram(bins = min(12, max(3, length(values)))) +",
f" labs(title = {title!r}, x = {x_label!r}, y = {y_label!r})",
]
elif chart_type == "pie":
r_lines = [
"library(ggplot2)",
f"labels <- c({', '.join(repr(label) for label in labels)})",
f"values <- c({', '.join(str(value) for value in series[0]['values'])})",
"df <- data.frame(label = labels, value = values)",
"ggplot(df, aes(x = '', y = value, fill = label)) +",
" geom_col(width = 1) +",
" coord_polar(theta = 'y') +",
f" labs(title = {title!r})",
]
else:
if chart_type == "bar":
r_geom = "geom_col()"
elif chart_type == "scatter":
r_geom = "geom_point()"
elif chart_type == "area":
r_geom = "geom_area(alpha = 0.35)"
else:
r_geom = "geom_line() + geom_point()"
r_lines = [
"library(ggplot2)",
f"labels <- c({', '.join(repr(label) for label in labels)})",
f"values <- c({', '.join(str(value) for value in series[0]['values'])})",
"df <- data.frame(label = labels, value = values)",
"ggplot(df, aes(x = label, y = value, group = 1)) +",
f" {r_geom} +",
f" labs(title = {title!r}, x = {x_label!r}, y = {y_label!r})",
]
return {
"Python Matplotlib (static)": "\n".join(matplotlib_lines),
"Python Plotly (interactive)": "\n".join(
[
"import plotly.graph_objects as go",
f"fig = go.Figure({json.dumps(spec['data'])})",
f"fig.update_layout({json.dumps(spec['layout'])})",
"fig.show()",
]
),
"JavaScript Plotly (interactive)": "\n".join(
[
'<script src="https://cdn.plot.ly/plotly-2.35.2.min.js"></script>',
'<div id="chart"></div>',
"<script>",
f"Plotly.newPlot('chart', {json.dumps(spec['data'])}, {json.dumps(spec['layout'])}, {{responsive: true}});",
"</script>",
]
),
"R ggplot2 (static)": "\n".join(r_lines),
}
def chart_path(chart_id: str) -> Path:
return DATA_DIR / f"{chart_id}.json"
def save_project(project: dict[str, Any]) -> None:
ensure_runtime_dirs()
project["updated_at"] = datetime.now().isoformat(timespec="seconds")
chart_path(project["id"]).write_text(json.dumps(project, indent=2), encoding="utf-8")
def load_project(chart_id: str) -> dict[str, Any]:
path = chart_path(chart_id)
if not path.exists():
raise FileNotFoundError(chart_id)
return json.loads(path.read_text(encoding="utf-8"))
def list_projects() -> list[dict[str, Any]]:
projects = []
for path in sorted(DATA_DIR.glob("*.json"), key=lambda item: item.stat().st_mtime, reverse=True):
try:
project = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
continue
projects.append(project)
return projects
def rows_to_csv(rows: list[list[str]]) -> str:
output = io.StringIO()
writer = csv.writer(output)
writer.writerows(rows)
return output.getvalue()
def project_rows(project: dict[str, Any]) -> list[list[str]]:
return [project["table"]["headers"], *project["table"]["rows"]]
def template_rows() -> list[list[str]]:
return [
["Chart type", "Label", "Series A", "Series B", "Supported data"],
["Line", "January", "1200", "750", "numbers, currency, percentages"],
["Bar", "February", "$1,500", "$820", "grouped numeric series"],
["Scatter", "March", "1325", "790", "numeric y values with label/index x"],
["Pie", "April", "1800", "", "first numeric series"],
["Histogram", "May", "45%", "", "first numeric series"],
["Area", "June", "2100", "980", "one or more numeric series"],
]
@app.route("/")
def home():
return render_template("home.html", projects=list_projects(), chart_types=CHART_TYPES)
@app.route("/charts/new", methods=["GET", "POST"])
def new_chart():
sample_rows = [
["Month", "Sales", "Expenses"],
["January", "1200", "750"],
["February", "1500", "820"],
["March", "1325", "790"],
["April", "1800", "910"],
]
if request.method == "GET":
return render_template("editor.html", chart_types=CHART_TYPES, editor_rows=sample_rows, project=None)
title = request.form.get("title", "").strip() or "Untitled chart"
chart_type = request.form.get("chart_type", "line")
if chart_type not in CHART_TYPES:
chart_type = "line"
try:
uploaded = request.files.get("data_file")
if uploaded and uploaded.filename:
rows, source_name = read_upload(uploaded)
else:
rows = rows_from_request()
source_name = "Typed data"
options = project_options()
table = normalize_table(rows, options["casing"])
chart_id = f"{slugify(title)}-{uuid.uuid4().hex[:8]}"
project = {
"id": chart_id,
"title": title,
"chart_type": chart_type,
"x_label": request.form.get("x_label", "").strip(),
"y_label": request.form.get("y_label", "").strip(),
"source_name": source_name,
"table": table,
"created_at": datetime.now().isoformat(timespec="seconds"),
**options,
}
project["image_name"] = render_chart(project)
save_project(project)
flash("Chart created.", "success")
return redirect(url_for("view_chart", chart_id=chart_id))
except ValueError as error:
flash(str(error), "error")
return render_template("editor.html", chart_types=CHART_TYPES, editor_rows=rows_from_request_or(sample_rows), project=None)
@app.route("/charts/<chart_id>")
def view_chart(chart_id: str):
try:
project = load_project(chart_id)
except FileNotFoundError:
flash("That chart could not be found.", "error")
return redirect(url_for("home"))
return render_template(
"chart.html",
project=project,
chart_types=CHART_TYPES,
interactive_spec=interactive_spec(project),
code_snippets=code_snippets(project),
)
@app.route("/charts/<chart_id>/edit", methods=["GET", "POST"])
def edit_chart(chart_id: str):
try:
project = load_project(chart_id)
except FileNotFoundError:
flash("That chart could not be found.", "error")
return redirect(url_for("home"))
if request.method == "GET":
return render_template("editor.html", chart_types=CHART_TYPES, project=project, editor_rows=project_rows(project))
try:
uploaded = request.files.get("data_file")
if uploaded and uploaded.filename:
rows, source_name = read_upload(uploaded)
else:
rows = rows_from_request()
source_name = project.get("source_name", "Typed data")
options = project_options(project)
project.update(
{
"title": request.form.get("title", "").strip() or project["title"],
"chart_type": request.form.get("chart_type", project["chart_type"]),
"x_label": request.form.get("x_label", "").strip(),
"y_label": request.form.get("y_label", "").strip(),
"source_name": source_name,
"table": normalize_table(rows, options["casing"]),
**options,
}
)
project["image_name"] = render_chart(project)
save_project(project)
flash("Chart updated.", "success")
return redirect(url_for("view_chart", chart_id=chart_id))
except ValueError as error:
flash(str(error), "error")
return redirect(url_for("edit_chart", chart_id=chart_id))
@app.route("/charts/<chart_id>/style", methods=["POST"])
def update_chart_style(chart_id: str):
try:
project = load_project(chart_id)
except FileNotFoundError:
flash("That chart could not be found.", "error")
return redirect(url_for("home"))
project.update(chart_page_style_options(project))
project["image_name"] = render_chart(project)
save_project(project)
flash("Chart style updated.", "success")
return redirect(url_for("view_chart", chart_id=chart_id))
@app.route("/charts/<chart_id>/download")
def download_chart(chart_id: str):
project = load_project(chart_id)
return send_from_directory(GENERATED_DIR, project["image_name"], as_attachment=True, download_name=f"{slugify(project['title'])}.png")
@app.route("/charts/<chart_id>/data.<file_format>")
def download_chart_data(chart_id: str, file_format: str):
project = load_project(chart_id)
rows = project_rows(project)
filename = f"{slugify(project['title'])}-data"
if file_format == "csv":
return Response(
rows_to_csv(rows),
mimetype="text/csv",
headers={"Content-Disposition": f"attachment; filename={filename}.csv"},
)
if file_format == "xlsx":
try:
from openpyxl import Workbook
except ImportError:
flash("Excel download needs openpyxl. Run: pip install -r requirements.txt", "error")
return redirect(url_for("view_chart", chart_id=chart_id))
workbook = Workbook()
sheet = workbook.active
sheet.title = "Chart data"
for row in rows:
sheet.append(row)
output = io.BytesIO()
workbook.save(output)
output.seek(0)
return Response(
output.getvalue(),
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers={"Content-Disposition": f"attachment; filename={filename}.xlsx"},
)
flash("Choose CSV or XLSX.", "error")
return redirect(url_for("view_chart", chart_id=chart_id))
@app.route("/templates/chart-data.<file_format>")
def download_data_template(file_format: str):
rows = template_rows()
if file_format == "csv":
return Response(
rows_to_csv(rows),
mimetype="text/csv",
headers={"Content-Disposition": "attachment; filename=plotty-supported-chart-data.csv"},
)
if file_format == "xlsx":
try:
from openpyxl import Workbook
except ImportError:
flash("Excel template download needs openpyxl. Run: pip install -r requirements.txt", "error")
return redirect(url_for("new_chart"))
workbook = Workbook()
overview = workbook.active
overview.title = "Supported styles"
for row in rows:
overview.append(row)
for chart_type, label in CHART_TYPES.items():
sheet = workbook.create_sheet(label)
sheet.append(["Label", "Series A", "Series B"])
sheet.append(["January", 1200, 750])
sheet.append(["February", 1500, 820])
sheet.append(["March", 1325, 790])
output = io.BytesIO()
workbook.save(output)
output.seek(0)
return Response(
output.getvalue(),
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers={"Content-Disposition": "attachment; filename=plotty-supported-chart-data.xlsx"},
)
flash("Choose CSV or XLSX.", "error")
return redirect(url_for("new_chart"))
def open_browser(host: str, port: int) -> None:
if os.environ.get("PLOTTY_NO_BROWSER") == "1":
return
threading.Timer(1.0, lambda: webbrowser.open(f"http://{host}:{port}")).start()
def main() -> None:
host = os.environ.get("PLOTTY_HOST", "127.0.0.1")
port = int(os.environ.get("PLOTTY_PORT", "5000"))
open_browser(host, port)
app.run(host=host, port=port, debug=False)
if __name__ == "__main__":
main()