FajarHidaa commited on
Commit
d000093
·
verified ·
1 Parent(s): ba15a1d

Delete src/core/chart_builder.py

Browse files
Files changed (1) hide show
  1. src/core/chart_builder.py +0 -309
src/core/chart_builder.py DELETED
@@ -1,309 +0,0 @@
1
- """
2
- Human+ Chart Builder
3
- Plotly gauge charts dan bar charts untuk biomarker visualization.
4
- Semua chart dark-mode native, sesuai Human+ design system.
5
- """
6
-
7
- from typing import Optional
8
-
9
- # ── Color palette (matches ui/theme.py) ──────────────────────────────
10
- _COL = {
11
- "bg": "#070710",
12
- "surface": "#0d0d1a",
13
- "elevated": "#131325",
14
- "line": "#1f1f38",
15
- "text": "#f0f0fa",
16
- "muted": "#8b8ba7",
17
- "optimal": "#10b981",
18
- "warning": "#f59e0b",
19
- "danger": "#ef4444",
20
- "violet": "#8b5cf6",
21
- "cyan": "#22d3ee",
22
- }
23
-
24
- _STATUS_COLOR = {
25
- "optimal": _COL["optimal"],
26
- "warning": _COL["warning"],
27
- "danger": _COL["danger"],
28
- "neutral": _COL["muted"],
29
- }
30
-
31
-
32
- def build_gauge_chart(
33
- name: str,
34
- value: float,
35
- unit: str,
36
- status: str,
37
- range_lo: float,
38
- range_hi: float,
39
- optimal_lo: Optional[float] = None,
40
- optimal_hi: Optional[float] = None,
41
- height: int = 220,
42
- ):
43
- """
44
- Build a single Plotly gauge chart untuk satu biomarker.
45
-
46
- Args:
47
- name: biomarker name
48
- value: numeric value
49
- unit: unit string
50
- status: 'optimal'|'warning'|'danger'|'neutral'
51
- range_lo / range_hi: full display range for the gauge
52
- optimal_lo / optimal_hi: target optimal range (green zone)
53
- height: chart height in px
54
-
55
- Returns:
56
- plotly Figure object
57
- """
58
- import plotly.graph_objects as go
59
-
60
- color = _STATUS_COLOR.get(status, _COL["muted"])
61
-
62
- # Build green threshold steps
63
- steps = []
64
- if optimal_lo is not None and optimal_hi is not None:
65
- steps = [
66
- {"range": [range_lo, optimal_lo], "color": "rgba(239,68,68,0.12)"},
67
- {"range": [optimal_lo, optimal_hi], "color": "rgba(16,185,129,0.15)"},
68
- {"range": [optimal_hi, range_hi], "color": "rgba(245,158,11,0.12)"},
69
- ]
70
- elif optimal_hi is not None:
71
- steps = [
72
- {"range": [range_lo, optimal_hi], "color": "rgba(16,185,129,0.15)"},
73
- {"range": [optimal_hi, range_hi], "color": "rgba(245,158,11,0.12)"},
74
- ]
75
- elif optimal_lo is not None:
76
- steps = [
77
- {"range": [range_lo, optimal_lo], "color": "rgba(245,158,11,0.12)"},
78
- {"range": [optimal_lo, range_hi], "color": "rgba(16,185,129,0.15)"},
79
- ]
80
-
81
- fig = go.Figure(go.Indicator(
82
- mode="gauge+number",
83
- value=value,
84
- number={
85
- "suffix": f" {unit}",
86
- "font": {"size": 20, "color": color, "family": "DM Sans"},
87
- },
88
- title={
89
- "text": name,
90
- "font": {"size": 13, "color": _COL["muted"], "family": "DM Sans"},
91
- },
92
- gauge={
93
- "axis": {
94
- "range": [range_lo, range_hi],
95
- "tickcolor": _COL["line"],
96
- "tickfont": {"color": _COL["muted"], "size": 9, "family": "JetBrains Mono"},
97
- "nticks": 5,
98
- },
99
- "bar": {"color": color, "thickness": 0.22},
100
- "bgcolor": _COL["elevated"],
101
- "borderwidth": 0,
102
- "steps": steps,
103
- "threshold": {
104
- "line": {"color": color, "width": 2},
105
- "thickness": 0.75,
106
- "value": value,
107
- },
108
- },
109
- ))
110
-
111
- fig.update_layout(
112
- height=height,
113
- margin=dict(t=30, b=10, l=20, r=20),
114
- paper_bgcolor=_COL["surface"],
115
- plot_bgcolor=_COL["surface"],
116
- font={"family": "DM Sans", "color": _COL["text"]},
117
- )
118
-
119
- return fig
120
-
121
-
122
- def build_biomarker_bar_chart(biomarkers: list[dict], height: int = 380) -> "go.Figure":
123
- """
124
- Build horizontal bar chart untuk semua biomarker sekaligus.
125
- Setiap bar dicolor sesuai status (merah/kuning/hijau).
126
-
127
- Args:
128
- biomarkers: list of enriched biomarker dicts dari pdf_processor
129
- height: chart height px
130
-
131
- Returns:
132
- plotly Figure
133
- """
134
- import plotly.graph_objects as go
135
-
136
- # Filter yang punya numeric value
137
- plottable = [
138
- b for b in biomarkers
139
- if b.get("raw_value") is not None and b.get("status") != "neutral"
140
- ]
141
-
142
- if not plottable:
143
- return None
144
-
145
- # Sort: danger first
146
- priority = {"danger": 0, "warning": 1, "optimal": 2}
147
- plottable = sorted(plottable, key=lambda b: priority.get(b["status"], 3))
148
-
149
- names = [b["name"] for b in plottable]
150
- values = [b["raw_value"] for b in plottable]
151
- colors = [_STATUS_COLOR.get(b["status"], _COL["muted"]) for b in plottable]
152
- statuses = [b["status"].upper() for b in plottable]
153
- units = [b.get("unit", "") for b in plottable]
154
- refs = [b.get("reference", "") for b in plottable]
155
-
156
- def _fmt_ref(r, u):
157
- """Tampilkan reference dengan unit jika ada, fallback ke '-' jika kosong."""
158
- if not r:
159
- return "—"
160
- # Jika reference sudah mengandung unit atau tanda < >, langsung pakai
161
- if any(c in r for c in ["<", ">", "–", "-"]):
162
- return f"{r} {u}".strip()
163
- return f"{r} {u}".strip()
164
-
165
- hover_texts = [
166
- f"<b>{n}</b><br>"
167
- f"Nilai: <b>{v} {u}</b><br>"
168
- f"Human+ target: {_fmt_ref(r, u)}<br>"
169
- f"Status: <b>{s}</b>"
170
- for n, v, u, r, s in zip(names, values, units, refs, statuses)
171
- ]
172
-
173
- fig = go.Figure(go.Bar(
174
- x=values,
175
- y=names,
176
- orientation="h",
177
- marker=dict(
178
- color=colors,
179
- line=dict(width=0),
180
- opacity=0.85,
181
- ),
182
- hovertext=hover_texts,
183
- hoverinfo="text",
184
- hoverlabel=dict(
185
- bgcolor=_COL["elevated"],
186
- bordercolor=_COL["line"],
187
- font=dict(family="DM Sans", size=12, color=_COL["text"]),
188
- ),
189
- text=[f"{v} {u}" for v, u in zip(values, units)],
190
- textposition="outside",
191
- textfont=dict(
192
- family="JetBrains Mono",
193
- size=10,
194
- color=_COL["muted"],
195
- ),
196
- ))
197
-
198
- dynamic_height = max(height, len(plottable) * 36 + 80)
199
-
200
- fig.update_layout(
201
- height=dynamic_height,
202
- margin=dict(t=16, b=16, l=16, r=80),
203
- paper_bgcolor=_COL["bg"],
204
- plot_bgcolor=_COL["bg"],
205
- font={"family": "DM Sans", "color": _COL["text"]},
206
- xaxis=dict(
207
- showgrid=True,
208
- gridcolor=_COL["line"],
209
- gridwidth=1,
210
- tickfont=dict(family="JetBrains Mono", size=9, color=_COL["muted"]),
211
- zeroline=False,
212
- ),
213
- yaxis=dict(
214
- tickfont=dict(family="DM Sans", size=11, color=_COL["text"]),
215
- categoryorder="array",
216
- categoryarray=list(reversed(names)),
217
- ),
218
- hoverlabel=dict(align="left"),
219
- bargap=0.35,
220
- )
221
-
222
- return fig
223
-
224
-
225
- def build_status_donut(optimal: int, warning: int, danger: int) -> "go.Figure":
226
- """
227
- Build a small donut chart untuk summary biomarker status.
228
- Digunakan di sidebar atau summary card.
229
- """
230
- import plotly.graph_objects as go
231
-
232
- labels = ["Optimal", "Sub-Optimal", "Perlu Perhatian"]
233
- values = [optimal, warning, danger]
234
- colors = [_COL["optimal"], _COL["warning"], _COL["danger"]]
235
-
236
- # Filter zero values
237
- filtered = [(l, v, c) for l, v, c in zip(labels, values, colors) if v > 0]
238
- if not filtered:
239
- return None
240
-
241
- labels_f, values_f, colors_f = zip(*filtered)
242
-
243
- fig = go.Figure(go.Pie(
244
- labels=labels_f,
245
- values=values_f,
246
- hole=0.65,
247
- marker=dict(
248
- colors=colors_f,
249
- line=dict(color=_COL["bg"], width=2),
250
- ),
251
- textinfo="none",
252
- hovertemplate="<b>%{label}</b><br>%{value} marker<extra></extra>",
253
- hoverlabel=dict(
254
- bgcolor=_COL["elevated"],
255
- font=dict(family="DM Sans", size=12, color=_COL["text"]),
256
- ),
257
- ))
258
-
259
- total = sum(values_f)
260
- fig.update_layout(
261
- height=180,
262
- margin=dict(t=0, b=0, l=0, r=0),
263
- paper_bgcolor="rgba(0,0,0,0)",
264
- plot_bgcolor="rgba(0,0,0,0)",
265
- showlegend=False,
266
- annotations=[{
267
- "text": f"<b>{total}</b><br><span style='font-size:10px'>Marker</span>",
268
- "x": 0.5, "y": 0.5,
269
- "font_size": 18,
270
- "font_family": "DM Sans",
271
- "font_color": _COL["text"],
272
- "showarrow": False,
273
- }],
274
- )
275
-
276
- return fig
277
-
278
-
279
- # ── Gauge config presets (Human+ biomarker ranges) ───────────────────
280
- # Format: name_lower → (range_lo, range_hi, optimal_lo, optimal_hi)
281
- GAUGE_PRESETS: dict[str, tuple] = {
282
- "hs-crp": (0, 10, None, 1.0),
283
- "homocysteine": (0, 30, None, 8.0),
284
- "hba1c": (4.0, 8.0, 4.8, 5.2),
285
- "vitamin d": (0, 100, 50, 80),
286
- "testosterone": (0, 1200, 600, None),
287
- "magnesium": (1.0, 3.5, 2.2, None),
288
- "vitamin b12": (0, 1500, 500, None),
289
- "ferritin": (0, 300, 50, 150),
290
- "apob": (0, 150, None, 80),
291
- "triglycerides": (0, 300, None, 90),
292
- "hdl": (0, 120, 60, None),
293
- "tsh": (0, 6, 0.5, 2.0),
294
- "zinc": (0, 200, 90, 120),
295
- "fasting insulin": (0, 30, None, 7.0),
296
- "fasting glucose": (50, 150, 75, 86),
297
- }
298
-
299
-
300
- def get_gauge_preset(name: str) -> Optional[tuple]:
301
- """
302
- Return (range_lo, range_hi, optimal_lo, optimal_hi) untuk biomarker.
303
- Returns None jika tidak ada preset.
304
- """
305
- name_lower = name.lower()
306
- for key, preset in GAUGE_PRESETS.items():
307
- if key in name_lower or name_lower in key:
308
- return preset
309
- return None