Anna Zhou commited on
Commit
423e236
Β·
1 Parent(s): ab38634

Add dynamic navigation pages

Browse files
Files changed (1) hide show
  1. app/app.py +197 -9
app/app.py CHANGED
@@ -3,7 +3,9 @@ import json
3
  import re
4
  import ast
5
  import uuid
 
6
  from pathlib import Path
 
7
  import streamlit as st
8
 
9
  sys.path.insert(0, str(Path(__file__).parent.parent))
@@ -119,9 +121,48 @@ def _render_source_links(raw_links, limit: int = 5) -> None:
119
  st.markdown(f" - [PDF]({link['pdf_url']})")
120
 
121
 
122
- def _render_navigation() -> None:
123
- st.markdown(
124
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  <style>
126
  .rfr-nav {
127
  position: sticky;
@@ -163,6 +204,11 @@ def _render_navigation() -> None:
163
  color: #17324d;
164
  text-decoration: none;
165
  }
 
 
 
 
 
166
  @media (max-width: 720px) {
167
  .rfr-nav {
168
  align-items: flex-start;
@@ -177,13 +223,12 @@ def _render_navigation() -> None:
177
  <nav class="rfr-nav" aria-label="Primary navigation">
178
  <div class="rfr-nav__brand">RFR Knowledge Platform</div>
179
  <div class="rfr-nav__links">
180
- <a href="#ask">Ask</a>
181
- <a href="#case-studies">Case Studies</a>
182
- <a href="#previous-responses">Previous Responses</a>
183
- <a href="#about">About</a>
184
  </div>
185
  </nav>
186
- """,
 
 
187
  unsafe_allow_html=True,
188
  )
189
 
@@ -321,6 +366,136 @@ def _metadata_answer_markdown(query: str) -> str | None:
321
  return None
322
 
323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324
  def _query_param_is_true(key: str) -> bool:
325
  if hasattr(st, "query_params"):
326
  value = st.query_params.get(key)
@@ -466,7 +641,8 @@ if not st.session_state.disclaimer_accepted:
466
  st.rerun()
467
  st.stop()
468
 
469
- _render_navigation()
 
470
 
471
  # ── Sidebar ───────────────────────────────────────────────────────────────────
472
  with st.sidebar:
@@ -509,6 +685,18 @@ with st.sidebar:
509
 
510
  model_choice = "claude"
511
 
 
 
 
 
 
 
 
 
 
 
 
 
512
  # ── Two-column layout ─────────────────────────────────────────────────────────
513
  main_col, history_col = st.columns([2, 1], gap="large")
514
 
 
3
  import re
4
  import ast
5
  import uuid
6
+ from html import escape
7
  from pathlib import Path
8
+ from urllib.parse import urlencode
9
  import streamlit as st
10
 
11
  sys.path.insert(0, str(Path(__file__).parent.parent))
 
121
  st.markdown(f" - [PDF]({link['pdf_url']})")
122
 
123
 
124
+ def _render_apa_source_links(raw_links, limit: int | None = None) -> None:
125
+ links = _parse_source_links(raw_links)
126
+ if not links:
127
+ st.caption("No source links available for this case yet.")
128
+ return
129
+
130
+ selected = links if limit is None else links[:limit]
131
+ for link in selected:
132
+ title = link.get("title") or link.get("doi") or link.get("url") or "Source"
133
+ url = link.get("url") or (f"https://doi.org/{link['doi']}" if link.get("doi") else "")
134
+ if url:
135
+ st.markdown(f"- [{title}]({url})")
136
+ else:
137
+ st.markdown(f"- {title}")
138
+ if link.get("pdf_url"):
139
+ st.markdown(f" - [PDF]({link['pdf_url']})")
140
+
141
+
142
+ def _nav_url(page: str, conversation_id: str) -> str:
143
+ params = {
144
+ "disclaimer_accepted": "true",
145
+ "conversation_id": conversation_id,
146
+ "page": page,
147
+ }
148
+ return "?" + urlencode(params)
149
+
150
+
151
+ def _render_navigation(current_page: str, conversation_id: str) -> None:
152
+ nav_items = [
153
+ ("ask", "Ask"),
154
+ ("case_studies", "Case Studies"),
155
+ ("previous_responses", "Previous Responses"),
156
+ ("about", "About"),
157
+ ]
158
+ nav_links = "\n".join(
159
+ (
160
+ f'<a class="{"is-active" if page == current_page else ""}" '
161
+ f'href="{escape(_nav_url(page, conversation_id))}">{label}</a>'
162
+ )
163
+ for page, label in nav_items
164
+ )
165
+ nav_html = """
166
  <style>
167
  .rfr-nav {
168
  position: sticky;
 
204
  color: #17324d;
205
  text-decoration: none;
206
  }
207
+ .rfr-nav__links a.is-active {
208
+ background: #edf3f7;
209
+ color: #17324d;
210
+ font-weight: 700;
211
+ }
212
  @media (max-width: 720px) {
213
  .rfr-nav {
214
  align-items: flex-start;
 
223
  <nav class="rfr-nav" aria-label="Primary navigation">
224
  <div class="rfr-nav__brand">RFR Knowledge Platform</div>
225
  <div class="rfr-nav__links">
226
+ __NAV_LINKS__
 
 
 
227
  </div>
228
  </nav>
229
+ """.replace("__NAV_LINKS__", nav_links)
230
+ st.markdown(
231
+ nav_html,
232
  unsafe_allow_html=True,
233
  )
234
 
 
366
  return None
367
 
368
 
369
+ def _current_page() -> str:
370
+ page = _get_query_param("page") or "ask"
371
+ allowed = {"ask", "case_studies", "previous_responses", "about"}
372
+ return page if page in allowed else "ask"
373
+
374
+
375
+ @st.cache_data
376
+ def _load_case_summary_chunks() -> list[dict]:
377
+ path = Path("data/extracted/case_summaries.json")
378
+ if not path.exists():
379
+ return []
380
+ try:
381
+ chunks = json.loads(path.read_text())
382
+ except Exception:
383
+ return []
384
+ return chunks if isinstance(chunks, list) else []
385
+
386
+
387
+ def _case_summary_records() -> list[dict]:
388
+ meta = load_case_meta()
389
+ records = []
390
+ for chunk in _load_case_summary_chunks():
391
+ cid = chunk.get("case_id", "")
392
+ case_meta = meta.get(cid, {})
393
+ records.append({
394
+ "case_id": cid,
395
+ "name": case_meta.get("name") or cid,
396
+ "location": chunk.get("location", ""),
397
+ "country": normalize_country(chunk.get("country", "")),
398
+ "continent": chunk.get("continent", ""),
399
+ "summary": _clean_excerpt(chunk.get("text", ""), max_chars=900),
400
+ "source_links": chunk.get("source_links"),
401
+ })
402
+ return sorted(records, key=lambda record: _case_sort_key(record["case_id"]))
403
+
404
+
405
+ def _render_case_studies_page() -> None:
406
+ st.title("Case Studies")
407
+ st.caption("Indexed managed retreat case studies with summary notes and paper/source links.")
408
+
409
+ records = _case_summary_records()
410
+ if not records:
411
+ st.warning("No case-study summaries were found. Run the ingest and summary chunk scripts first.")
412
+ return
413
+
414
+ countries = sorted({record["country"] for record in records if record["country"]})
415
+ continents = sorted({record["continent"] for record in records if record["continent"]})
416
+ filter_col, country_col = st.columns([1, 1])
417
+ with filter_col:
418
+ continent_filter = st.selectbox("Continent", ["All"] + continents)
419
+ with country_col:
420
+ country_filter = st.selectbox("Country", ["All"] + countries)
421
+
422
+ filtered = [
423
+ record for record in records
424
+ if (continent_filter == "All" or record["continent"] == continent_filter)
425
+ and (country_filter == "All" or record["country"] == country_filter)
426
+ ]
427
+ st.caption(f"Showing {len(filtered)} of {len(records)} indexed case studies.")
428
+
429
+ for record in filtered:
430
+ with st.expander(f"{record['case_id']} β€” {record['name']} ({record['country']})", expanded=False):
431
+ st.markdown(f"**Location:** {record['location']}")
432
+ if record["continent"]:
433
+ st.markdown(f"**Continent:** {record['continent']}")
434
+ st.markdown("**Summary:**")
435
+ st.markdown(record["summary"])
436
+ st.markdown("**Sources:**")
437
+ _render_apa_source_links(record["source_links"], limit=None)
438
+
439
+
440
+ def _render_previous_responses_page(conversation_id: str, questions: list[dict]) -> None:
441
+ st.title("Previous Responses")
442
+ st.caption("Full responses saved for this browser conversation.")
443
+
444
+ history = _load_history(conversation_id)
445
+ if not history:
446
+ st.info("No previous responses are saved for this conversation yet.")
447
+ return
448
+
449
+ if st.button("Clear previous responses", type="secondary"):
450
+ st.session_state.history = []
451
+ _save_history(conversation_id, st.session_state.history)
452
+ st.rerun()
453
+
454
+ for i, entry in enumerate(history):
455
+ response_number = len(history) - i
456
+ st.markdown(f"## Response {response_number}")
457
+ st.markdown(f"**Question:** {entry.get('query', '')}")
458
+
459
+ context = entry.get("context") or {}
460
+ if context:
461
+ with st.expander("Context used", expanded=False):
462
+ for qid, val in context.items():
463
+ q_text = next((q["text"] for q in questions if q["id"] == qid), qid)
464
+ st.markdown(f"**{q_text}** {val}")
465
+
466
+ st.markdown(entry.get("answer", ""))
467
+
468
+ chunks = entry.get("chunks") or []
469
+ if chunks:
470
+ with st.expander("Case studies and sources used", expanded=False):
471
+ seen_ids = set()
472
+ for chunk in chunks:
473
+ metadata = chunk.get("metadata", {})
474
+ cid = metadata.get("case_id", "")
475
+ if cid in seen_ids:
476
+ continue
477
+ seen_ids.add(cid)
478
+ st.markdown(f"**{cid} β€” {metadata.get('source', '')}**")
479
+ _render_apa_source_links(metadata.get("source_links"), limit=5)
480
+
481
+ st.divider()
482
+
483
+
484
+ def _render_about_page() -> None:
485
+ st.title("About")
486
+ st.markdown(
487
+ """
488
+ This AI-assisted knowledge platform supports exploration of managed retreat
489
+ case-study literature from the Retreat From Risk project.
490
+
491
+ The tool retrieves evidence from indexed case-study summaries and sections,
492
+ then generates a grounded response for planning, policy, and research use.
493
+ It is a research aid only and does not replace professional planning, legal,
494
+ engineering, or policy advice.
495
+ """
496
+ )
497
+
498
+
499
  def _query_param_is_true(key: str) -> bool:
500
  if hasattr(st, "query_params"):
501
  value = st.query_params.get(key)
 
641
  st.rerun()
642
  st.stop()
643
 
644
+ current_page = _current_page()
645
+ _render_navigation(current_page, conversation_id)
646
 
647
  # ── Sidebar ───────────────────────────────────────────────────────────────────
648
  with st.sidebar:
 
685
 
686
  model_choice = "claude"
687
 
688
+ if current_page == "case_studies":
689
+ _render_case_studies_page()
690
+ st.stop()
691
+
692
+ if current_page == "previous_responses":
693
+ _render_previous_responses_page(conversation_id, questions)
694
+ st.stop()
695
+
696
+ if current_page == "about":
697
+ _render_about_page()
698
+ st.stop()
699
+
700
  # ── Two-column layout ─────────────────────────────────────────────────────────
701
  main_col, history_col = st.columns([2, 1], gap="large")
702