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

Upload 3 files

Browse files
src/core/chart_builder.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
src/core/pdf_processor.py CHANGED
@@ -182,17 +182,21 @@ def _enrich_biomarker(raw: dict) -> Optional[dict]:
182
  name, numeric_value, raw.get("lab_flag", "normal")
183
  )
184
 
 
 
 
185
  return {
186
  # For UI rendering
187
  "name": name,
188
  "value": value,
189
  "unit": unit,
190
  "status": status,
191
- "reference": human_plus_ref,
192
  # Raw lab data (untuk expander / debug)
193
  "raw_value": numeric_value,
194
  "lab_flag": raw.get("lab_flag", "normal"),
195
  "reference_range": raw.get("reference_range", ""),
 
196
  }
197
  except Exception:
198
  return None
@@ -210,12 +214,14 @@ def _map_to_human_plus_status(
210
  (status, human_plus_reference_string)
211
  status: 'optimal' | 'warning' | 'danger' | 'neutral'
212
  """
213
- name_lower = name.lower()
 
 
214
 
215
  # Find matching range config
216
  range_cfg = None
217
  for key, cfg in _OPTIMAL_RANGES.items():
218
- if key in name_lower or name_lower in key:
219
  range_cfg = cfg
220
  break
221
 
 
182
  name, numeric_value, raw.get("lab_flag", "normal")
183
  )
184
 
185
+ # Gunakan Human+ target jika tersedia, fallback ke reference_range dari lab
186
+ display_reference = human_plus_ref if human_plus_ref else raw.get("reference_range", "")
187
+
188
  return {
189
  # For UI rendering
190
  "name": name,
191
  "value": value,
192
  "unit": unit,
193
  "status": status,
194
+ "reference": display_reference,
195
  # Raw lab data (untuk expander / debug)
196
  "raw_value": numeric_value,
197
  "lab_flag": raw.get("lab_flag", "normal"),
198
  "reference_range": raw.get("reference_range", ""),
199
+ "human_plus_ref": human_plus_ref, # Human+ target khusus (bisa berbeda)
200
  }
201
  except Exception:
202
  return None
 
214
  (status, human_plus_reference_string)
215
  status: 'optimal' | 'warning' | 'danger' | 'neutral'
216
  """
217
+ # Normalisasi: hapus teks dalam kurung, lowercase
218
+ # contoh: "hs-CRP (High-sensitivity C-Reactive Protein)" → "hs-crp"
219
+ name_lower = re.sub(r"\s*\(.*?\)", "", name.lower()).strip()
220
 
221
  # Find matching range config
222
  range_cfg = None
223
  for key, cfg in _OPTIMAL_RANGES.items():
224
+ if key == name_lower or key in name_lower or name_lower in key:
225
  range_cfg = cfg
226
  break
227
 
src/core/protocol_generator.py CHANGED
@@ -199,19 +199,23 @@ def _parse_delimiter_response(raw: str) -> dict:
199
 
200
 
201
  def _parse_by_delimiter(raw: str, result: dict) -> dict:
202
- """Split response berdasarkan ===DELIMITER=== markers."""
203
- # Buat pattern untuk split
 
 
 
 
 
 
204
  delimiter_pattern = r"(===(?:SUMMARY|IV_DRIP|SUPPLEMENTS|LIFESTYLE|RETEST)===)"
205
- parts = re.split(delimiter_pattern, raw)
206
 
207
- # parts akan berupa: ['teks_awal', '===SUMMARY===', 'isi_summary', '===IV_DRIP===', ...]
208
  current_key = None
209
  for part in parts:
210
  part = part.strip()
211
  if not part:
212
  continue
213
 
214
- # Cek apakah ini delimiter
215
  matched_key = None
216
  for key, delimiter in _DELIMITERS.items():
217
  if part == delimiter:
@@ -221,7 +225,11 @@ def _parse_by_delimiter(raw: str, result: dict) -> dict:
221
  if matched_key:
222
  current_key = matched_key
223
  elif current_key and part:
224
- result[current_key] = part
 
 
 
 
225
 
226
  return result
227
 
@@ -279,12 +287,13 @@ def _ensure_sections_filled(result: dict, raw_full: str) -> dict:
279
  "semua konten ditampilkan di bawah."
280
  )
281
  elif empty_sections:
282
- # Sebagian kosong — tandai agar user tahu
 
283
  for key in empty_sections:
284
- result[key] = (
285
- f"*Section ini tidak terbaca dari response AI. "
286
- f"Silakan generate ulang atau konsultasi langsung dengan Human+ Bali.*"
287
- )
288
 
289
  return result
290
 
 
199
 
200
 
201
  def _parse_by_delimiter(raw: str, result: dict) -> dict:
202
+ """Split response berdasarkan ===DELIMITER=== markers.
203
+
204
+ Fix: Gemini sering menambahkan spasi/newline di sekitar delimiter.
205
+ Normalisasi dulu sebelum split agar match selalu berhasil.
206
+ """
207
+ # Normalisasi: pastikan setiap delimiter berdiri di baris sendiri
208
+ normalized = re.sub(r"[ \t]*(===\w+===)[ \t]*", r"\n\1\n", raw)
209
+
210
  delimiter_pattern = r"(===(?:SUMMARY|IV_DRIP|SUPPLEMENTS|LIFESTYLE|RETEST)===)"
211
+ parts = re.split(delimiter_pattern, normalized)
212
 
 
213
  current_key = None
214
  for part in parts:
215
  part = part.strip()
216
  if not part:
217
  continue
218
 
 
219
  matched_key = None
220
  for key, delimiter in _DELIMITERS.items():
221
  if part == delimiter:
 
225
  if matched_key:
226
  current_key = matched_key
227
  elif current_key and part:
228
+ # Akumulasi — jangan overwrite jika sudah ada konten
229
+ if result[current_key]:
230
+ result[current_key] += "\n" + part
231
+ else:
232
+ result[current_key] = part
233
 
234
  return result
235
 
 
287
  "semua konten ditampilkan di bawah."
288
  )
289
  elif empty_sections:
290
+ # Summary boleh kosong — tidak tampilkan pesan error yang membingungkan.
291
+ # Section lain yang kosong: beri pesan singkat saja.
292
  for key in empty_sections:
293
+ if key == "summary":
294
+ result[key] = "" # kosong = info box tidak ditampilkan
295
+ else:
296
+ result[key] = "*Konten tidak terbaca. Silakan generate ulang.*"
297
 
298
  return result
299