Spaces:
Sleeping
Sleeping
Delete src/core/protocol_generator.py
Browse files- src/core/protocol_generator.py +0 -329
src/core/protocol_generator.py
DELETED
|
@@ -1,329 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Human+ Protocol Generator
|
| 3 |
-
Menggunakan plain-text delimiter output — BUKAN JSON.
|
| 4 |
-
|
| 5 |
-
Alasan tidak pakai JSON:
|
| 6 |
-
- Protocol lengkap bisa 6000-10000 token per response
|
| 7 |
-
- JSON yang terpotong di tengah menyebabkan silent parse failure
|
| 8 |
-
- Semua section menjadi kosong tanpa error yang jelas
|
| 9 |
-
- Plain text dengan delimiter jauh lebih andal dan tidak ada risiko truncation
|
| 10 |
-
"""
|
| 11 |
-
|
| 12 |
-
import re
|
| 13 |
-
from core.ai_client import call_gemini, TEMP_PROTOCOL, MAX_TOKENS_PROTOCOL
|
| 14 |
-
from core.rag_engine import retrieve_context
|
| 15 |
-
from langchain_community.vectorstores import FAISS
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
# ── Section delimiters ────────────────────────────────────────────────
|
| 19 |
-
# Dipakai untuk split response Gemini menjadi dict per section
|
| 20 |
-
_DELIMITERS = {
|
| 21 |
-
"summary": "===SUMMARY===",
|
| 22 |
-
"iv_drip": "===IV_DRIP===",
|
| 23 |
-
"supplements": "===SUPPLEMENTS===",
|
| 24 |
-
"lifestyle": "===LIFESTYLE===",
|
| 25 |
-
"retest": "===RETEST===",
|
| 26 |
-
}
|
| 27 |
-
|
| 28 |
-
# ── System identity ───────────────────────────────────────────────────
|
| 29 |
-
_SYSTEM_IDENTITY = """
|
| 30 |
-
Kamu adalah AI Longevity Specialist resmi dari Human+ Bali, didirikan oleh Benjamin White (@bennywhitethatsright).
|
| 31 |
-
|
| 32 |
-
Filosofi utama: "From Injured → Optimized"
|
| 33 |
-
Voice: Positif, empowering, seperti seorang coach yang peduli — bukan dokter yang menghakimi.
|
| 34 |
-
Bahasa: Indonesia yang mudah dipahami, natural, tidak terlalu formal.
|
| 35 |
-
|
| 36 |
-
Background Benjamin White: Pernah koma dan mengalami traumatic brain injury.
|
| 37 |
-
Bangkit melalui 8+ tahun natural medicine, neuroscience, dan biohacking.
|
| 38 |
-
Sekarang membantu orang lain melakukan hal yang sama di Bali.
|
| 39 |
-
"""
|
| 40 |
-
|
| 41 |
-
# ── Main prompt ───────────────────────────────────────────────────────
|
| 42 |
-
_PROTOCOL_PROMPT_TEMPLATE = """{system_identity}
|
| 43 |
-
|
| 44 |
-
═══════════════════════════════════════
|
| 45 |
-
HASIL LAB PASIEN:
|
| 46 |
-
{biomarker_summary}
|
| 47 |
-
|
| 48 |
-
═══════════════════════════════════════
|
| 49 |
-
KNOWLEDGE BASE HUMAN+:
|
| 50 |
-
{context}
|
| 51 |
-
|
| 52 |
-
═══════════════════════════════════════
|
| 53 |
-
INSTRUKSI:
|
| 54 |
-
|
| 55 |
-
Buat rekomendasi protocol hyperpersonal yang LENGKAP dan DETAIL berdasarkan hasil lab di atas.
|
| 56 |
-
|
| 57 |
-
Format output WAJIB menggunakan delimiter berikut — tulis persis seperti ini:
|
| 58 |
-
|
| 59 |
-
===SUMMARY===
|
| 60 |
-
Tulis 3-4 kalimat ringkasan temuan utama. Sebutkan marker spesifik yang paling kritis
|
| 61 |
-
beserta nilainya. Akhiri dengan motivasi positif "From Injured → Optimized".
|
| 62 |
-
|
| 63 |
-
===IV_DRIP===
|
| 64 |
-
Tulis rekomendasi IV Drip yang LENGKAP dan DETAIL:
|
| 65 |
-
- Nama protocol (The All-In atau varian custom)
|
| 66 |
-
- SEMUA komposisi dengan dosis spesifik
|
| 67 |
-
- Frekuensi dan durasi per sesi
|
| 68 |
-
- Penjelasan MENGAPA setiap komponen dipilih berdasarkan nilai lab pasien
|
| 69 |
-
|
| 70 |
-
===SUPPLEMENTS===
|
| 71 |
-
Tulis suplemen harian yang LENGKAP:
|
| 72 |
-
- Minimal 6-8 suplemen yang relevan dengan hasil lab
|
| 73 |
-
- Setiap suplemen: nama, dosis, waktu minum, dan alasan (kaitkan dengan nilai lab)
|
| 74 |
-
- Gunakan format list atau tabel yang jelas
|
| 75 |
-
|
| 76 |
-
===LIFESTYLE===
|
| 77 |
-
Tulis protocol lifestyle yang LENGKAP dan KONKRET:
|
| 78 |
-
1. Ice Bath / Cold Exposure (suhu, durasi, frekuensi, breathing protocol)
|
| 79 |
-
2. Movement & Exercise (jenis, frekuensi, durasi)
|
| 80 |
-
3. Sleep & Recovery (jam tidur, tips HRV, no-screen, dll)
|
| 81 |
-
4. Nutrisi & Diet (makanan yang dianjurkan/dihindari, khusus berdasarkan hasil lab)
|
| 82 |
-
5. Sunlight & Circadian Rhythm
|
| 83 |
-
|
| 84 |
-
===RETEST===
|
| 85 |
-
Tulis jadwal retest yang KONKRET:
|
| 86 |
-
- Timeline retest pertama (kapan)
|
| 87 |
-
- Marker prioritas yang perlu diperiksa
|
| 88 |
-
- Target angka spesifik yang ingin dicapai per marker
|
| 89 |
-
- Next step dan CTA untuk konsultasi langsung dengan Human+ Bali
|
| 90 |
-
|
| 91 |
-
PENTING:
|
| 92 |
-
- Selalu sebut nilai lab pasien secara spesifik (contoh: "Vitamin D Anda 22 ng/mL, target kami 60-70 ng/mL")
|
| 93 |
-
- Setiap rekomendasi HARUS terhubung ke hasil lab, bukan generic
|
| 94 |
-
- Tulis selengkap dan sedetail mungkin untuk setiap section
|
| 95 |
-
- Gunakan markdown (bold, bullet, tabel) agar mudah dibaca
|
| 96 |
-
- Akhiri dengan semangat "From Injured → Optimized"
|
| 97 |
-
"""
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
class ProtocolGeneratorError(Exception):
|
| 101 |
-
pass
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
def generate_protocol(
|
| 105 |
-
biomarkers: list[dict],
|
| 106 |
-
vector_store: FAISS = None,
|
| 107 |
-
) -> dict:
|
| 108 |
-
"""
|
| 109 |
-
Generate protocol dari biomarker list.
|
| 110 |
-
Output: dict dengan keys summary, iv_drip, supplements, lifestyle, retest.
|
| 111 |
-
"""
|
| 112 |
-
biomarker_summary = _format_biomarkers_for_prompt(biomarkers)
|
| 113 |
-
|
| 114 |
-
try:
|
| 115 |
-
context = retrieve_context(biomarker_summary, vector_store)
|
| 116 |
-
except Exception as e:
|
| 117 |
-
raise ProtocolGeneratorError(f"RAG retrieval gagal: {e}") from e
|
| 118 |
-
|
| 119 |
-
prompt = _PROTOCOL_PROMPT_TEMPLATE.format(
|
| 120 |
-
system_identity=_SYSTEM_IDENTITY,
|
| 121 |
-
biomarker_summary=biomarker_summary,
|
| 122 |
-
context=context,
|
| 123 |
-
)
|
| 124 |
-
|
| 125 |
-
try:
|
| 126 |
-
raw_response = call_gemini(
|
| 127 |
-
contents=[prompt],
|
| 128 |
-
temperature=TEMP_PROTOCOL,
|
| 129 |
-
max_tokens=MAX_TOKENS_PROTOCOL, # 16000 — cukup untuk semua section
|
| 130 |
-
)
|
| 131 |
-
except Exception as e:
|
| 132 |
-
raise ProtocolGeneratorError(f"Gemini protocol generation gagal: {e}") from e
|
| 133 |
-
|
| 134 |
-
return _parse_delimiter_response(raw_response)
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
def generate_protocol_from_raw_text(
|
| 138 |
-
extracted_text: str,
|
| 139 |
-
vector_store: FAISS = None,
|
| 140 |
-
) -> dict:
|
| 141 |
-
"""Fallback: generate dari raw text (non-structured biomarkers)."""
|
| 142 |
-
try:
|
| 143 |
-
context = retrieve_context(extracted_text, vector_store)
|
| 144 |
-
except Exception as e:
|
| 145 |
-
raise ProtocolGeneratorError(f"RAG retrieval gagal: {e}") from e
|
| 146 |
-
|
| 147 |
-
prompt = _PROTOCOL_PROMPT_TEMPLATE.format(
|
| 148 |
-
system_identity=_SYSTEM_IDENTITY,
|
| 149 |
-
biomarker_summary=extracted_text,
|
| 150 |
-
context=context,
|
| 151 |
-
)
|
| 152 |
-
|
| 153 |
-
try:
|
| 154 |
-
raw_response = call_gemini(
|
| 155 |
-
contents=[prompt],
|
| 156 |
-
temperature=TEMP_PROTOCOL,
|
| 157 |
-
max_tokens=MAX_TOKENS_PROTOCOL,
|
| 158 |
-
)
|
| 159 |
-
except Exception as e:
|
| 160 |
-
raise ProtocolGeneratorError(f"Gemini gagal: {e}") from e
|
| 161 |
-
|
| 162 |
-
return _parse_delimiter_response(raw_response)
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
# ── Private helpers ──────────────────────────────────────────────────
|
| 166 |
-
|
| 167 |
-
def _parse_delimiter_response(raw: str) -> dict:
|
| 168 |
-
"""
|
| 169 |
-
Parse plain-text response dengan delimiter menjadi dict per section.
|
| 170 |
-
|
| 171 |
-
Strategi:
|
| 172 |
-
1. Split berdasarkan ===SECTION=== delimiter
|
| 173 |
-
2. Map ke dict key yang sesuai
|
| 174 |
-
3. Fallback: jika delimiter tidak ditemukan (Gemini tidak patuh format),
|
| 175 |
-
coba parse otomatis berdasarkan heading markdown
|
| 176 |
-
"""
|
| 177 |
-
result = {
|
| 178 |
-
"summary": "",
|
| 179 |
-
"iv_drip": "",
|
| 180 |
-
"supplements": "",
|
| 181 |
-
"lifestyle": "",
|
| 182 |
-
"retest": "",
|
| 183 |
-
"key_priorities": [],
|
| 184 |
-
}
|
| 185 |
-
|
| 186 |
-
# Cek apakah response mengandung delimiter
|
| 187 |
-
has_delimiters = any(d in raw for d in _DELIMITERS.values())
|
| 188 |
-
|
| 189 |
-
if has_delimiters:
|
| 190 |
-
result = _parse_by_delimiter(raw, result)
|
| 191 |
-
else:
|
| 192 |
-
# Fallback: Gemini tidak pakai delimiter — coba parse by heading
|
| 193 |
-
result = _parse_by_heading(raw, result)
|
| 194 |
-
|
| 195 |
-
# Validasi: semua section terisi, fallback ke full text jika ada yang kosong
|
| 196 |
-
result = _ensure_sections_filled(result, raw)
|
| 197 |
-
|
| 198 |
-
return result
|
| 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:
|
| 222 |
-
matched_key = key
|
| 223 |
-
break
|
| 224 |
-
|
| 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 |
-
|
| 236 |
-
|
| 237 |
-
def _parse_by_heading(raw: str, result: dict) -> dict:
|
| 238 |
-
"""
|
| 239 |
-
Fallback parser jika Gemini tidak pakai delimiter.
|
| 240 |
-
Coba deteksi section berdasarkan heading markdown yang umum.
|
| 241 |
-
"""
|
| 242 |
-
# Mapping heading keywords ke section keys
|
| 243 |
-
heading_map = {
|
| 244 |
-
"summary": ["ringkasan", "temuan utama", "summary"],
|
| 245 |
-
"iv_drip": ["iv drip", "iv therapy", "drip", "infus", "rekomendasi iv"],
|
| 246 |
-
"supplements": ["suplemen", "supplement", "suplementasi"],
|
| 247 |
-
"lifestyle": ["lifestyle", "gaya hidup", "ice bath", "recovery", "latihan"],
|
| 248 |
-
"retest": ["retest", "jadwal", "next step", "tindak lanjut"],
|
| 249 |
-
}
|
| 250 |
-
|
| 251 |
-
# Split berdasarkan markdown headings (## atau ###)
|
| 252 |
-
sections = re.split(r"\n(?=#{1,3}\s)", raw)
|
| 253 |
-
|
| 254 |
-
for section in sections:
|
| 255 |
-
if not section.strip():
|
| 256 |
-
continue
|
| 257 |
-
|
| 258 |
-
section_lower = section.lower()
|
| 259 |
-
matched_key = None
|
| 260 |
-
|
| 261 |
-
for key, keywords in heading_map.items():
|
| 262 |
-
if any(kw in section_lower for kw in keywords):
|
| 263 |
-
matched_key = key
|
| 264 |
-
break
|
| 265 |
-
|
| 266 |
-
if matched_key and not result[matched_key]:
|
| 267 |
-
result[matched_key] = section.strip()
|
| 268 |
-
|
| 269 |
-
return result
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
def _ensure_sections_filled(result: dict, raw_full: str) -> dict:
|
| 273 |
-
"""
|
| 274 |
-
Jika masih ada section kosong setelah parsing,
|
| 275 |
-
cek apakah ini karena response terpotong atau format tidak dikenali.
|
| 276 |
-
Sebagai last resort, masukkan full response ke iv_drip agar
|
| 277 |
-
tidak ada konten yang hilang sama sekali.
|
| 278 |
-
"""
|
| 279 |
-
required = ["summary", "iv_drip", "supplements", "lifestyle", "retest"]
|
| 280 |
-
empty_sections = [k for k in required if not result.get(k, "").strip()]
|
| 281 |
-
|
| 282 |
-
if len(empty_sections) == len(required):
|
| 283 |
-
# Semua kosong — berarti parsing total gagal, dump full response
|
| 284 |
-
result["iv_drip"] = raw_full
|
| 285 |
-
result["summary"] = (
|
| 286 |
-
"Protocol berhasil dibuat. Format response tidak terstruktur — "
|
| 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 |
-
|
| 300 |
-
|
| 301 |
-
def _format_biomarkers_for_prompt(biomarkers: list[dict]) -> str:
|
| 302 |
-
"""Format biomarker list menjadi teks ringkas dan prioritas untuk prompt."""
|
| 303 |
-
lines = []
|
| 304 |
-
|
| 305 |
-
danger = [b for b in biomarkers if b.get("status") == "danger"]
|
| 306 |
-
warning = [b for b in biomarkers if b.get("status") == "warning"]
|
| 307 |
-
optimal = [b for b in biomarkers if b.get("status") == "optimal"]
|
| 308 |
-
|
| 309 |
-
if danger:
|
| 310 |
-
lines.append("🔴 PERLU PERHATIAN SEGERA:")
|
| 311 |
-
for b in danger:
|
| 312 |
-
ref = f" (Human+ target: {b['reference']})" if b.get("reference") else ""
|
| 313 |
-
lines.append(f" - {b['name']}: {b['value']} {b['unit']}{ref}")
|
| 314 |
-
|
| 315 |
-
if warning:
|
| 316 |
-
lines.append("\n🟡 SUB-OPTIMAL (perlu dioptimalkan):")
|
| 317 |
-
for b in warning:
|
| 318 |
-
ref = f" (Human+ target: {b['reference']})" if b.get("reference") else ""
|
| 319 |
-
lines.append(f" - {b['name']}: {b['value']} {b['unit']}{ref}")
|
| 320 |
-
|
| 321 |
-
if optimal:
|
| 322 |
-
lines.append("\n🟢 SUDAH OPTIMAL (maintain):")
|
| 323 |
-
for b in optimal:
|
| 324 |
-
lines.append(f" - {b['name']}: {b['value']} {b['unit']}")
|
| 325 |
-
|
| 326 |
-
if not lines:
|
| 327 |
-
return "Tidak ada biomarker yang berhasil diekstrak."
|
| 328 |
-
|
| 329 |
-
return "\n".join(lines)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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