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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
<!doctype html>
<html lang="id">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta name="description" content="Konsol uji deteksi entitas bernama (NER) transformer dan aturan Bahasa Indonesia." />
  <title>NER Detector: Konsol Uji</title>
  <link rel="preconnect" href="https://fonts.googleapis.com" />
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Epilogue:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500;600&display=swap" />
  <link rel="stylesheet" href="assets/css/tailwind.css" />
</head>

<body class="app-shell">
  <header class="topbar">
    <div class="topbar-inner">
      <div class="brand-mark">
        <a href="index.html" class="btn btn--secondary btn-sm">Kembali</a>
        <h1 class="brand-title">Deteksi Entitas Bernama (NER)</h1>
      </div>
      <span id="modelName" class="inline-badge inline-badge--muted font-mono">Model: memuat…</span>
    </div>
  </header>

  <main class="console-container">
    <section class="console-panel">
      <div>
        <div class="prompt-field-header">
          <label for="nerInput" class="prompt-field-label">Teks uji</label>
          <span class="prompt-field-hint">Masukkan teks dengan nama tokoh, organisasi, lokasi, tanggal, atau nominal</span>
        </div>
        <textarea id="nerInput" rows="5" class="ink-textarea ink-textarea--resizable"
          placeholder="Contoh: Dr. Budi Santoso memimpin rapat Kementerian Pendidikan di Jakarta pada 17 Agustus 2025..."></textarea>
      </div>

      <div class="flex flex-wrap items-center justify-end gap-2">
        <button id="sampleBtn" type="button" class="btn btn--secondary btn-sm">Contoh Teks</button>
        <button id="clearBtn" type="button" class="btn btn--quiet btn-sm">Bersihkan</button>
        <button id="detectBtn" type="button" class="btn btn--primary btn-sm">Deteksi Entitas</button>
      </div>

      <div id="errorBox" class="error-banner hidden" role="alert"></div>
      <div id="legend" class="flex flex-wrap gap-2"></div>
    </section>

    <section class="console-panel">
      <h2 class="pane-title">Sorotan Teks</h2>
      <div id="highlightBox" class="console-panel--soft text-sm leading-relaxed whitespace-pre-wrap"></div>

      <div id="entityListSection" class="flex flex-col gap-3">
        <div class="flex items-center justify-between gap-2">
          <h3 class="section-rule-title">Daftar Entitas</h3>
          <span id="entityCount" class="prompt-field-hint num">0 ditemukan</span>
        </div>
        <div id="entityList" class="flex flex-col gap-2"></div>
      </div>
    </section>
  </main>

  <script type="module">
    import {
      $,
      clearError,
      esc,
      pollServerStatus,
      renderEmptyState,
      showError,
    } from "./assets/js/test-page-common.js";

    const API = "http://127.0.0.1:8001";

    const LABEL_CLASS = {
      PERSON: "cat-risky_content",
      ORGANIZATION: "cat-pii",
      LOCATION: "cat-ner",
      FACILITY: "cat-quality",
      DATE: "cat-syntax",
      TIME: "cat-missing",
      EVENT: "cat-filler",
      PRODUCT: "cat-special_char",
      WORK_OF_ART: "cat-field_fit",
      LAW: "cat-profanity",
      MONEY: "cat-slang",
      RELIGION: "cat-weak",
      LANGUAGE: "cat-typo",
    };

    const LABEL_DISPLAY = {
      PERSON: "Orang",
      ORGANIZATION: "Organisasi",
      LOCATION: "Lokasi",
      FACILITY: "Fasilitas",
      DATE: "Tanggal",
      TIME: "Waktu",
      EVENT: "Kejadian",
      PRODUCT: "Produk",
      WORK_OF_ART: "Karya",
      LAW: "Peraturan",
      MONEY: "Uang",
      RELIGION: "Agama",
      LANGUAGE: "Bahasa",
    };

    function displayLabel(label) {
      return LABEL_DISPLAY[label] || label;
    }

    const SAMPLE =
      "Prof. Dr. Hendra Kusuma dari Universitas Gadjah Mada mengunjungi SMPN 5 Surakarta " +
      "pada 12 Oktober 2025 untuk membahas anggaran dana BOS sebesar Rp 15.000.000 sesuai UU No. 20 Tahun 2003.";

    function renderLegend() {
      $("legend").innerHTML = Object.entries(LABEL_CLASS)
        .map(
          ([label, cls]) =>
            `<span class="inline-badge ${cls}"><span class="entity-dot"></span>${esc(displayLabel(label))}</span>`,
        )
        .join("");
    }

    function renderResults(text, entities) {
      if (!entities.length) {
        $("highlightBox").textContent = text;
        $("entityCount").textContent = "0 ditemukan";
        $("entityList").innerHTML = renderEmptyState(
          "Tidak ada entitas terdeteksi",
          "Model maupun aturan tidak menemukan nama tokoh, tempat, atau organisasi.",
        );
        return;
      }

      const sorted = [...entities].sort((a, b) => a.start - b.start);
      let cursor = 0;
      const chunks = [];
      for (const ent of sorted) {
        if (ent.start < cursor) continue;
        if (ent.start > cursor) chunks.push(esc(text.slice(cursor, ent.start)));
        const cls = LABEL_CLASS[ent.label] || "cat-ner";
        const disp = displayLabel(ent.label);
        chunks.push(
          `<span class="hl-mark ${cls}" data-tooltip="${esc(disp)}">${esc(text.slice(ent.start, ent.end))}</span>`,
        );
        cursor = ent.end;
      }
      if (cursor < text.length) chunks.push(esc(text.slice(cursor)));
      $("highlightBox").innerHTML = chunks.join("");

      $("entityCount").textContent = `${entities.length} ditemukan`;
      $("entityList").innerHTML = sorted
        .map((ent) => {
          const cls = LABEL_CLASS[ent.label] || "cat-ner";
          const srcLabel = ent.source === "rule" ? "aturan" : "model ML";
          const pct = Math.round((ent.score ?? ent.confidence ?? 0) * 100);
          return `<div class="finding-row">
            <div class="flex flex-wrap items-center gap-2">
              <span class="inline-badge ${cls}"><span class="entity-dot"></span>${esc(displayLabel(ent.label))}</span>
              <span class="font-mono text-xs font-semibold">${esc(ent.word ?? ent.text)}</span>
              <span class="inline-badge inline-badge--muted">${esc(srcLabel)}</span>
            </div>
            <span class="font-mono text-xs text-muted num">[${ent.start}:${ent.end}] (${pct}%)</span>
          </div>`;
        })
        .join("");
    }

    async function runDetect() {
      const text = $("nerInput").value;
      clearError("errorBox");
      if (!text.trim()) {
        showError("errorBox", "Masukkan teks terlebih dahulu sebelum menjalankan deteksi.");
        return;
      }
      const btn = $("detectBtn");
      btn.disabled = true;
      btn.textContent = "Mendeteksi...";
      try {
        const res = await fetch(`${API}/api/ner`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ text }),
        });
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const data = await res.json();
        renderResults(text, data.entities || []);
      } catch (err) {
        showError("errorBox", `Gagal menghubungi server NER (${API}): ${err.message}`);
      } finally {
        btn.disabled = false;
        btn.textContent = "Deteksi Entitas";
      }
    }

    renderLegend();
    $("highlightBox").innerHTML = renderEmptyState(
      "Belum ada pemeriksaan",
      "Isi teks uji atau pilih Contoh Teks lalu klik Deteksi Entitas.",
    );

    $("sampleBtn").addEventListener("click", () => {
      $("nerInput").value = SAMPLE;
      clearError("errorBox");
    });
    $("clearBtn").addEventListener("click", () => {
      $("nerInput").value = "";
      clearError("errorBox");
      $("highlightBox").innerHTML = renderEmptyState(
        "Belum ada pemeriksaan",
        "Isi teks uji atau pilih Contoh Teks lalu klik Deteksi Entitas.",
      );
      $("entityCount").textContent = "0 ditemukan";
      $("entityList").innerHTML = "";
    });
    $("detectBtn").addEventListener("click", runDetect);

    pollServerStatus({
      api: API,
      onStatus(data) {
        if (data?.model) $("modelName").textContent = `Model: ${data.model}`;
      },
    });
  </script>
</body>

</html>