async function handleResponse(response) { const raw = await response.text(); // Try to parse JSON safely try { return JSON.parse(raw); } catch (e) { throw new Error("Invalid JSON response:\n" + raw); } } // ====================== // NER // ====================== async function runNER() { try { const text = document.getElementById("text").value.trim(); if (!text) { document.getElementById("output").textContent = "Please enter text."; return; } const response = await fetch("/predict", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text: text, mode: "1" }) }); const data = await handleResponse(response); if (data.error) { document.getElementById("output").textContent = "NER Backend Error:\n" + data.error; return; } if (!data.resp || data.resp.length === 0) { document.getElementById("output").textContent = "No NER results."; return; } // pretty print document.getElementById("output").textContent = JSON.stringify(data.resp, null, 2); } catch (err) { document.getElementById("output").textContent = "NER Error: " + err.message; } } // ====================== // Relation Extraction // ====================== async function runRE() { try { const text = document.getElementById("text").value.trim(); if (!text) { document.getElementById("output").textContent = "Please enter text."; return; } const response = await fetch("/predict_re", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text: text }) }); const data = await handleResponse(response); if (data.error) { document.getElementById("output").textContent = "RE Backend Error:\n" + data.error; return; } if (!data.resp || data.resp.length === 0) { document.getElementById("output").textContent = "No relations found."; return; } // ========================= // CLEAN JSON OUTPUT FORMAT // ========================= const formattedList = data.resp.map(r => ({ Subject: { Type: r.Subject.Type, Label: r.Subject.Label }, Relation: r.Relation, Object: { Type: r.Object.Type, Label: r.Object.Label }, Confidence: r.Confidence })); document.getElementById("output").textContent = JSON.stringify(formattedList, null, 2); } catch (err) { document.getElementById("output").textContent = "RE Error: " + err.message; } }