nikeshn commited on
Commit
3947185
Β·
verified Β·
1 Parent(s): 66c9713

Upload 5 files

Browse files
src/agentcore/access_routing.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic detection of e-resource access problems.
2
+
3
+ Access problems ("I can't access ScienceDirect", "OpenAthens login keeps
4
+ failing", "how do I access databases off campus") are routed straight to the
5
+ knowledge-base RAG path. Requests for a specific article's full text stay on
6
+ the full-text chain. Kept separate from constants.py so it has no dependencies
7
+ and can be tested on its own.
8
+ """
9
+ import re
10
+
11
+ # Unambiguous access/authentication cues. Context-dependent words (remote,
12
+ # VPN, off campus) only count next to an access or sign-in verb, so research
13
+ # topics such as "remote sensing" or "VPN security" are not misrouted.
14
+ ACCESS_PROBLEM_RE = re.compile(
15
+ r"\b("
16
+ r"openathens|single sign.?on"
17
+ r"|access (denied|error|issue|problem)s?"
18
+ r"|(asks?|asking|wants?) me to (pay|purchase|buy|subscribe)"
19
+ r"|(log(?:ging)?\s?(?:in|on)|sign(?:ing)?\s?in|sso)\W+(?:\w+\W+){0,4}(fail\w*|error|problem|issue|loop\w*|not working|keeps)"
20
+ r"|(off[\s-]?campus|remote(ly)?|from home|outside (the )?campus|vpn)\W+(?:\w+\W+){0,4}(access\w*|log(?:ging)?\s?(?:in|on)|sign(?:ing)?\s?in)"
21
+ r"|(access\w*|log(?:ging)?\s?(?:in|on)|sign(?:ing)?\s?in)\W+(?:\w+\W+){0,4}(off[\s-]?campus|remote(ly)?|from home|outside (the )?campus)"
22
+ r"|(link|database|platform|e-?resource)s?\W+(?:\w+\W+){0,3}(not working|broken|down|dead)"
23
+ r")\b",
24
+ re.IGNORECASE,
25
+ )
26
+
27
+ # "can't access X", "trouble logging in to X", "problem opening X"
28
+ ACCESS_FAIL_RE = re.compile(
29
+ r"\b(can.?t|cannot|unable to|not able to|couldn.?t|trouble|problems?|issues?|lost)\b"
30
+ r"\W+(?:\w+\W+){0,3}(access\w*|log(?:ging)?\s?(?:in|on)|sign(?:ing)?\s?in|connect\w*|open\w*)\b",
31
+ re.IGNORECASE,
32
+ )
33
+
34
+ ARTICLE_CUE_RE = re.compile(r"\b(pdf|full.?text|articles?|papers?|chapters?)\b", re.IGNORECASE)
35
+
36
+ # Extra tokens appended to the retrieval query so BM25 reliably surfaces the
37
+ # access-troubleshooting and remote-access chunks alongside any resource chunk.
38
+ ACCESS_RETRIEVAL_HINT = "access troubleshooting sign in remote access electronic resources"
39
+
40
+
41
+ def _is_access_problem(question: str) -> bool:
42
+ q = question or ""
43
+ if ACCESS_PROBLEM_RE.search(q):
44
+ return True
45
+ # "can't access ScienceDirect" is a platform problem;
46
+ # "can't access this article" is a full-text request.
47
+ return bool(ACCESS_FAIL_RE.search(q)) and not ARTICLE_CUE_RE.search(q)
src/agentcore/intents_library.py CHANGED
@@ -248,29 +248,39 @@ def _database_recommendation_answer(question: str) -> str:
248
  return answer
249
 
250
 
 
 
 
 
251
  def _fulltext_chain_answer(question: str) -> str:
252
  return (
253
- "<strong>πŸ“„ How to get full text for an article</strong><br><br>"
254
- "Try these routes to full text:<br><br>"
255
- "<strong>Step 1 β€” Search KU PRIMO</strong><br>"
256
- "Find the article in <a href=\"https://khalifa.primo.exlibrisgroup.com/discovery/search"
257
- "?vid=971KUOSTAR_INST:KU\" target=\"_blank\">KU Library Discovery</a>. "
258
  "If KU subscribes, you'll see a <em>Full Text Available</em> or <em>Online Access</em> link. "
259
- "Follow the access link and sign in through KU when prompted.<br><br>"
260
- "<strong>Step 2 β€” Try LibKey Nomad (browser extension)</strong><br>"
261
- "<a href=\"https://libkey.io/libraries/3025/\" target=\"_blank\">LibKey Nomad</a> is a free browser "
 
 
 
 
 
262
  "extension that detects articles you're viewing and fetches KU's full text automatically. "
263
- "Select Khalifa University after installation; support varies by website.<br><br>"
264
- "<strong>Step 3 β€” Try the publisher or open access</strong><br>"
265
  "Visit the DOI link directly. Many authors post their accepted manuscript on "
266
- "<a href=\"https://arxiv.org\" target=\"_blank\">arXiv</a>, "
267
- "<a href=\"https://www.researchgate.net\" target=\"_blank\">ResearchGate</a>, or their institutional page. "
268
- "<a href=\"https://openalex.org\" target=\"_blank\">OpenAlex</a> also links to many legal open-access PDFs.<br><br>"
269
- "<strong>Step 4 β€” Submit an Interlibrary Loan (ILL) request</strong><br>"
270
- "If none of the above work, request the article through Interlibrary Loan. Delivery depends on the supplying library and licence conditions. "
271
- "Submit here: <a href=\"https://library.ku.ac.ae/ill/\" target=\"_blank\">library.ku.ac.ae/ill/</a><br>"
 
272
  "Contact: <strong>Suaad Al Jneibi</strong> Β· "
273
- "<a href=\"mailto:suaad.aljneibi@ku.ac.ae\">suaad.aljneibi@ku.ac.ae</a> Β· +971 2 312 4278"
 
274
  )
275
 
276
 
@@ -329,5 +339,3 @@ def _library_follow_up(question: str) -> Tuple[str, List[dict]]:
329
  {"label": "KU library page for this topic", "question": "Open the KU library page for this topic"},
330
  ],
331
  )
332
-
333
-
 
248
  return answer
249
 
250
 
251
+ _PRIMO_URL = "https://khalifa.primo.exlibrisgroup.com/discovery/search?vid=971KUOSTAR_INST:KU"
252
+ _ERESOURCES_URL = "https://library.ku.ac.ae/eresources"
253
+
254
+
255
  def _fulltext_chain_answer(question: str) -> str:
256
  return (
257
+ "<strong>πŸ“„ How to get full text for an article</strong>"
258
+ '<ol class="lb-steps">'
259
+ "<li><strong>Search KU PRIMO</strong><br>"
260
+ f'Find the article in <a href="{_PRIMO_URL}" target="_blank">KU Library Discovery</a>. '
 
261
  "If KU subscribes, you'll see a <em>Full Text Available</em> or <em>Online Access</em> link. "
262
+ "Follow the access link and sign in through KU when prompted.</li>"
263
+ "<li><strong>Go through the KU E-Resources page</strong><br>"
264
+ "If PRIMO's link doesn't work, open the journal's database or publisher platform from "
265
+ f'<a href="{_ERESOURCES_URL}" target="_blank">KU E-Resources</a> '
266
+ "and search for the article there. Starting from this page routes you through KU sign-in, "
267
+ "which also fixes most off-campus access errors.</li>"
268
+ "<li><strong>Try LibKey Nomad (browser extension)</strong><br>"
269
+ '<a href="https://libkey.io/libraries/3025/" target="_blank">LibKey Nomad</a> is a free browser '
270
  "extension that detects articles you're viewing and fetches KU's full text automatically. "
271
+ "Select Khalifa University after installation; support varies by website.</li>"
272
+ "<li><strong>Try the publisher or open access</strong><br>"
273
  "Visit the DOI link directly. Many authors post their accepted manuscript on "
274
+ '<a href="https://arxiv.org" target="_blank">arXiv</a>, '
275
+ '<a href="https://www.researchgate.net" target="_blank">ResearchGate</a>, or their institutional page. '
276
+ '<a href="https://openalex.org" target="_blank">OpenAlex</a> also links to many legal open-access PDFs.</li>'
277
+ "<li><strong>Submit an Interlibrary Loan (ILL) request</strong><br>"
278
+ "If none of the above work, request the article through Interlibrary Loan. "
279
+ "Delivery depends on the supplying library and licence conditions. "
280
+ 'Submit here: <a href="https://library.ku.ac.ae/ill/" target="_blank">library.ku.ac.ae/ill/</a><br>'
281
  "Contact: <strong>Suaad Al Jneibi</strong> Β· "
282
+ '<a href="mailto:suaad.aljneibi@ku.ac.ae">suaad.aljneibi@ku.ac.ae</a> Β· +971 2 312 4278</li>'
283
+ "</ol>"
284
  )
285
 
286
 
 
339
  {"label": "KU library page for this topic", "question": "Open the KU library page for this topic"},
340
  ],
341
  )
 
 
src/agentcore/libcal.py CHANGED
@@ -1,5 +1,10 @@
1
- """LibCal client + formatting for live opening hours and events."""
 
 
 
 
2
  import asyncio
 
3
  import json
4
  import logging
5
  import re
@@ -26,6 +31,7 @@ _LIBCAL_LOC_HABSHAN = 25028
26
  _LIBCAL_IID = 3495
27
  _LIBCAL_EVENTS_CAL = 8398
28
  _UAE_TIMEZONE = timezone(timedelta(hours=4))
 
29
  _libcal_tokens: Dict[str, Dict[str, Any]] = {
30
  "hours": {"value": "", "expires_at": 0.0},
31
  "events": {"value": "", "expires_at": 0.0},
@@ -140,7 +146,7 @@ async def _libcal_fetch_hours() -> Optional[dict]:
140
  def _parse_libcal_time(raw: str) -> str:
141
  if not raw:
142
  return raw
143
- raw = str(raw).strip().replace("\u2013", "-").replace("–", "-")
144
  raw = re.sub(r"\s+", "", raw)
145
  raw = re.sub(r"(?i)(am|pm)$", lambda m: " " + m.group(1).upper(), raw)
146
  return raw
@@ -183,6 +189,14 @@ def _format_libcal_day(day_data: dict) -> str:
183
  return with_note("See hours page")
184
 
185
 
 
 
 
 
 
 
 
 
186
  async def _hours_answer() -> str:
187
  uae_now = datetime.now(_UAE_TIMEZONE)
188
  today_str = uae_now.strftime("%Y-%m-%d")
@@ -193,82 +207,59 @@ async def _hours_answer() -> str:
193
  return (
194
  "Here are the <strong>Khalifa University Library</strong> hours:<br><br>"
195
  "⚠️ Live hours are currently unavailable. Please check the official schedule:<br>"
196
- f'<a href="{LIBRARY_HOURS_URL}" target="_blank" '
197
- f'style="font-weight:700;color:#003366">{LIBRARY_HOURS_URL}</a><br><br>'
198
- "<strong>πŸ“ Contacts:</strong><br>"
199
- 'Main Campus Library Β· E Building Β· <a href="tel:+97123124604">+971 2 312 4604</a><br>'
200
- 'Habshan Library Β· SAN Campus Β· <a href="tel:+97123123160">+971 2 312 3160</a>'
201
  )
202
  location_labels = {
203
  "main_campus": "Main Campus Library",
204
  "habshan": "Habshan Library (SAN Campus)",
205
  }
206
- def _today_line(loc_name: str, loc_data: dict) -> str:
 
 
 
 
207
  dates = loc_data.get("dates", {})
208
  today_entry = dates.get(today_str, {})
209
  if not today_entry:
210
- return f"<em>See <a href='{LIBRARY_HOURS_URL}' target='_blank'>live hours</a> for today</em>"
211
  hours_str = _format_libcal_day(today_entry)
212
- is_closed = hours_str.lower().startswith("closed")
213
- colour = "#dc2626" if is_closed else "#16a34a"
214
- safe_hours = _escape(hours_str)
215
  return (
216
- f"πŸ“… <strong>Today ({today_name}):</strong> "
217
- f"<span style='color:{colour};font-weight:700'>{safe_hours}</span>"
218
  )
 
219
  def _week_table(loc_data: dict) -> str:
 
220
  dates = loc_data.get("dates", {})
221
- if not dates:
222
- return ""
223
  rows = ""
224
  for date_key in sorted(dates.keys())[:7]:
225
  try:
226
- from datetime import date as _date
227
- d = _date.fromisoformat(date_key)
228
- day_label = d.strftime("%a %d %b")
229
- is_today = date_key == today_str
230
  except ValueError:
231
  day_label = _escape(str(date_key))
232
- is_today = False
233
  hours_str = _format_libcal_day(dates[date_key])
234
- is_closed = hours_str.lower().startswith("closed")
235
- colour = "#dc2626" if is_closed else "#16a34a"
236
- weight = "700" if is_today else "400"
237
- bg = "#fffbeb" if is_today else "transparent"
238
- safe_hours = _escape(hours_str)
239
  rows += (
240
- f"<tr style='background:{bg}'>"
241
- f"<td style='padding:3px 12px 3px 0;color:#374151;font-weight:{weight}'>{day_label}</td>"
242
- f"<td style='padding:3px 0;font-weight:600;color:{colour}'>{safe_hours}</td>"
243
- f"</tr>"
244
  )
245
- if not rows:
246
- return ""
247
- return (
248
- "<table style='font-size:.84rem;border-collapse:collapse;width:100%;max-width:380px'>"
249
- + rows + "</table>"
250
- )
251
- answer = "Here are the <strong>Khalifa University Library</strong> live hours (UAE time, UTC+4):<br><br>"
252
  for key, label in location_labels.items():
253
  loc = hours_data.get(key)
 
254
  if not loc:
255
- answer += f"<strong>πŸ“ {label}</strong><br>Live hours unavailable; please check the official schedule below.<br><br>"
256
  continue
257
- answer += f"<strong>πŸ“ {label}</strong><br>"
258
- answer += _today_line(label, loc) + "<br>"
259
- week_tbl = _week_table(loc)
260
- if week_tbl:
261
- answer += week_tbl + "<br><br>"
262
- else:
263
- answer += "<br>"
264
  answer += (
265
- "⚠️ <strong>Hours may change during Ramadan, public holidays, and exam periods.</strong><br>"
266
- f'Always confirm at: <a href="{LIBRARY_HOURS_URL}" target="_blank" '
267
- f'style="font-weight:700;color:#003366">{LIBRARY_HOURS_URL}</a><br><br>'
268
- '<span style="font-size:.82rem;color:#6b7280">'
269
- 'Main Campus Library Β· E Building Β· <a href="tel:+97123124604">+971 2 312 4604</a><br>'
270
- 'Habshan Library Β· Building 5, SAN Campus Β· <a href="tel:+97123123160">+971 2 312 3160</a>'
271
- '</span>'
272
  )
273
  return answer
274
 
@@ -278,6 +269,44 @@ _libcal_events_cache: Dict[str, Any] = {}
278
 
279
  _LIBCAL_EVENTS_TTL = 30 * 60
280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
 
282
  async def _libcal_fetch_events(days: int = 30, limit: int = 10) -> Optional[list]:
283
  now = time.time()
@@ -301,8 +330,8 @@ async def _libcal_fetch_events(days: int = 30, limit: int = 10) -> Optional[list
301
  "iid": _LIBCAL_IID,
302
  "cal_id": _LIBCAL_EVENTS_CAL,
303
  "date": uae_now.strftime("%Y-%m-%d"),
304
- "days": max(1, min(int(days), 90)),
305
- "limit": max(1, min(int(limit), 50)),
306
  },
307
  headers={"Authorization": f"Bearer {token}"},
308
  )
@@ -330,13 +359,13 @@ async def _libcal_fetch_events(days: int = 30, limit: int = 10) -> Optional[list
330
  cat_str = _safe_str(cats)
331
  events.append({
332
  "id": e.get("id", ""),
333
- "title": _safe_str(e.get("title") or "Untitled Event"),
334
  "start": _safe_str(e.get("start") or ""),
335
  "end": _safe_str(e.get("end") or ""),
336
  "allDay": _libcal_bool(e.get("allday", e.get("allDay", False))),
337
- "location": _safe_str(e.get("location") or ""),
338
- "description": _safe_str(e.get("description") or e.get("summary") or "")[:300],
339
- "url": _safe_str(e.get("url") or ""),
340
  "registration": _libcal_bool(e.get("registration")) or _libcal_bool(e.get("seats")),
341
  "campus": _safe_str(e.get("campus") or ""),
342
  "category": cat_str,
@@ -356,9 +385,10 @@ def _libcal_bool(value: Any) -> bool:
356
  return bool(value)
357
 
358
 
359
- def _format_event_datetime(start: str, end: str, all_day: bool) -> str:
360
  if not start:
361
  return ""
 
362
  try:
363
  s = datetime.fromisoformat(start.replace("Z", "+00:00"))
364
  if all_day:
@@ -374,71 +404,67 @@ def _format_event_datetime(start: str, end: str, all_day: bool) -> str:
374
  end_str = e.strftime("%I:%M %p").lstrip("0")
375
  if e.date() != s.date():
376
  end_str = e.strftime("%a %d %b") + " Β· " + end_str
377
- return f"{date_str} Β· {time_str} – {end_str} (UAE, UTC+4)"
378
- return f"{date_str} Β· {time_str} (UAE, UTC+4)"
379
  except (ValueError, TypeError):
380
  return "Time unavailable β€” check the event page"
381
 
382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383
  async def _events_answer(days: int = 30) -> str:
384
- EVENTS_URL = "https://kustar.libcal.com/calendar/events"
385
  events = await _libcal_fetch_events(days=days, limit=15)
386
  if events is None:
387
  return (
388
  "<strong>πŸ“… Khalifa University Library Events</strong><br><br>"
389
  "Live event data is currently unavailable. Browse all upcoming events here:<br>"
390
- f'<a href="{EVENTS_URL}" target="_blank" '
391
- f'style="font-weight:700;color:#003366">{EVENTS_URL}</a>'
392
  )
393
- if len(events) == 0:
 
 
 
394
  return (
395
  "<strong>πŸ“… Khalifa University Library Events</strong><br><br>"
396
- f"No upcoming events found in the next {days} days.<br><br>"
397
- f'Browse the full calendar: <a href="{EVENTS_URL}" target="_blank"'
398
- f' style="font-weight:700;color:#003366">{EVENTS_URL}</a>'
399
- )
400
- answer = f"<strong>πŸ“… Upcoming Library Events, Workshops & Training</strong> (next {days} days)<br><br>"
401
- for ev in events[:10]:
402
- title = _escape(str(ev.get("title") or "Untitled Event"))
403
- when = _escape(_format_event_datetime(
404
- str(ev.get("start") or ""), str(ev.get("end") or ""), bool(ev.get("allDay"))
405
- ))
406
- location = _escape(str(ev.get("location") or ""))
407
- desc = _escape(str(ev.get("description") or ""))
408
- candidate_url = str(ev.get("url") or EVENTS_URL)
409
- try:
410
- parsed_url = urlsplit(candidate_url)
411
- if parsed_url.scheme != "https" or not parsed_url.netloc:
412
- candidate_url = EVENTS_URL
413
- except ValueError:
414
- candidate_url = EVENTS_URL
415
- url = _escape(candidate_url)
416
- reg = bool(ev.get("registration"))
417
- answer += (
418
- f'<div style="margin-bottom:12px;padding:10px 12px;border-left:3px solid #003366;'
419
- f'background:#f8fafc;border-radius:0 8px 8px 0">'
420
- f'<div style="font-weight:700;font-size:.88rem;color:#003366">'
421
- f'<a href="{url}" target="_blank" style="color:#003366;text-decoration:none">{title}</a></div>'
422
  )
423
- if when:
424
- answer += f'<div style="font-size:.80rem;color:#374151;margin-top:2px">πŸ• {when}</div>'
425
- if location:
426
- answer += f'<div style="font-size:.80rem;color:#374151">πŸ“ {location}</div>'
427
- if desc:
428
- answer += f'<div style="font-size:.78rem;color:#6b7280;margin-top:4px">{desc[:180]}{"…" if len(desc) > 180 else ""}</div>'
429
- if reg:
430
- answer += (
431
- f'<div style="margin-top:5px">'
432
- f'<a href="{url}" target="_blank" '
433
- f'style="font-size:.76rem;font-weight:700;color:#003366;'
434
- f'padding:3px 10px;border:1px solid #003366;border-radius:6px;text-decoration:none">'
435
- f'Register β†’</a></div>'
436
- )
437
- answer += '</div>'
438
- answer += (
439
- f'<br><a href="{EVENTS_URL}" target="_blank" '
440
- f'style="font-weight:700;color:#003366">View full library events calendar β†’</a>'
441
  )
442
- return answer
443
-
444
-
 
1
+ """LibCal client + formatting for live opening hours and events.
2
+
3
+ Rendering emits class names only (lb-hours-*, lb-event*); see rendering.py for
4
+ the styling contract.
5
+ """
6
  import asyncio
7
+ import html as _html
8
  import json
9
  import logging
10
  import re
 
31
  _LIBCAL_IID = 3495
32
  _LIBCAL_EVENTS_CAL = 8398
33
  _UAE_TIMEZONE = timezone(timedelta(hours=4))
34
+ _EVENTS_URL = "https://kustar.libcal.com/calendar/events"
35
  _libcal_tokens: Dict[str, Dict[str, Any]] = {
36
  "hours": {"value": "", "expires_at": 0.0},
37
  "events": {"value": "", "expires_at": 0.0},
 
146
  def _parse_libcal_time(raw: str) -> str:
147
  if not raw:
148
  return raw
149
+ raw = str(raw).strip().replace("–", "-").replace("–", "-")
150
  raw = re.sub(r"\s+", "", raw)
151
  raw = re.sub(r"(?i)(am|pm)$", lambda m: " " + m.group(1).upper(), raw)
152
  return raw
 
189
  return with_note("See hours page")
190
 
191
 
192
+ _HOURS_CONTACTS = (
193
+ '<div class="lb-muted lb-hours-contacts">'
194
+ 'Main Campus Library Β· E Building Β· <a href="tel:+97123124604">+971 2 312 4604</a><br>'
195
+ 'Habshan Library Β· Building 5, SAN Campus Β· <a href="tel:+97123123160">+971 2 312 3160</a>'
196
+ '</div>'
197
+ )
198
+
199
+
200
  async def _hours_answer() -> str:
201
  uae_now = datetime.now(_UAE_TIMEZONE)
202
  today_str = uae_now.strftime("%Y-%m-%d")
 
207
  return (
208
  "Here are the <strong>Khalifa University Library</strong> hours:<br><br>"
209
  "⚠️ Live hours are currently unavailable. Please check the official schedule:<br>"
210
+ f'<a href="{LIBRARY_HOURS_URL}" target="_blank"><strong>{LIBRARY_HOURS_URL}</strong></a>'
211
+ + _HOURS_CONTACTS
 
 
 
212
  )
213
  location_labels = {
214
  "main_campus": "Main Campus Library",
215
  "habshan": "Habshan Library (SAN Campus)",
216
  }
217
+
218
+ def _state(hours_str: str) -> str:
219
+ return "closed" if hours_str.lower().startswith("closed") else "open"
220
+
221
+ def _today_line(loc_data: dict) -> str:
222
  dates = loc_data.get("dates", {})
223
  today_entry = dates.get(today_str, {})
224
  if not today_entry:
225
+ return f'<em>See <a href="{LIBRARY_HOURS_URL}" target="_blank">live hours</a> for today</em>'
226
  hours_str = _format_libcal_day(today_entry)
 
 
 
227
  return (
228
+ f'<div class="lb-hours-today-line">πŸ“… <strong>Today ({today_name}):</strong> '
229
+ f'<span class="lb-hours-status lb-hours-status--{_state(hours_str)}">{_escape(hours_str)}</span></div>'
230
  )
231
+
232
  def _week_table(loc_data: dict) -> str:
233
+ from datetime import date as _date
234
  dates = loc_data.get("dates", {})
 
 
235
  rows = ""
236
  for date_key in sorted(dates.keys())[:7]:
237
  try:
238
+ day_label = _date.fromisoformat(date_key).strftime("%a %d %b")
 
 
 
239
  except ValueError:
240
  day_label = _escape(str(date_key))
 
241
  hours_str = _format_libcal_day(dates[date_key])
242
+ row_class = ' class="lb-hours-today"' if date_key == today_str else ""
 
 
 
 
243
  rows += (
244
+ f"<tr{row_class}>"
245
+ f'<td class="lb-hours-day">{day_label}</td>'
246
+ f'<td class="lb-hours-time lb-hours-status--{_state(hours_str)}">{_escape(hours_str)}</td>'
247
+ "</tr>"
248
  )
249
+ return f'<table class="lb-hours-table"><tbody>{rows}</tbody></table>' if rows else ""
250
+
251
+ answer = "Here are the <strong>Khalifa University Library</strong> live hours (UAE time, UTC+4):"
 
 
 
 
252
  for key, label in location_labels.items():
253
  loc = hours_data.get(key)
254
+ answer += f'<div class="lb-hours-location"><div class="lb-hours-heading">πŸ“ {label}</div>'
255
  if not loc:
256
+ answer += "Live hours unavailable; please check the official schedule below.</div>"
257
  continue
258
+ answer += _today_line(loc) + _week_table(loc) + "</div>"
 
 
 
 
 
 
259
  answer += (
260
+ '<div class="lb-note">⚠️ <strong>Hours may change during Ramadan, public holidays, and exam periods.</strong> '
261
+ f'Always confirm at <a href="{LIBRARY_HOURS_URL}" target="_blank">{LIBRARY_HOURS_URL}</a></div>'
262
+ + _HOURS_CONTACTS
 
 
 
 
263
  )
264
  return answer
265
 
 
269
 
270
  _LIBCAL_EVENTS_TTL = 30 * 60
271
 
272
+ _TAG_RE = re.compile(r"<[^>]+>")
273
+ _BLOCK_TAG_RE = re.compile(r"</?(?:p|br|div|li|h\d)\b[^>]*>", re.IGNORECASE)
274
+
275
+
276
+ def _plain_text(value: str) -> str:
277
+ """LibCal descriptions are rich-text HTML; reduce them to clean prose."""
278
+ text = _TAG_RE.sub("", _BLOCK_TAG_RE.sub(" ", value or ""))
279
+ text = _html.unescape(text).replace("\xa0", " ")
280
+ return re.sub(r"\s+", " ", text).strip()
281
+
282
+
283
+ def _truncate_words(text: str, limit: int = 200) -> str:
284
+ if len(text) <= limit:
285
+ return text
286
+ return text[:limit].rsplit(" ", 1)[0].rstrip(" ,;:.-–") + "…"
287
+
288
+
289
+ def _event_public_url(e: dict) -> str:
290
+ """LibCal 1.1 returns url as {"public": ..., "admin": ...}; never expose admin."""
291
+ url = e.get("url")
292
+ if isinstance(url, dict):
293
+ url = url.get("public") or ""
294
+ url = str(url or "").strip()
295
+ if not url and e.get("id"):
296
+ url = f"{_LIBCAL_BASE}/event/{e['id']}"
297
+ return url
298
+
299
+
300
+ def _event_end(ev: dict) -> Optional[datetime]:
301
+ raw = str(ev.get("end") or ev.get("start") or "")
302
+ try:
303
+ dt = datetime.fromisoformat(raw.replace("Z", "+00:00"))
304
+ except ValueError:
305
+ return None
306
+ if ev.get("allDay"):
307
+ return datetime.combine(dt.date(), datetime.max.time(), _UAE_TIMEZONE)
308
+ return dt.replace(tzinfo=_UAE_TIMEZONE) if dt.tzinfo is None else dt
309
+
310
 
311
  async def _libcal_fetch_events(days: int = 30, limit: int = 10) -> Optional[list]:
312
  now = time.time()
 
330
  "iid": _LIBCAL_IID,
331
  "cal_id": _LIBCAL_EVENTS_CAL,
332
  "date": uae_now.strftime("%Y-%m-%d"),
333
+ "days": days,
334
+ "limit": limit,
335
  },
336
  headers={"Authorization": f"Bearer {token}"},
337
  )
 
359
  cat_str = _safe_str(cats)
360
  events.append({
361
  "id": e.get("id", ""),
362
+ "title": _plain_text(_safe_str(e.get("title") or "Untitled Event")),
363
  "start": _safe_str(e.get("start") or ""),
364
  "end": _safe_str(e.get("end") or ""),
365
  "allDay": _libcal_bool(e.get("allday", e.get("allDay", False))),
366
+ "location": _plain_text(_safe_str(e.get("location") or "")),
367
+ "description": _plain_text(_safe_str(e.get("description") or e.get("summary") or ""))[:600],
368
+ "url": _event_public_url(e),
369
  "registration": _libcal_bool(e.get("registration")) or _libcal_bool(e.get("seats")),
370
  "campus": _safe_str(e.get("campus") or ""),
371
  "category": cat_str,
 
385
  return bool(value)
386
 
387
 
388
+ def _format_event_datetime(start: str, end: str, all_day: bool, with_tz: bool = True) -> str:
389
  if not start:
390
  return ""
391
+ suffix = " (UAE, UTC+4)" if with_tz else ""
392
  try:
393
  s = datetime.fromisoformat(start.replace("Z", "+00:00"))
394
  if all_day:
 
404
  end_str = e.strftime("%I:%M %p").lstrip("0")
405
  if e.date() != s.date():
406
  end_str = e.strftime("%a %d %b") + " Β· " + end_str
407
+ return f"{date_str} Β· {time_str} – {end_str}{suffix}"
408
+ return f"{date_str} Β· {time_str}{suffix}"
409
  except (ValueError, TypeError):
410
  return "Time unavailable β€” check the event page"
411
 
412
 
413
+ def _render_event(ev: dict, now: datetime) -> str:
414
+ url = str(ev.get("url") or "")
415
+ try:
416
+ parsed = urlsplit(url)
417
+ if parsed.scheme != "https" or not parsed.netloc:
418
+ url = _EVENTS_URL
419
+ except ValueError:
420
+ url = _EVENTS_URL
421
+ url = _escape(url)
422
+ title = _escape(str(ev.get("title") or "Untitled event"))
423
+ when = _format_event_datetime(
424
+ str(ev.get("start") or ""), str(ev.get("end") or ""), bool(ev.get("allDay")), with_tz=False
425
+ )
426
+ today = ' <span class="lb-badge">Today</span>' if when.startswith(now.strftime("%a %d %b")) else ""
427
+ location = _escape(str(ev.get("location") or ""))
428
+ desc = _escape(_truncate_words(str(ev.get("description") or "")))
429
+ parts = [
430
+ '<div class="lb-event">'
431
+ f'<div class="lb-event-title"><a href="{url}" target="_blank">{title}</a>{today}</div>'
432
+ ]
433
+ if when:
434
+ parts.append(f'<div class="lb-event-meta">πŸ• {_escape(when)}</div>')
435
+ if location:
436
+ parts.append(f'<div class="lb-event-meta">πŸ“ {location}</div>')
437
+ if desc:
438
+ parts.append(f'<div class="lb-event-desc">{desc}</div>')
439
+ if ev.get("registration"):
440
+ parts.append(f'<a class="lb-btn" href="{url}" target="_blank">Register β†’</a>')
441
+ parts.append("</div>")
442
+ return "".join(parts)
443
+
444
+
445
  async def _events_answer(days: int = 30) -> str:
 
446
  events = await _libcal_fetch_events(days=days, limit=15)
447
  if events is None:
448
  return (
449
  "<strong>πŸ“… Khalifa University Library Events</strong><br><br>"
450
  "Live event data is currently unavailable. Browse all upcoming events here:<br>"
451
+ f'<a href="{_EVENTS_URL}" target="_blank">{_EVENTS_URL}</a>'
 
452
  )
453
+ now = datetime.now(_UAE_TIMEZONE)
454
+ # LibCal's date parameter returns the whole first day, including sessions that have ended.
455
+ upcoming = [ev for ev in events if (_event_end(ev) or now) >= now]
456
+ if not upcoming:
457
  return (
458
  "<strong>πŸ“… Khalifa University Library Events</strong><br><br>"
459
+ f"No upcoming events in the next {days} days.<br><br>"
460
+ f'Browse the full calendar: <a href="{_EVENTS_URL}" target="_blank">{_EVENTS_URL}</a>'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
  )
462
+ items = "".join(_render_event(ev, now) for ev in upcoming[:8])
463
+ return (
464
+ '<div class="lb-events">'
465
+ "<strong>πŸ“… Upcoming library events &amp; workshops</strong>"
466
+ f'<div class="lb-muted">Next {days} days Β· all times are UAE time (UTC+4)</div>'
467
+ f"{items}"
468
+ f'<a class="lb-events-all" href="{_EVENTS_URL}" target="_blank">View the full events calendar β†’</a>'
469
+ "</div>"
 
 
 
 
 
 
 
 
 
 
470
  )
 
 
 
src/agentcore/orchestrator.py CHANGED
@@ -42,6 +42,7 @@ from src.agentcore.constants import (
42
  THESES_RE,
43
  _INJECTION_RE,
44
  )
 
45
  from src.agentcore.utils import (
46
  _escape,
47
  _isbn_search_value,
@@ -301,6 +302,69 @@ def _log_agent_query(question: str, response: AgentResponse, start_time: float)
301
  pass
302
 
303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
  async def _agent_query_inner(
305
  question: str,
306
  history,
@@ -443,6 +507,18 @@ async def _agent_query_inner(
443
  follow_up_suggestions=follow_up_suggestions,
444
  )
445
 
 
 
 
 
 
 
 
 
 
 
 
 
446
  if _is_database_recommendation_question(question):
447
  answer = _database_recommendation_answer(question)
448
  answer += _contact_footer_for_query(question, None)
@@ -696,49 +772,7 @@ async def _agent_query_inner(
696
  )
697
 
698
  if intent == "library_info":
699
- rag_results = []
700
- try:
701
- from app import get_rag_service
702
- rag_results = await get_rag_service().hybrid_search(_rag_retrieval_query(question, history), top_k=4)
703
- except Exception as e:
704
- logger.error(f"RAG search failed: {e}")
705
-
706
- if not rag_results:
707
- answer = (
708
- "I couldn't find specific information on that in my knowledge base.<br><br>"
709
- "Please contact our librarians directly:<br>"
710
- 'πŸ“§ <a href="mailto:libse@ku.ac.ae">libse@ku.ac.ae</a><br>'
711
- f'πŸ”— <a href="{ASK_LIBRARIAN_URL}" target="_blank">Ask a Librarian</a>'
712
- )
713
- answer += _source_badge("ku_library", ASK_LIBRARIAN_URL)
714
- sources = []
715
- tools_used = ["rag_no_results"]
716
- thought = _thought_block("library_info", "rag_no_results", question,
717
- "No matching content was found β€” I am directing you to Ask a Librarian.")
718
- else:
719
- answer = await _rag_answer(question, rag_results, history, model)
720
- answer += _source_badge("rag", "https://library.ku.ac.ae/")
721
- sources = list({
722
- r["source"]: {"title": r.get("title", "Library KB"), "url": r["source"]}
723
- for r in rag_results if r.get("source")
724
- }.values())
725
- retrieval_mode = rag_results[0].get("retrieval_mode", "hybrid")
726
- tools_used = ["rag_hybrid_search" if retrieval_mode == "hybrid" else "rag_keyword_search"]
727
- thought = _thought_block("rag_search", tools_used[0], question,
728
- f"The {retrieval_mode} search returned {len(rag_results)} matching passages.")
729
-
730
- follow_up_question, follow_up_suggestions = _library_follow_up(question)
731
- return AgentResponse(
732
- answer=thought + answer,
733
- intent="library_info",
734
- tools_used=tools_used,
735
- sources=sources,
736
- ask_librarian=not bool(rag_results),
737
- model_used=model,
738
- response_time=time.time() - start_time,
739
- follow_up_question=follow_up_question,
740
- follow_up_suggestions=follow_up_suggestions,
741
- )
742
 
743
  if intent in ("search_academic", "search_medical"):
744
  topic = await _extract_topic(question, model)
 
42
  THESES_RE,
43
  _INJECTION_RE,
44
  )
45
+ from src.agentcore.access_routing import ACCESS_RETRIEVAL_HINT, _is_access_problem
46
  from src.agentcore.utils import (
47
  _escape,
48
  _isbn_search_value,
 
302
  pass
303
 
304
 
305
+ async def _library_rag_response(
306
+ question: str,
307
+ history,
308
+ model: str,
309
+ start_time: float,
310
+ *,
311
+ retrieval_hint: str = "",
312
+ top_k: int = 4,
313
+ extra_tools: Tuple[str, ...] = (),
314
+ ) -> AgentResponse:
315
+ """Answer a library_info question from the knowledge base (RAG).
316
+
317
+ Used for classifier-routed library_info questions and, with a retrieval
318
+ hint, for access problems detected before classification.
319
+ """
320
+ query = _rag_retrieval_query(question, history)
321
+ if retrieval_hint:
322
+ query = f"{query} {retrieval_hint}"
323
+ rag_results = []
324
+ try:
325
+ from app import get_rag_service
326
+ rag_results = await get_rag_service().hybrid_search(query, top_k=top_k)
327
+ except Exception as e:
328
+ logger.error(f"RAG search failed: {e}")
329
+
330
+ if not rag_results:
331
+ answer = (
332
+ "I couldn't find specific information on that in my knowledge base.<br><br>"
333
+ "Please contact our librarians directly:<br>"
334
+ 'πŸ“§ <a href="mailto:libse@ku.ac.ae">libse@ku.ac.ae</a><br>'
335
+ f'πŸ”— <a href="{ASK_LIBRARIAN_URL}" target="_blank">Ask a Librarian</a>'
336
+ )
337
+ answer += _source_badge("ku_library", ASK_LIBRARIAN_URL)
338
+ sources = []
339
+ tools_used = ["rag_no_results"]
340
+ thought = _thought_block("library_info", "rag_no_results", question,
341
+ "No matching content was found β€” I am directing you to Ask a Librarian.")
342
+ else:
343
+ answer = await _rag_answer(question, rag_results, history, model)
344
+ answer += _source_badge("rag", "https://library.ku.ac.ae/")
345
+ sources = list({
346
+ r["source"]: {"title": r.get("title", "Library KB"), "url": r["source"]}
347
+ for r in rag_results if r.get("source")
348
+ }.values())
349
+ retrieval_mode = rag_results[0].get("retrieval_mode", "hybrid")
350
+ tools_used = ["rag_hybrid_search" if retrieval_mode == "hybrid" else "rag_keyword_search"]
351
+ thought = _thought_block("rag_search", tools_used[0], question,
352
+ f"The {retrieval_mode} search returned {len(rag_results)} matching passages.")
353
+
354
+ follow_up_question, follow_up_suggestions = _library_follow_up(question)
355
+ return AgentResponse(
356
+ answer=thought + answer,
357
+ intent="library_info",
358
+ tools_used=list(extra_tools) + tools_used,
359
+ sources=sources,
360
+ ask_librarian=not bool(rag_results),
361
+ model_used=model,
362
+ response_time=time.time() - start_time,
363
+ follow_up_question=follow_up_question,
364
+ follow_up_suggestions=follow_up_suggestions,
365
+ )
366
+
367
+
368
  async def _agent_query_inner(
369
  question: str,
370
  history,
 
507
  follow_up_suggestions=follow_up_suggestions,
508
  )
509
 
510
+ # ── E-resource access problems β†’ knowledge base ───────────────────────────
511
+ # Checked before the database-recommendation and full-text handlers, whose
512
+ # regexes would otherwise catch "access to databases off campus" or
513
+ # "can't access ScienceDirect". Skips the LLM classifier entirely.
514
+ if _is_access_problem(question):
515
+ _safe_metrics_bucket("intents", "access_problem")
516
+ return await _library_rag_response(
517
+ question, history, model, start_time,
518
+ retrieval_hint=ACCESS_RETRIEVAL_HINT, top_k=5,
519
+ extra_tools=("access_problem_rag",),
520
+ )
521
+
522
  if _is_database_recommendation_question(question):
523
  answer = _database_recommendation_answer(question)
524
  answer += _contact_footer_for_query(question, None)
 
772
  )
773
 
774
  if intent == "library_info":
775
+ return await _library_rag_response(question, history, model, start_time)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
776
 
777
  if intent in ("search_academic", "search_medical"):
778
  topic = await _extract_topic(question, model)
src/agentcore/rendering.py CHANGED
@@ -1,4 +1,13 @@
1
- """HTML fragment renderers: source badges, reasoning trace blocks, AI-tools footer, contacts."""
 
 
 
 
 
 
 
 
 
2
  import asyncio
3
  import html
4
  import json
@@ -35,29 +44,27 @@ from src.agentcore.utils import (
35
 
36
  logger = logging.getLogger(__name__)
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  def _source_badge(source: str, url: str = "") -> str:
39
- styles = {
40
- "rag": ("πŸ“–", "KU Library Knowledge Base", "#fef3c7", "#92400e"),
41
- "primo": ("πŸ“š", "KU Library PRIMO", "#eff6ff", "#1e40af"),
42
- "semantic": ("πŸŽ“", "Semantic Scholar", "#f0fdf4", "#166534"),
43
- "consensus_badge": ("🧬", "Consensus", "#fdf4ff", "#86198f"),
44
- "semantic_badge": ("πŸŽ“", "Semantic Scholar", "#f0fdf4", "#166534"),
45
- "pubmed": ("πŸ₯", "PubMed", "#d1fae5", "#065f46"),
46
- "web": ("🌐", "Web Search", "#f5f3ff", "#4c1d95"),
47
- "web_live": ("🌐", "Web Search · Live", "#fdf4ff", "#86198f"),
48
- "libbee": ("🐝", "LibBee", "#fef9c3", "#713f12"),
49
- "ku_library": ("πŸ“‹", "KU Library", "#eff6ff", "#1e40af"),
50
- "llm": ("πŸ€–", "AI response Β· web not verified", "#f3f4f6", "#374151"),
51
- }
52
- icon, label, bg, fg = styles.get(source, ("ℹ️", source, "#f3f4f6", "#374151"))
53
- inner = f"{icon} Source: {label}"
54
  if url:
55
- inner = f'<a href="{_escape(url)}" target="_blank" style="color:{fg};text-decoration:none">{inner}</a>'
56
- return (
57
- f'<div style="margin-top:10px;display:inline-flex;align-items:center;gap:5px;'
58
- f'padding:4px 10px;background:{bg};color:{fg};border-radius:20px;'
59
- f'font-size:.72rem;font-weight:600;border:1px solid {fg}33">{inner}</div>'
60
- )
61
 
62
 
63
  def _tool_urls(context: SearchContextPayload) -> Dict[str, str]:
@@ -172,16 +179,13 @@ def _thought_block(intent: str, tool: str, question: str, extra: str = "") -> st
172
  if extra:
173
  reasoning += " " + extra
174
  return (
175
- f'<details style="margin:0 0 12px 0;border:1px solid #e5e7eb;border-radius:10px;'
176
- f'background:#fafafa;overflow:hidden">'
177
- f'<summary style="padding:8px 12px;cursor:pointer;font-size:.75rem;font-weight:700;'
178
- f'color:#6b7280;list-style:none;display:flex;align-items:center;gap:5px">'
179
- f'<span>{icon}</span> My approach β€” click to see</summary>'
180
- f'<div style="padding:4px 12px 10px 12px;font-size:.79rem;line-height:1.7;border-top:1px solid #e5e7eb">'
181
  f'<strong>Question:</strong> {_escape(question)}<br>'
182
  f'<strong>Classified as:</strong> {label}<br>'
183
  f'<strong>How I answered:</strong> {reasoning}'
184
- f'</div></details>'
185
  )
186
 
187
 
@@ -216,32 +220,47 @@ def _search_trace_block(question: str, context: SearchContextPayload) -> str:
216
  if context.intent == "search_medical" and context.source != "pubmed":
217
  reasoning += " For medical topics, PubMed and Embase are also recommended."
218
  block = (
219
- f'<details style="margin:0 0 14px 0;border:1px solid #dbe4ff;border-radius:12px;background:#f8fbff;overflow:hidden">'
220
- f'<summary style="padding:10px 14px;cursor:pointer;font-size:.8rem;font-weight:700;color:#1e40af;list-style:none;display:flex;align-items:center;gap:6px">'
221
- f'<span style="font-size:.9rem">πŸ”</span> How I searched β€” click to expand'
222
- f'</summary>'
223
- f'<div style="padding:4px 14px 12px 14px;font-size:.82rem;line-height:1.7;border-top:1px solid #dbe4ff">'
224
  f'<strong>Your question:</strong> {_escape(question)}<br>'
225
  f'<strong>Interpreted topic:</strong> {topic}<br>'
226
  )
227
  if primo_boolean:
228
  block += (
229
  f'<strong>Prepared query for {source_label}:</strong><br>'
230
- f'<code style="display:block;margin:4px 0;padding:6px 10px;background:#1a1a2e;color:#C8A951;'
231
- f'border-radius:7px;font-size:.78rem;word-break:break-all">{primo_boolean}</code>'
232
  )
233
  block += f'<strong>Reasoning:</strong> {reasoning}<br>'
234
- block += '<span style="color:#5b21b6;font-size:.78rem">✨ AI research tools for deeper exploration are listed at the end of this answer.</span>'
235
  block += '</div></details>'
236
  return block
237
 
238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  def _ai_tools_footer(context):
240
  from urllib.parse import quote as _q
241
 
242
  ai_q = _q(context.ai_tool_query or context.display_topic or context.topic)
243
  bool_q = context.primo_boolean_query or ""
244
- primo_url = _primo_clean_url(context)
245
  primo_ai = PRIMO_AI_URL + ai_q
246
  is_med = context.intent == "search_medical"
247
  pubmed_url = _shared_build_pubmed_url(
@@ -263,208 +282,26 @@ def _ai_tools_footer(context):
263
  if is_med and pubmed_url:
264
  platforms.append(("PubMed", pubmed_url, "pubmed"))
265
 
266
- _SVGS = {
267
- "bee": (
268
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="16" height="16" style="flex-shrink:0">'
269
- '<ellipse cx="5.5" cy="9" rx="5" ry="2.5" fill="#a8d4f0" opacity=".85"/>'
270
- '<ellipse cx="14.5" cy="9" rx="5" ry="2.5" fill="#a8d4f0" opacity=".85"/>'
271
- '<ellipse cx="10" cy="13" rx="5" ry="6" fill="#1a3a6b"/>'
272
- '<ellipse cx="10" cy="15" rx="3" ry="1.5" fill="#243f7a"/>'
273
- '<circle cx="10" cy="8" r="5" fill="#1a3a6b"/>'
274
- '<rect x="6" y="6.5" width="8" height="3.5" rx="1.5" fill="#001a40"/>'
275
- '<ellipse cx="8.2" cy="8.2" rx="1.5" ry="1.2" fill="#00ccee" opacity=".9"/>'
276
- '<ellipse cx="11.8" cy="8.2" rx="1.5" ry="1.2" fill="#00ccee" opacity=".9"/>'
277
- '<path d="M8 10 Q10 11.5 12 10" fill="none" stroke="#00ccee" stroke-width=".8" stroke-linecap="round"/>'
278
- '<line x1="8.5" y1="3.5" x2="6.5" y2="1.5" stroke="#1a3a6b" stroke-width="1.2" stroke-linecap="round"/>'
279
- '<circle cx="6.5" cy="1.5" r="1.2" fill="#00ccee" opacity=".8"/>'
280
- '<line x1="11.5" y1="3.5" x2="13.5" y2="1.5" stroke="#1a3a6b" stroke-width="1.2" stroke-linecap="round"/>'
281
- '<ellipse cx="13.5" cy="1.2" rx="1.5" ry="1.8" fill="#e8e8e8" stroke="#aaa" stroke-width=".5"/>'
282
- '<text x="10" y="17.5" font-family="Arial,sans-serif" font-size="3" font-weight="bold" fill="#C8A951" text-anchor="middle">LB</text>'
283
- '</svg>'
284
- ),
285
- "book": (
286
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" style="flex-shrink:0">'
287
- '<rect x="2" y="2" width="9" height="12" rx="1" fill="#2563eb"/>'
288
- '<rect x="3" y="2" width="1.5" height="12" fill="#1d4ed8"/>'
289
- '<rect x="4" y="4" width="5" height="1" rx=".5" fill="#bfdbfe"/>'
290
- '<rect x="4" y="6" width="5" height="1" rx=".5" fill="#bfdbfe"/>'
291
- '<rect x="4" y="8" width="3" height="1" rx=".5" fill="#bfdbfe"/>'
292
- '<rect x="11" y="3" width="3" height="10" rx="1" fill="#1e40af"/>'
293
- '</svg>'
294
- ),
295
- "microscope": (
296
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" style="flex-shrink:0">'
297
- '<rect x="7" y="1" width="2" height="5" rx="1" fill="#6b7280"/>'
298
- '<ellipse cx="8" cy="1.5" rx="2.5" ry="1.5" fill="#9ca3af"/>'
299
- '<rect x="6.5" y="5" width="3" height="5" rx=".5" fill="#374151"/>'
300
- '<rect x="5" y="9.5" width="6" height="1.5" rx=".5" fill="#374151"/>'
301
- '<rect x="3" y="13" width="10" height="1.5" rx=".5" fill="#374151"/>'
302
- '<line x1="8" y1="11" x2="8" y2="13" stroke="#374151" stroke-width="1.5"/>'
303
- '<circle cx="8" cy="6" r="1.5" fill="#60a5fa" opacity=".8"/>'
304
- '</svg>'
305
- ),
306
- "circuit": (
307
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" style="flex-shrink:0">'
308
- '<rect x="1" y="1" width="14" height="14" rx="2" fill="#1e293b"/>'
309
- '<circle cx="4" cy="4" r="1.5" fill="#22d3ee"/>'
310
- '<circle cx="12" cy="4" r="1.5" fill="#22d3ee"/>'
311
- '<circle cx="4" cy="12" r="1.5" fill="#22d3ee"/>'
312
- '<circle cx="12" cy="12" r="1.5" fill="#22d3ee"/>'
313
- '<circle cx="8" cy="8" r="2" fill="#06b6d4"/>'
314
- '<line x1="4" y1="4" x2="8" y2="8" stroke="#22d3ee" stroke-width=".8"/>'
315
- '<line x1="12" y1="4" x2="8" y2="8" stroke="#22d3ee" stroke-width=".8"/>'
316
- '<line x1="4" y1="12" x2="8" y2="8" stroke="#22d3ee" stroke-width=".8"/>'
317
- '<line x1="12" y1="12" x2="8" y2="8" stroke="#22d3ee" stroke-width=".8"/>'
318
- '</svg>'
319
- ),
320
- "leaf": (
321
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" style="flex-shrink:0">'
322
- '<path d="M8 14 C8 14 2 10 2 5 C2 2 5 1 8 1 C11 1 14 2 14 5 C14 10 8 14 8 14Z" fill="#16a34a"/>'
323
- '<line x1="8" y1="1" x2="8" y2="14" stroke="#bbf7d0" stroke-width=".8"/>'
324
- '<line x1="8" y1="5" x2="5" y2="7" stroke="#bbf7d0" stroke-width=".6"/>'
325
- '<line x1="8" y1="7" x2="5" y2="9" stroke="#bbf7d0" stroke-width=".6"/>'
326
- '<line x1="8" y1="5" x2="11" y2="7" stroke="#bbf7d0" stroke-width=".6"/>'
327
- '<line x1="8" y1="7" x2="11" y2="9" stroke="#bbf7d0" stroke-width=".6"/>'
328
- '</svg>'
329
- ),
330
- "gear": (
331
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" style="flex-shrink:0">'
332
- '<path d="M6.5 1h3l.5 1.5a5 5 0 011.2.7l1.5-.5 1.5 2.6-1.2 1a5 5 0 010 1.4l1.2 1-1.5 2.6-1.5-.5a5 5 0 01-1.2.7L9.5 15h-3l-.5-1.5a5 5 0 01-1.2-.7l-1.5.5L1.8 10.8l1.2-1a5 5 0 010-1.4l-1.2-1L3.3 4.8l1.5.5A5 5 0 016 4.5L6.5 1z" fill="#64748b"/>'
333
- '<circle cx="8" cy="8" r="2.5" fill="#f1f5f9"/>'
334
- '<circle cx="8" cy="8" r="1.2" fill="#64748b"/>'
335
- '</svg>'
336
- ),
337
- "chart": (
338
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" style="flex-shrink:0">'
339
- '<rect x="1" y="1" width="14" height="14" rx="1.5" fill="#f0fdf4"/>'
340
- '<rect x="3" y="9" width="2" height="5" rx=".5" fill="#16a34a"/>'
341
- '<rect x="7" y="6" width="2" height="8" rx=".5" fill="#15803d"/>'
342
- '<rect x="11" y="3" width="2" height="11" rx=".5" fill="#166534"/>'
343
- '<line x1="1" y1="13.5" x2="15" y2="13.5" stroke="#166534" stroke-width=".8"/>'
344
- '</svg>'
345
- ),
346
- "atom": (
347
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" style="flex-shrink:0">'
348
- '<ellipse cx="8" cy="8" rx="7" ry="3" fill="none" stroke="#7c3aed" stroke-width=".9"/>'
349
- '<ellipse cx="8" cy="8" rx="7" ry="3" fill="none" stroke="#7c3aed" stroke-width=".9" transform="rotate(60 8 8)"/>'
350
- '<ellipse cx="8" cy="8" rx="7" ry="3" fill="none" stroke="#7c3aed" stroke-width=".9" transform="rotate(120 8 8)"/>'
351
- '<circle cx="8" cy="8" r="1.8" fill="#7c3aed"/>'
352
- '</svg>'
353
- ),
354
- "medical": (
355
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" style="flex-shrink:0">'
356
- '<rect x="1" y="1" width="14" height="14" rx="2" fill="#dc2626"/>'
357
- '<rect x="6.5" y="3" width="3" height="10" rx="1" fill="white"/>'
358
- '<rect x="3" y="6.5" width="10" height="3" rx="1" fill="white"/>'
359
- '</svg>'
360
- ),
361
- "wrench": (
362
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" style="flex-shrink:0">'
363
- '<path d="M13 2a3 3 0 00-3 3c0 .4.1.8.2 1.1L2.6 13.7a1 1 0 001.4 1.4L11.7 7.8c.3.1.7.2 1.1.2a3 3 0 000-6z" fill="#d97706"/>'
364
- '<circle cx="12" cy="4" r="1.2" fill="#fef3c7"/>'
365
- '</svg>'
366
- ),
367
- "primo": (
368
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" style="flex-shrink:0">'
369
- '<rect x="1" y="1" width="14" height="14" rx="2" fill="#003366"/>'
370
- '<rect x="3" y="4" width="10" height="1.5" rx=".5" fill="#C8A951"/>'
371
- '<rect x="3" y="7" width="7" height="1.5" rx=".5" fill="white" opacity=".9"/>'
372
- '<rect x="3" y="10" width="9" height="1.5" rx=".5" fill="white" opacity=".7"/>'
373
- '<circle cx="12" cy="11" r="2.5" fill="#C8A951"/>'
374
- '<line x1="11" y1="11" x2="13" y2="11" stroke="#003366" stroke-width=".8"/>'
375
- '<line x1="12" y1="10" x2="12" y2="12" stroke="#003366" stroke-width=".8"/>'
376
- '</svg>'
377
- ),
378
- "scopus": (
379
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" style="flex-shrink:0">'
380
- '<rect x="1" y="1" width="14" height="14" rx="2" fill="#e8650a"/>'
381
- '<text x="8" y="11.5" font-family="Arial,sans-serif" font-size="8" font-weight="bold" fill="white" text-anchor="middle">Sc</text>'
382
- '</svg>'
383
- ),
384
- "ebsco": (
385
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" style="flex-shrink:0">'
386
- '<rect x="1" y="1" width="14" height="14" rx="2" fill="#00427a"/>'
387
- '<text x="8" y="11.5" font-family="Arial,sans-serif" font-size="7" font-weight="bold" fill="white" text-anchor="middle">EBS</text>'
388
- '</svg>'
389
- ),
390
- "consensus": (
391
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" style="flex-shrink:0">'
392
- '<rect x="1" y="1" width="14" height="14" rx="7" fill="#6c47ff"/>'
393
- '<circle cx="6" cy="7" r="1.2" fill="white"/>'
394
- '<circle cx="10" cy="7" r="1.2" fill="white"/>'
395
- '<path d="M5 10 Q8 12.5 11 10" fill="none" stroke="white" stroke-width="1.2" stroke-linecap="round"/>'
396
- '</svg>'
397
- ),
398
- "leapspace": (
399
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" style="flex-shrink:0">'
400
- '<rect x="1" y="1" width="14" height="14" rx="2" fill="#ff6b00"/>'
401
- '<path d="M4 12 L4 7 L8 4 L12 7 L12 12 Z" fill="white" opacity=".9"/>'
402
- '<rect x="6.5" y="9" width="3" height="3" fill="#ff6b00"/>'
403
- '</svg>'
404
- ),
405
- "perplexity": (
406
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" style="flex-shrink:0">'
407
- '<rect x="1" y="1" width="14" height="14" rx="2" fill="#1a1a2e"/>'
408
- '<circle cx="8" cy="6.5" r="3" fill="none" stroke="#20b2aa" stroke-width="1.2"/>'
409
- '<line x1="8" y1="9.5" x2="8" y2="13" stroke="#20b2aa" stroke-width="1.2" stroke-linecap="round"/>'
410
- '<circle cx="8" cy="13" r=".8" fill="#20b2aa"/>'
411
- '</svg>'
412
- ),
413
- "semanticscholar": (
414
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" style="flex-shrink:0">'
415
- '<rect x="1" y="1" width="14" height="14" rx="2" fill="#1857b6"/>'
416
- '<path d="M4 11 Q8 4 12 11" fill="none" stroke="white" stroke-width="1.5" stroke-linecap="round"/>'
417
- '<circle cx="8" cy="7" r="1.8" fill="#4fc3f7"/>'
418
- '</svg>'
419
- ),
420
- "pubmed": (
421
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" style="flex-shrink:0">'
422
- '<rect x="1" y="1" width="14" height="14" rx="2" fill="#336699"/>'
423
- '<text x="8" y="11" font-family="Arial,sans-serif" font-size="6.5" font-weight="bold" fill="white" text-anchor="middle">PubMed</text>'
424
- '</svg>'
425
- ),
426
- }
427
- _DB_MASCOT = {
428
- "PubMed@KU": "microscope", "Embase": "medical", "CINAHL Ultimate": "medical",
429
- "Cochrane Library": "microscope", "UpToDate": "medical",
430
- "IEEE Xplore": "circuit", "ACM Digital Library": "circuit",
431
- "ScienceDirect": "microscope", "Scopus": "microscope",
432
- "Web of Science": "microscope", "SpringerLink": "book",
433
- "ACS Publications": "atom", "APS Journals": "atom", "Knovel": "wrench",
434
- "Business Source Complete": "chart", "Emerald Insight": "chart",
435
- "Taylor & Francis": "book", "EBSCO": "book",
436
- }
437
- _BEE = _SVGS["bee"]
438
-
439
- def _btn(label, url, mascot_key="bee"):
440
- icon = _SVGS.get(mascot_key, _SVGS["bee"])
441
- style = (
442
- 'display:inline-flex;align-items:center;gap:7px;'
443
- 'padding:8px 14px;border-radius:10px;text-decoration:none;'
444
- 'font-size:.8rem;font-weight:600;color:#1a1a2e;'
445
- 'background:#fff;border:1.5px solid #d1d5db;'
446
- 'transition:box-shadow .2s;width:100%;box-sizing:border-box'
447
  )
448
- return '<a href="' + url + '" target="_blank" style="' + style + '">' + icon + label + '</a>'
449
 
450
  btn_rows = ""
451
  for k in range(0, len(platforms), 2):
452
- pair = platforms[k:k+2]
453
- cells = ""
454
- for lbl, url, mascot_key in pair:
455
- cells += '<td style="width:50%;padding:3px 4px 3px 0">' + _btn(lbl, url, mascot_key) + '</td>'
456
- if len(pair) == 1:
457
- cells += '<td style="width:50%"></td>'
458
- btn_rows += "<tr>" + cells + "</tr>"
459
 
460
  platforms_html = (
461
- '<div style="margin-top:18px;padding:14px 16px;border:1px solid #c4b5fd;'
462
- 'border-radius:12px;background:linear-gradient(135deg,#f5f3ff,#fdf4ff)">'
463
- '<div style="font-size:.8rem;font-weight:800;color:#5b21b6;margin-bottom:4px">'
464
- 'πŸ€– Search your query across AI platforms</div>'
465
- '<div style="font-size:.73rem;color:#6b7280;margin-bottom:10px">'
466
  'Your query is pre-loaded. Click any platform to search instantly.</div>'
467
- '<table style="width:100%;border-collapse:collapse">' + btn_rows + '</table>'
468
  '</div>'
469
  )
470
 
@@ -475,17 +312,11 @@ def _ai_tools_footer(context):
475
  else:
476
  bool_label = "Try adding synonyms with OR to find more relevant results:"
477
  bool_html = (
478
- '<div style="margin-top:12px;padding:12px 14px;border:1px solid #fde68a;'
479
- 'border-radius:10px;background:#fffbeb">'
480
- '<div style="font-size:.78rem;font-weight:700;color:#92400e;margin-bottom:6px">'
481
- '\U0001f4a1 Boolean search tip</div>'
482
- '<div style="font-size:.74rem;color:#6b7280;margin-bottom:6px">' + bool_label + '</div>'
483
- '<code style="display:block;padding:8px 10px;background:#1a1a2e;color:#C8A951;'
484
- 'border-radius:7px;font-size:.76rem;word-break:break-all;white-space:pre-wrap">'
485
- + _escape(bool_q) +
486
- '</code>'
487
- '<div style="font-size:.71rem;color:#92400e;margin-top:6px">'
488
- 'Paste into the Advanced Search box of any database below.</div>'
489
  '</div>'
490
  )
491
  else:
@@ -493,16 +324,13 @@ def _ai_tools_footer(context):
493
 
494
  all_lower = ((context.ai_tool_query or "") + " " + (context.topic or "")).lower()
495
 
496
- def _db_row(name, url, desc, favicon=None):
497
- icon = _SVGS.get(_DB_MASCOT.get(name, "bee"), _SVGS["bee"])
498
  return (
499
- '<div style="display:flex;align-items:center;gap:8px;'
500
- 'padding:7px 0;border-bottom:1px solid #f3f4f6">'
501
- + icon +
502
- '<div><a href="' + url + '" target="_blank" '
503
- 'style="font-size:.8rem;font-weight:700;color:#003366;text-decoration:none">'
504
- + name + '</a>'
505
- '<span style="font-size:.73rem;color:#6b7280"> β€” ' + desc + '</span></div>'
506
  '</div>'
507
  )
508
 
@@ -570,20 +398,15 @@ def _ai_tools_footer(context):
570
  ("Web of Science",_openathens_url("https://www.webofscience.com"),"Citation index, all disciplines"),
571
  ]
572
 
573
- dbs_html_rows = ""
574
- for name, url, desc in dbs:
575
- dbs_html_rows += _db_row(name, url, desc)
576
 
577
  db_section = (
578
- '<div style="margin-top:12px;padding:12px 14px;border:1px solid #d1d5db;'
579
- 'border-radius:10px;background:#f9fafb">'
580
- '<div style="font-size:.78rem;font-weight:700;color:#003366;margin-bottom:8px">'
581
- '\U0001f4c2 Recommended KU databases \u2014 ' + db_subject + '</div>'
582
  + dbs_html_rows +
583
- '<div style="padding-top:8px;font-size:.74rem">'
584
- '<a href="https://library.ku.ac.ae/eresources" target="_blank" '
585
- 'style="color:#003366;font-weight:700">'
586
- '\U0001f5c4\ufe0f Browse the current KU resource directory \u2192</a></div>'
587
  '</div>'
588
  )
589
 
@@ -593,5 +416,3 @@ def _ai_tools_footer(context):
593
  if is_med and context.open_access:
594
  filter_note += '<p><small>The PubMed link uses its Free full text filter; free access does not establish an open reuse licence.</small></p>'
595
  return platforms_html + filter_note + bool_html + db_section
596
-
597
-
 
1
+ """HTML fragment renderers: source badges, reasoning trace blocks, AI-tools footer, contacts.
2
+
3
+ Styling contract: renderers emit class names only. The answer sanitizer
4
+ (src/services/html_sanitizer.py) strips every style attribute and every svg element,
5
+ so inline styles never reached the browser. Presentation lives in the
6
+ frontend stylesheet:
7
+ - lb-* classes: LibBee server components (trace, source badge, events, hours, steps)
8
+ - kb-* classes: research-answer components already styled by the LibGuides page
9
+ (kb-ai-platform-*, kb-search-process*, kb-database-*, kb-boolean-query-*)
10
+ """
11
  import asyncio
12
  import html
13
  import json
 
44
 
45
  logger = logging.getLogger(__name__)
46
 
47
+ _SOURCE_BADGES = {
48
+ "rag": ("πŸ“–", "KU Library Knowledge Base", "kb"),
49
+ "primo": ("πŸ“š", "KU Library PRIMO", "library"),
50
+ "semantic": ("πŸŽ“", "Semantic Scholar", "scholarly"),
51
+ "consensus_badge": ("🧬", "Consensus", "scholarly"),
52
+ "semantic_badge": ("πŸŽ“", "Semantic Scholar", "scholarly"),
53
+ "pubmed": ("πŸ₯", "PubMed", "scholarly"),
54
+ "web": ("🌐", "Web Search", "web"),
55
+ "web_live": ("🌐", "Web Search · Live", "web"),
56
+ "libbee": ("🐝", "LibBee", "libbee"),
57
+ "ku_library": ("πŸ“‹", "KU Library", "library"),
58
+ "llm": ("πŸ€–", "AI response Β· web not verified", "llm"),
59
+ }
60
+
61
+
62
  def _source_badge(source: str, url: str = "") -> str:
63
+ icon, label, variant = _SOURCE_BADGES.get(source, ("ℹ️", source, "llm"))
64
+ inner = f"{icon} Source: {_escape(label)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  if url:
66
+ inner = f'<a href="{_escape(url)}" target="_blank">{inner}</a>'
67
+ return f'<div class="lb-source lb-source--{variant}">{inner}</div>'
 
 
 
 
68
 
69
 
70
  def _tool_urls(context: SearchContextPayload) -> Dict[str, str]:
 
179
  if extra:
180
  reasoning += " " + extra
181
  return (
182
+ '<details class="lb-trace">'
183
+ f'<summary class="lb-trace-summary"><span class="lb-trace-icon">{icon}</span> My approach</summary>'
184
+ '<div class="lb-trace-body">'
 
 
 
185
  f'<strong>Question:</strong> {_escape(question)}<br>'
186
  f'<strong>Classified as:</strong> {label}<br>'
187
  f'<strong>How I answered:</strong> {reasoning}'
188
+ '</div></details>'
189
  )
190
 
191
 
 
220
  if context.intent == "search_medical" and context.source != "pubmed":
221
  reasoning += " For medical topics, PubMed and Embase are also recommended."
222
  block = (
223
+ '<details class="kb-search-process">'
224
+ '<summary class="kb-search-process-summary">'
225
+ '<span class="kb-search-process-icon">πŸ”</span> How I searched'
226
+ '</summary>'
227
+ '<div class="lb-trace-body">'
228
  f'<strong>Your question:</strong> {_escape(question)}<br>'
229
  f'<strong>Interpreted topic:</strong> {topic}<br>'
230
  )
231
  if primo_boolean:
232
  block += (
233
  f'<strong>Prepared query for {source_label}:</strong><br>'
234
+ f'<code class="lb-code">{primo_boolean}</code>'
 
235
  )
236
  block += f'<strong>Reasoning:</strong> {reasoning}<br>'
237
+ block += '<span class="lb-muted">✨ AI research tools for deeper exploration are listed at the end of this answer.</span>'
238
  block += '</div></details>'
239
  return block
240
 
241
 
242
+ # Emoji stand-ins for the former SVG mascots (the sanitizer drops svg elements).
243
+ _PLATFORM_ICONS = {
244
+ "primo": "πŸ“š", "leapspace": "πŸš€", "scopus": "πŸ”Ž", "ebsco": "πŸ“˜",
245
+ "consensus": "🧬", "semanticscholar": "πŸŽ“", "perplexity": "πŸ’¬", "pubmed": "πŸ₯",
246
+ }
247
+
248
+ _DB_ICONS = {
249
+ "PubMed": "πŸ”¬", "PubMed@KU": "πŸ”¬", "Embase": "πŸ₯", "CINAHL Ultimate": "πŸ₯",
250
+ "Cochrane Library": "πŸ”¬", "UpToDate": "πŸ₯",
251
+ "IEEE Xplore": "πŸ’»", "ACM Digital Library": "πŸ’»",
252
+ "ScienceDirect": "πŸ”¬", "Scopus": "πŸ”¬", "Web of Science": "πŸ”¬", "SpringerLink": "πŸ“š",
253
+ "ACS Publications": "βš›οΈ", "APS Journals": "βš›οΈ", "Knovel": "πŸ”§",
254
+ "Business Source Complete": "πŸ“Š", "Emerald Insight": "πŸ“Š",
255
+ "Taylor & Francis": "πŸ“š", "EBSCO": "πŸ“š",
256
+ }
257
+
258
+
259
  def _ai_tools_footer(context):
260
  from urllib.parse import quote as _q
261
 
262
  ai_q = _q(context.ai_tool_query or context.display_topic or context.topic)
263
  bool_q = context.primo_boolean_query or ""
 
264
  primo_ai = PRIMO_AI_URL + ai_q
265
  is_med = context.intent == "search_medical"
266
  pubmed_url = _shared_build_pubmed_url(
 
282
  if is_med and pubmed_url:
283
  platforms.append(("PubMed", pubmed_url, "pubmed"))
284
 
285
+ def _btn(label, url, icon_key):
286
+ icon = _PLATFORM_ICONS.get(icon_key, "🐝")
287
+ return (
288
+ f'<a class="kb-ai-platform-button" href="{_escape(url)}" target="_blank">'
289
+ f'<span class="kb-ai-platform-icon">{icon}</span>{_escape(label)}</a>'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
  )
 
291
 
292
  btn_rows = ""
293
  for k in range(0, len(platforms), 2):
294
+ pair = platforms[k:k + 2]
295
+ cells = "".join(f"<td>{_btn(lbl, url, key)}</td>" for lbl, url, key in pair)
296
+ btn_rows += f"<tr>{cells}</tr>"
 
 
 
 
297
 
298
  platforms_html = (
299
+ '<div class="kb-ai-platform-panel">'
300
+ '<div class="kb-ai-platform-heading">'
301
+ '<span class="kb-ai-platform-heading-icon">πŸ€–</span> Search your query across AI platforms</div>'
302
+ '<div class="kb-ai-platform-subtitle">'
 
303
  'Your query is pre-loaded. Click any platform to search instantly.</div>'
304
+ f'<table class="kb-ai-platform-grid"><tbody>{btn_rows}</tbody></table>'
305
  '</div>'
306
  )
307
 
 
312
  else:
313
  bool_label = "Try adding synonyms with OR to find more relevant results:"
314
  bool_html = (
315
+ '<div class="kb-boolean-query-panel">'
316
+ '<div class="kb-boolean-query-title">πŸ’‘ Boolean search tip</div>'
317
+ f'<div class="lb-boolean-hint">{bool_label}</div>'
318
+ f'<code class="kb-boolean-query-text">{_escape(bool_q)}</code>'
319
+ '<div class="lb-boolean-hint">Paste into the Advanced Search box of any database below.</div>'
 
 
 
 
 
 
320
  '</div>'
321
  )
322
  else:
 
324
 
325
  all_lower = ((context.ai_tool_query or "") + " " + (context.topic or "")).lower()
326
 
327
+ def _db_row(name, url, desc):
328
+ icon = _DB_ICONS.get(name, "🐝")
329
  return (
330
+ '<div class="kb-database-row">'
331
+ f'<span class="kb-database-icon">{icon}</span>'
332
+ f'<a class="kb-database-name" href="{_escape(url)}" target="_blank">{_escape(name)}</a>'
333
+ f'<span class="lb-muted"> β€” {_escape(desc)}</span>'
 
 
 
334
  '</div>'
335
  )
336
 
 
398
  ("Web of Science",_openathens_url("https://www.webofscience.com"),"Citation index, all disciplines"),
399
  ]
400
 
401
+ dbs_html_rows = "".join(_db_row(name, url, desc) for name, url, desc in dbs)
 
 
402
 
403
  db_section = (
404
+ '<div class="kb-database-list">'
405
+ f'<div class="lb-db-heading">πŸ“‚ Recommended KU databases β€” {_escape(db_subject)}</div>'
 
 
406
  + dbs_html_rows +
407
+ '<div class="lb-db-more">'
408
+ '<a href="https://library.ku.ac.ae/eresources" target="_blank">'
409
+ 'πŸ—„οΈ Browse the current KU resource directory β†’</a></div>'
 
410
  '</div>'
411
  )
412
 
 
416
  if is_med and context.open_access:
417
  filter_note += '<p><small>The PubMed link uses its Free full text filter; free access does not establish an open reuse licence.</small></p>'
418
  return platforms_html + filter_note + bool_html + db_section