Spaces:
Sleeping
Sleeping
File size: 17,802 Bytes
622b3c4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 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 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>MapMate — Chat + Places</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Tailwind theme (brand + accent) — must be defined BEFORE the CDN script -->
<script>
tailwind = {}; // ensure object exists
tailwind.config = {
theme: {
extend: {
colors: { brand: '#0A2647', accent: '#FF6B00' },
},
},
};
</script>
<script src="https://cdn.tailwindcss.com"></script>
<!-- Markdown renderer + sanitizer -->
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dompurify@3.0.9/dist/purify.min.js"></script>
<!-- Optional code highlighting -->
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/styles/github.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/lib/common.min.js"></script>
<style>
.md :is(pre, code) {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
}
.md pre { background: rgba(15,23,42,.05); padding: .75rem; border-radius: .5rem; overflow: auto; }
.md code:not(pre code) { background: rgba(15,23,42,.05); padding: .15rem .35rem; border-radius: .35rem; }
.md a { color: #2563eb; text-decoration: underline; }
.md ul, .md ol { margin-left: 1.25rem; list-style: revert; }
.md h1, .md h2, .md h3 { font-weight: 600; margin-top: .75rem; }
.md p { margin: .4rem 0; }
kbd { border: 1px solid rgba(100,116,139,.4); border-bottom-width: 2px; padding: 0 .35rem; border-radius: .35rem; font-size: .75rem; background: #fff; }
:focus-visible { outline: 2px dashed #FF6B00; outline-offset: 2px; }
</style>
</head>
<body class="min-h-screen bg-slate-50 text-slate-900">
<!-- Header -->
<header class="bg-brand text-white sticky top-0 z-40">
<div class="max-w-6xl mx-auto px-4 py-3 flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
<h1 class="text-xl font-semibold tracking-tight">🗺️ MapMate</h1>
<div class="flex flex-wrap items-center gap-2">
<label class="text-sm/none opacity-80">API Base URL</label>
<input id="baseUrl" class="px-3 py-2 rounded-lg border bg-white/95 text-slate-900 text-sm w-72" placeholder="http://localhost:8000" />
<button id="saveBaseUrl" class="px-3 py-2 rounded-lg bg-accent text-white text-sm hover:brightness-110">Save</button>
<button id="clearHistory" class="px-3 py-2 rounded-lg border border-white/30 text-sm hover:bg-white/10">Clear History</button>
</div>
</div>
</header>
<!-- Main -->
<main class="max-w-6xl mx-auto p-4 grid grid-cols-1 lg:grid-cols-3 gap-4">
<!-- Chat + BBox panel -->
<section class="lg:col-span-2 flex flex-col bg-white rounded-2xl shadow-sm border">
<div class="p-4 border-b">
<h2 class="font-semibold">Chat</h2>
<p class="text-sm text-slate-500">
Use one <em>Send</em> button. If a bounding box is filled, it’s included automatically. If you send with empty text + filled bbox, we’ll explore places inside that rectangle.
</p>
</div>
<!-- Messages -->
<div id="messages" class="p-4 space-y-4 overflow-auto" style="max-height: 44vh"></div>
<!-- Divider -->
<div class="px-4"><div class="h-px bg-slate-200"></div></div>
<!-- Bounding Box inputs (no separate button) -->
<div class="p-4 border-t">
<div class="flex items-center justify-between mb-3">
<h3 class="font-semibold">Bounding Box (optional)</h3>
<span class="text-xs text-slate-500">Will be sent with your message (or alone if message is empty)</span>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
<div class="p-3 border rounded-xl">
<div class="font-medium text-sm mb-2">North-East</div>
<div class="grid grid-cols-2 gap-2">
<input id="neLat" type="number" step="any" placeholder="NE lat" class="px-3 py-2 rounded-lg border bg-white text-sm" value="13.111864" />
<input id="neLon" type="number" step="any" placeholder="NE lon" class="px-3 py-2 rounded-lg border bg-white text-sm" value="80.243246" />
</div>
</div>
<div class="p-3 border rounded-xl">
<div class="font-medium text-sm mb-2">South-West</div>
<div class="grid grid-cols-2 gap-2">
<input id="swLat" type="number" step="any" placeholder="SW lat" class="px-3 py-2 rounded-lg border bg-white text-sm" value="13.105112" />
<input id="swLon" type="number" step="any" placeholder="SW lon" class="px-3 py-2 rounded-lg border bg-white text-sm" value="80.236375" />
</div>
</div>
</div>
<p class="text-xs text-slate-500 mt-2">
Backend defaults to “points of interest” when message is empty (bbox-only).
</p>
</div>
<!-- Composer (single send) -->
<div class="p-4 border-t">
<form id="chatForm" class="flex items-end gap-2">
<textarea id="userInput" rows="2" class="flex-1 px-3 py-2 rounded-xl border bg-white"
placeholder="Type your message… (e.g., best 5 hotels in Chennai)"></textarea>
<button id="sendBtn" type="submit" class="px-4 py-2 rounded-xl bg-accent text-white font-medium hover:brightness-110">
Send
</button>
</form>
<p class="text-xs text-slate-500 mt-2">
Tip: Press <kbd>Enter</kbd> to send, <kbd>Shift+Enter</kbd> for a new line.
</p>
</div>
</section>
<!-- Results panel -->
<section class="bg-white rounded-2xl shadow-sm border">
<div class="p-4 border-b flex items-center justify-between">
<h2 class="font-semibold">Places</h2>
<label class="text-xs text-slate-500 flex items-center gap-2">
<input type="checkbox" id="toggleRaw" class="rounded border" />
Show raw JSON
</label>
</div>
<div id="places" class="p-4 space-y-4 overflow-auto" style="max-height: 60vh">
<p class="text-sm text-slate-500">No places yet — try “best hotel in Chennai” or fill a bounding box and press Send.</p>
</div>
<div id="rawJsonWrap" class="hidden border-t">
<pre id="rawJson" class="p-4 text-xs overflow-auto"></pre>
</div>
</section>
</main>
<!-- Toast -->
<div id="toast" class="fixed bottom-4 right-4 hidden px-4 py-2 rounded-xl bg-rose-600 text-white shadow-lg"></div>
<script>
// Elements
const baseUrlInput = document.getElementById("baseUrl");
const saveBaseUrlBtn = document.getElementById("saveBaseUrl");
const clearHistoryBtn = document.getElementById("clearHistory");
const messagesEl = document.getElementById("messages");
const placesEl = document.getElementById("places");
const toggleRaw = document.getElementById("toggleRaw");
const rawJsonWrap = document.getElementById("rawJsonWrap");
const rawJsonEl = document.getElementById("rawJson");
const chatForm = document.getElementById("chatForm");
const userInput = document.getElementById("userInput");
const sendBtn = document.getElementById("sendBtn");
const toast = document.getElementById("toast");
// BBox inputs
const neLat = document.getElementById("neLat");
const neLon = document.getElementById("neLon");
const swLat = document.getElementById("swLat");
const swLon = document.getElementById("swLon");
// State
let conversation_history = [];
let lastResponseRaw = null;
// Base URL init
const DEFAULT_BASE = window.location.origin;
baseUrlInput.value = localStorage.getItem("mapmate_base") || DEFAULT_BASE;
saveBaseUrlBtn.addEventListener("click", () => {
localStorage.setItem("mapmate_base", baseUrlInput.value.trim() || DEFAULT_BASE);
showToast("Base URL saved");
});
clearHistoryBtn.addEventListener("click", () => {
conversation_history = [];
messagesEl.innerHTML = "";
placesEl.innerHTML = '<p class="text-sm text-slate-500">No places yet — try “best hotel in Chennai” or fill a bounding box and press Send.</p>';
rawJsonEl.textContent = "";
lastResponseRaw = null;
showToast("History cleared");
});
toggleRaw.addEventListener("change", () => {
rawJsonWrap.classList.toggle("hidden", !toggleRaw.checked);
});
// Enter-to-send
userInput.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
chatForm.requestSubmit();
}
});
// ---------- Helpers ----------
function fmt(n) {
if (n === null || n === undefined || n === "") return "—";
return Number(n).toFixed(6);
}
// Strip ChatML / header tokens the model might emit
function stripHeaders(s = "") {
return (s || "")
.replace(/<\|header_start\|>.*?<\|header_end\|>/gs, "")
.replace(/<\|im_start\|>.*?<\|im_end\|>/gs, "")
.replace(/<\|[^>]*\|>/g, "")
.trim();
}
// Rendering
function renderMessage(role, text) {
const isUser = role === "user";
const wrapper = document.createElement("div");
wrapper.className = `flex ${isUser ? "justify-end" : "justify-start"}`;
const bubble = document.createElement("div");
bubble.className = `max-w-[85%] rounded-2xl px-4 py-3 shadow-sm ${
isUser
// User bubble: black text
? "bg-accent/10 text-black border border-accent/30 rounded-br-md"
// Assistant bubble: markdown styled
: "bg-slate-100 text-slate-900 rounded-bl-md md"
}`;
if (isUser) {
bubble.textContent = text;
} else {
bubble.classList.add("md");
const safe = DOMPurify.sanitize(marked.parse(stripHeaders(text || "")));
bubble.innerHTML = safe;
if (window.hljs) bubble.querySelectorAll("pre code").forEach((el) => hljs.highlightElement(el));
}
wrapper.appendChild(bubble);
messagesEl.appendChild(wrapper);
messagesEl.scrollTop = messagesEl.scrollHeight;
}
function renderPlaces(places, raw) {
placesEl.innerHTML = "";
if (!places || places.length === 0) {
placesEl.innerHTML = '<p class="text-sm text-slate-500">No places returned.</p>';
} else {
places.forEach((p, idx) => {
const ne = p.bounding_box?.north_east || {};
const sw = p.bounding_box?.south_west || {};
const mapsUrl =
p.maps_url || (p.latitude && p.longitude ? `https://www.google.com/maps?q=${p.latitude},${p.longitude}` : null);
const card = document.createElement("div");
card.className = "rounded-xl border p-4 hover:shadow-sm transition";
card.innerHTML = `
<div class="flex items-start justify-between gap-2">
<div>
<div class="text-sm text-slate-500">#${idx + 1}</div>
<h3 class="font-semibold">${p.name || "Unknown"}</h3>
<p class="text-sm text-slate-600">${p.address || "—"}</p>
</div>
${
mapsUrl
? `<a href="${mapsUrl}" target="_blank" class="text-sm text-accent hover:underline">Open in Maps ↗</a>`
: ""
}
</div>
<div class="grid grid-cols-2 gap-3 mt-3 text-sm">
<div class="space-y-1">
<div><span class="text-slate-500">lat,lng:</span> ${fmt(p.latitude)}, ${fmt(p.longitude)}</div>
<div><span class="text-slate-500">Rating:</span> ${p.rating ?? "—"}</div>
<div><span class="text-slate-500">Reviews:</span> ${p.user_rating_count ?? "—"}</div>
</div>
<div class="space-y-1">
<div class="text-slate-500">Bounding Box</div>
<div>NE: ${fmt(ne.lat)}, ${fmt(ne.lon)}</div>
<div>SW: ${fmt(sw.lat)}, ${fmt(sw.lon)}</div>
</div>
</div>`;
placesEl.appendChild(card);
});
}
lastResponseRaw = raw || null;
rawJsonEl.textContent = lastResponseRaw ? JSON.stringify(lastResponseRaw, null, 2) : "";
}
function showToast(msg) {
toast.textContent = msg;
toast.classList.remove("hidden");
setTimeout(() => toast.classList.add("hidden"), 1400);
}
function getBase() {
return (baseUrlInput.value || "").trim() || DEFAULT_BASE;
}
function getBoundingBoxFromInputs() {
const neLatVal = parseFloat(neLat.value);
const neLonVal = parseFloat(neLon.value);
const swLatVal = parseFloat(swLat.value);
const swLonVal = parseFloat(swLon.value);
if ([neLatVal, neLonVal, swLatVal, swLonVal].some((v) => Number.isNaN(v))) return null;
if (swLatVal > neLatVal) return null;
if (swLonVal > neLonVal) return null;
return { north_east: { lat: neLatVal, lon: neLonVal }, south_west: { lat: swLatVal, lon: swLonVal } };
}
// Single-send API call (includes bbox if present; supports bbox-only)
async function sendSingle() {
const base = getBase();
const text = userInput.value.trim();
const bbox = getBoundingBoxFromInputs();
if (!text && !bbox) {
showToast("Type a message or fill a bounding box.");
return;
}
// Local echo - never show bbox info in user messages
if (text) {
renderMessage("user", text);
} else {
renderMessage(
"user",
`Search within **Bounding Box**\nNE: ${fmt(bbox.north_east.lat)}, ${fmt(
bbox.north_east.lon
)} | SW: ${fmt(bbox.south_west.lat)}, ${fmt(bbox.south_west.lon)}\n(_message empty → bbox-only mode_)`
);
}
const body = { user_input: text, conversation_history, bounding_box: bbox };
// Typing indicator
const typing = document.createElement("div");
typing.className = "flex justify-start";
typing.innerHTML = `<div class="max-w-[85%] rounded-2xl px-4 py-3 shadow-sm bg-slate-100 text-slate-900 rounded-bl-md">
<span class="inline-flex items-center gap-2 text-sm">
<span class="w-2 h-2 rounded-full bg-slate-400 animate-pulse"></span> thinking…
</span></div>`;
messagesEl.appendChild(typing);
messagesEl.scrollTop = messagesEl.scrollHeight;
sendBtn.disabled = true;
sendBtn.classList.add("opacity-60", "cursor-not-allowed");
try {
const res = await fetch(`${base}/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
const data = await res.json();
typing.remove();
// Defensive: if backend returns raw JSON in message, recompose from places.
let msg = data?.agent_reply?.message || "";
if (msg.trim().startsWith("[")) {
const places = data?.agent_reply?.places || [];
msg = places.length
? places
.map(
(p, i) =>
`${i + 1}. ${p.name || "—"} — ${p.address || "—"}${
p.rating != null ? ` (Rating ★ ${p.rating}, Reviews ${p.user_rating_count ?? "—"})` : ""
}${p.maps_url ? ` — ${p.maps_url}` : ""}\nlat,lng: ${p.latitude}, ${p.longitude}\n${
p.bounding_box
? `SW: (${p.bounding_box.south_west.lat}, ${p.bounding_box.south_west.lon}), NE: (${p.bounding_box.north_east.lat}, ${p.bounding_box.north_east.lon})`
: ""
}`
)
.join("\n\n")
: "No places found.";
}
msg = stripHeaders(msg); // strip ChatML/header tokens
renderMessage("assistant", msg);
renderPlaces(data?.agent_reply?.places || [], data);
conversation_history = data?.conversation_history || conversation_history;
} catch (err) {
console.error(err);
typing.remove();
renderMessage("assistant", `**Error:** ${err?.message || err}`);
showToast("Request failed — check console & CORS");
} finally {
sendBtn.disabled = false;
sendBtn.classList.remove("opacity-60", "cursor-not-allowed");
userInput.value = "";
}
}
// Handlers
chatForm.addEventListener("submit", (e) => {
e.preventDefault();
sendSingle();
});
// Welcome
renderMessage(
"assistant",
"Hi! I'm **Talk2Map**. One button does it all 👋\n\nTry:\n1. **best 5 hotels in Chennai**\n2. Fill a bounding box and press **Send** (no message) to list POIs inside.\n3. Fill both message + bbox to constrain results to that rectangle."
);
</script>
</body>
</html>
|