Slaiwala commited on
Commit
7f2d899
·
verified ·
1 Parent(s): 90f850d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +868 -75
app.py CHANGED
@@ -1,91 +1,884 @@
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from askstein import ask
3
 
4
- def main():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  with gr.Blocks() as demo:
6
- # Store user info and chat history in state
7
- user_info = gr.State({"first_name": None, "last_name": None})
8
- chat_history = gr.State([]) # list of (user_msg, bot_response, feedback)
9
 
10
- # --- User info input ---
11
- with gr.Row():
12
- first_name = gr.Textbox(label="First Name", placeholder="Enter your first name", interactive=True)
13
- last_name = gr.Textbox(label="Last Name", placeholder="Enter your last name", interactive=True)
14
- submit_names = gr.Button("Submit")
15
-
16
- # --- Chatbot interface (hidden initially) ---
17
- chatbot = gr.Chatbot(visible=False)
18
- user_msg = gr.Textbox(placeholder="Ask me anything...", visible=False)
19
- send_btn = gr.Button("Send", visible=False)
20
- feedback = gr.Radio(choices=["👍", "👎"], label="Your feedback", visible=False)
21
- submit_feedback = gr.Button("Submit Feedback", visible=False)
22
- clear_btn = gr.Button("Clear Chat", visible=False)
23
-
24
- # --- Functions ---
25
-
26
- def submit_user_info(fn, ln):
27
- fn = fn.strip()
28
- ln = ln.strip()
29
- if not fn or not ln:
30
- return gr.update(visible=True), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), "Please enter both first and last names."
31
- user_info.value = {"first_name": fn, "last_name": ln}
32
- return (
33
- gr.update(visible=False), # hide first_name
34
- gr.update(visible=False), # hide last_name
35
- gr.update(visible=True), # show chatbot
36
- gr.update(visible=True), # show user_msg
37
- gr.update(visible=True), # show send_btn
38
- gr.update(visible=False), # hide feedback (initially)
39
- gr.update(visible=False), # hide submit_feedback
40
- gr.update(visible=True), # show clear_btn
41
- ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  )
 
 
 
 
 
 
 
 
 
 
43
 
44
- def send_message(message, history):
45
- if not message.strip():
46
- return history, "", gr.update(visible=False), gr.update(visible=True), gr.update(value=None)
47
- response = ask(message)
48
- history = history + [(message, response, None)]
49
- return history, "", gr.update(visible=True), gr.update(visible=False), gr.update(value=None)
50
-
51
- def submit_user_feedback(feedback_value, history):
52
- if not history:
53
- return history, gr.update(visible=False), "No conversation yet."
54
- if feedback_value is None:
55
- return history, gr.update(visible=True), "Please provide feedback."
56
- # Update last message feedback
57
- history[-1] = (history[-1][0], history[-1][1], feedback_value)
58
- return history, gr.update(visible=False), "Thank you for your feedback!"
59
-
60
- def clear_chat():
61
- return [], ""
62
-
63
- # --- Event bindings ---
64
- submit_names.click(
65
- submit_user_info,
66
- inputs=[first_name, last_name],
67
- outputs=[first_name, last_name, chatbot, user_msg, send_btn, feedback, submit_feedback, clear_btn, gr.Textbox(visible=True, interactive=False, label="Error Message")]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  )
 
 
 
 
 
69
 
70
- send_btn.click(
71
- send_message,
72
- inputs=[user_msg, chat_history],
73
- outputs=[chatbot, user_msg, feedback, submit_feedback, feedback]
74
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
- submit_feedback.click(
77
- submit_user_feedback,
78
- inputs=[feedback, chat_history],
79
- outputs=[chatbot, feedback, gr.Textbox(visible=True, interactive=False, label="Feedback Status")]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
- clear_btn.click(
83
- clear_chat,
84
- outputs=[chatbot, user_msg]
 
 
 
 
 
 
 
 
 
85
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
88
 
89
- if __name__ == "__main__":
90
- main()
91
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import os, re, json, time, sys, csv, uuid, datetime
5
+ from typing import List, Dict, Any, Optional
6
+ from functools import lru_cache
7
+ from xml.etree import ElementTree as ET
8
+
9
+ import numpy as np
10
+ import requests
11
  import gradio as gr
 
12
 
13
+ # ================== CONFIG / PATHS ==================
14
+ ASSETS_DIR = os.environ.get("ASSETS_DIR", "assets")
15
+ FAISS_PATH = os.environ.get("FAISS_PATH", f"{ASSETS_DIR}/index.faiss")
16
+ META_PATH = os.environ.get("META_PATH", f"{ASSETS_DIR}/index_meta.filtered.jsonl")
17
+ REL_CONFIG_PATH = os.environ.get("REL_CONFIG_PATH", f"{ASSETS_DIR}/relevance_config.json")
18
+
19
+ # Models
20
+ BASE_MODEL = os.environ.get("BASE_MODEL", "mistralai/Mistral-7B-Instruct-v0.2")
21
+ ADAPTER_PATH = os.environ.get("ADAPTER_PATH", f"{ASSETS_DIR}/lora_adapter") # local folder if present
22
+ ADAPTER_REPO = os.environ.get("ADAPTER_REPO", "") # optional HF repo id for adapter
23
+
24
+ # Embeddings used to build FAISS
25
+ EMBED_MODEL_NAME = os.environ.get("EMBED_MODEL_NAME", "pritamdeka/S-PubMedBERT-MS-MARCO")
26
+
27
+ # PubMed / NCBI (set in Space Secrets if you have them)
28
+ NCBI_EMAIL = os.environ.get("NCBI_EMAIL", "")
29
+ NCBI_TOOL = os.environ.get("NCBI_TOOL", "askstein")
30
+ NCBI_APIKEY = os.environ.get("NCBI_APIKEY", "")
31
+
32
+ # Feedback logging
33
+ FEEDBACK_PATH = os.environ.get("FEEDBACK_PATH", "feedback.csv")
34
+ PUSH_FEEDBACK = os.environ.get("PUSH_FEEDBACK", "0") == "1" # set to "1" to enable Hub upload
35
+ HF_TOKEN = os.environ.get("HF_TOKEN", "") # add in Space Secrets
36
+ SPACE_REPO_ID = os.environ.get("SPACE_REPO_ID", "") # auto-provided in Spaces
37
+
38
+ # Generation / toggles
39
+ ALLOW_WIKIPEDIA = False
40
+ DEBUG = True
41
+ MAX_NEW_TOKENS_GROUNDED = 512
42
+ MAX_NEW_TOKENS_FALLBACK = 256
43
+ MIN_USEFUL_CHARS = 260
44
+
45
+ def dlog(tag, msg):
46
+ if DEBUG: print(f"[{tag}] {msg}")
47
+
48
+ # ================== HEAVY IMPORTS ==================
49
+ import faiss
50
+ from sentence_transformers import SentenceTransformer
51
+ import torch
52
+ from transformers import AutoTokenizer, AutoModelForCausalLM
53
+ from peft import PeftModel
54
+ import wikipedia
55
+ from wikipedia.exceptions import DisambiguationError, PageError
56
+ from huggingface_hub import login, snapshot_download, HfApi
57
+
58
+ # ================== GPU CHECK ==================
59
+ if not torch.cuda.is_available():
60
  with gr.Blocks() as demo:
61
+ gr.Markdown("### 🚦 GPU not detected.\nThis Space needs a GPU (A10G or better). Go to **Settings → Hardware** and select a GPU.")
62
+ demo.launch()
63
+ sys.exit(0)
64
 
65
+ device = "cuda"
66
+ dtype = torch.float16
67
+ torch.manual_seed(42)
68
+
69
+ # ================== RELEVANCE CONFIG ==================
70
+ DEFAULT_REL_CONFIG = {
71
+ "positive_terms": [
72
+ "ctra","rigidity","ct-based","qct","micro-ct","hounsfield",
73
+ "femur","femoral","hip","proximal femur",
74
+ "bending","torsional","axial","failure load","modulus",
75
+ "nazarian","freedman","alboro"
76
+ ],
77
+ "negative_terms": [
78
+ "t cell","lymph","immunolog","synapse","receptor","egfr",
79
+ "tumor","oncolog","immune","lymph node","cardio","myocard","neuro","skull","heart","brain"
80
+ ],
81
+ "weights": {"positive": 2, "negative": 1},
82
+ "author_whitelist": ["Nazarian","Freedman","Alboro"],
83
+ "mesh_positive": [
84
+ "Femur", "Femoral Neck", "Hip", "Bone Density",
85
+ "Tomography, X-Ray Computed", "Finite Element Analysis",
86
+ "Bone and Bones", "Elastic Modulus", "Biomechanical Phenomena"
87
+ ],
88
+ "mesh_weight": 2,
89
+ "author_weight": 3,
90
+ "min_rel_to_use_faiss": 3,
91
+ "ncbi_email": NCBI_EMAIL,
92
+ "ncbi_tool": NCBI_TOOL,
93
+ "ncbi_apikey": NCBI_APIKEY,
94
+ }
95
+
96
+ def load_rel_config(path: str) -> Dict[str, Any]:
97
+ cfg = DEFAULT_REL_CONFIG.copy()
98
+ try:
99
+ if os.path.exists(path):
100
+ with open(path, "r", encoding="utf-8") as f:
101
+ user_cfg = json.load(f)
102
+ cfg.update(user_cfg)
103
+ except Exception as e:
104
+ dlog("rel-config", f"using defaults ({e})")
105
+ return cfg
106
+
107
+ REL_CFG = load_rel_config(REL_CONFIG_PATH)
108
+ dlog("rel-config", f"Loaded keys: {list(REL_CFG.keys())}")
109
+
110
+ # ================== HTTP / NCBI HELPERS ==================
111
+ class _Http:
112
+ session = requests.Session()
113
+ session.headers.update({"User-Agent": "Askstein/1.0 (https://huggingface.co)"})
114
+
115
+ def _ncbi_params(extra: Dict[str, Any] | None = None) -> Dict[str, Any]:
116
+ p = {"retmode": "xml"}
117
+ if REL_CFG.get("ncbi_email"): p["email"] = REL_CFG["ncbi_email"]
118
+ if REL_CFG.get("ncbi_tool"): p["tool"] = REL_CFG["ncbi_tool"]
119
+ if REL_CFG.get("ncbi_apikey"): p["api_key"] = REL_CFG["ncbi_apikey"]
120
+ if extra: p.update(extra)
121
+ return p
122
+
123
+ def _get_with_backoff(url: str, params: Dict[str, Any], tries: int = 2, base_sleep: float = 0.5, timeout: int = 6) -> str:
124
+ for i in range(tries):
125
+ try:
126
+ if not REL_CFG.get("ncbi_apikey"):
127
+ time.sleep(0.34)
128
+ r = _Http.session.get(url, params=params, timeout=timeout)
129
+ r.raise_for_status()
130
+ return r.text
131
+ except Exception:
132
+ if i == tries - 1: raise
133
+ time.sleep(base_sleep * (2 ** i))
134
+
135
+ # ================== WIKIPEDIA ==================
136
+ def wiki_summary_allow(query: str, sentences: int = 2) -> Optional[str]:
137
+ prev = globals().get("ALLOW_WIKIPEDIA", False)
138
+ globals()["ALLOW_WIKIPEDIA"] = True
139
+ try:
140
+ q = re.sub(r'^(what is|what are|define|where is|where are)\s+', '', query, flags=re.IGNORECASE)
141
+ q = re.sub(r'\s+(located|location)\s*\?*$', '', q, flags=re.IGNORECASE).strip('?').strip()
142
+ return wikipedia.summary(q, sentences=sentences)
143
+ except (DisambiguationError, PageError, Exception):
144
+ return None
145
+ finally:
146
+ globals()["ALLOW_WIKIPEDIA"] = prev
147
+
148
+ # ================== LOAD FAISS + META + EMBEDDER ==================
149
+ dlog("FAISS", "Loading index…")
150
+ index = faiss.read_index(FAISS_PATH)
151
+ dlog("FAISS", f"ntotal={index.ntotal}")
152
+
153
+ dlog("FAISS", "Loading metadata…")
154
+ all_chunks: List[Dict[str, Any]] = []
155
+ with open(META_PATH, "r", encoding="utf-8") as f:
156
+ for line in f:
157
+ try:
158
+ all_chunks.append(json.loads(line))
159
+ except Exception:
160
+ pass
161
+ dlog("FAISS", f"Metadata records: {len(all_chunks)}")
162
+
163
+ if len(all_chunks) != index.ntotal:
164
+ raise RuntimeError(f"[ALIGNMENT] Metadata rows ({len(all_chunks)}) != FAISS ntotal ({index.ntotal}).")
165
+
166
+ dlog("EMBED", f"Loading embedder: {EMBED_MODEL_NAME}")
167
+ embed_model = SentenceTransformer(EMBED_MODEL_NAME)
168
+
169
+ try:
170
+ _probe = embed_model.encode(["__dimcheck__"], convert_to_numpy=True).astype("float32")
171
+ _dim = _probe.shape[1] if _probe.ndim == 2 else len(_probe)
172
+ assert index.d == _dim, f"FAISS dim {index.d} != embed dim {_dim} (model={EMBED_MODEL_NAME}). Rebuild index."
173
+ except Exception as e:
174
+ raise RuntimeError(f"[FAISS] Dimension check failed: {e}")
175
+
176
+ _IS_IP = isinstance(index, faiss.IndexFlatIP) or "IndexFlatIP" in type(index).__name__
177
+
178
+ # ================== LOAD LLM (BASE + LORA) ==================
179
+ if HF_TOKEN:
180
+ try:
181
+ login(token=HF_TOKEN)
182
+ dlog("HF", "Login successful via HF_TOKEN")
183
+ except Exception as e:
184
+ dlog("HF", f"Login issue: {e}")
185
+
186
+ if ADAPTER_REPO:
187
+ ADAPTER_PATH = snapshot_download(repo_id=ADAPTER_REPO, allow_patterns=["*"])
188
+
189
+ dlog("LLM", f"Loading base model: {BASE_MODEL}")
190
+ tokenizer_lm = AutoTokenizer.from_pretrained(BASE_MODEL, use_fast=False)
191
+ base_model = AutoModelForCausalLM.from_pretrained(
192
+ BASE_MODEL, torch_dtype=dtype, device_map="auto"
193
+ )
194
+
195
+ dlog("LLM", f"Loading LoRA adapter from: {ADAPTER_PATH}")
196
+ model_lm = PeftModel.from_pretrained(base_model, ADAPTER_PATH)
197
+ model_lm.to(device)
198
+ model_lm.eval()
199
+
200
+ GEN_ARGS_GROUNDED = dict(
201
+ max_new_tokens=MAX_NEW_TOKENS_GROUNDED,
202
+ do_sample=False,
203
+ num_beams=1,
204
+ no_repeat_ngram_size=3,
205
+ repetition_penalty=1.08,
206
+ eos_token_id=tokenizer_lm.eos_token_id,
207
+ )
208
+ GEN_ARGS_FALLBACK = dict(
209
+ max_new_tokens=MAX_NEW_TOKENS_FALLBACK,
210
+ do_sample=False,
211
+ num_beams=1,
212
+ no_repeat_ngram_size=3,
213
+ repetition_penalty=1.05,
214
+ eos_token_id=tokenizer_lm.eos_token_id,
215
+ )
216
+
217
+ def _generate(inputs, grounded: bool):
218
+ args = GEN_ARGS_GROUNDED if grounded else GEN_ARGS_FALLBACK
219
+ with torch.inference_mode():
220
+ return model_lm.generate(**inputs, **args)
221
+
222
+ # ================== UTILITIES ==================
223
+ _SANITIZE = re.compile(r"```.*?```|<\s*script[^>]*>.*?<\s*/\s*script\s*>", re.DOTALL|re.IGNORECASE)
224
+ def _to_text(rec: Any) -> str:
225
+ if isinstance(rec, str): return rec.strip()
226
+ for k in ("text","chunk_text","content","body","passage","raw_text","section_text","abstract"):
227
+ v = rec.get(k)
228
+ if isinstance(v, str) and v.strip():
229
+ return _SANITIZE.sub("", v.strip())
230
+ segs = rec.get("segments")
231
+ if isinstance(segs, list):
232
+ return _SANITIZE.sub("", " ".join(s.get("text","").strip() for s in segs if isinstance(s, dict)).strip())
233
+ return ""
234
+
235
+ def _hydrate_text(item: Dict[str, Any]) -> str:
236
+ t = _to_text(item)
237
+ if t: return t
238
+ pmid = item.get("pmid")
239
+ if pmid:
240
+ abs_chunks = fetch_pubmed_chunks(str(pmid), max_papers=1)
241
+ if abs_chunks: return abs_chunks[0].get("text", "").strip()
242
+ title = item.get("title")
243
+ if isinstance(title, str) and title.strip():
244
+ return title.strip()
245
+ return ""
246
+
247
+ def _dedup_by_pmid_or_title(records: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
248
+ seen, out = set(), []
249
+ for r in records:
250
+ key = str(r.get("pmid") or "").strip()
251
+ if not key: key = (r.get("title") or "").strip().lower()[:120]
252
+ if not key: key = (r.get("text") or "").strip().lower()[:200]
253
+ if key in seen: continue
254
+ seen.add(key); out.append(r)
255
+ return out
256
+
257
+ def _split_sentences(s: str) -> List[str]:
258
+ s = s.replace("\r"," ").replace("\n"," ")
259
+ parts = re.split(r"(?<=[\.\?\!])\s+", s)
260
+ return [p.strip() for p in parts if p.strip()]
261
+
262
+ _BAD_BULLETS = re.compile(r"^\s*(?:\d+\s*\)|[•\-\*])\s*$", re.M)
263
+ _DANGLING = re.compile(r"[\[\(][^\]\)]$")
264
+ def _post_clean(text: str) -> str:
265
+ t = re.sub(r"[ \t]+\n", "\n", text)
266
+ t = _BAD_BULLETS.sub("", t)
267
+ t = re.sub(r"\n{3,}", "\n\n", t).strip()
268
+ sents = _split_sentences(t)
269
+ seen, kept = set(), []
270
+ for s in sents:
271
+ key = s.lower()
272
+ if key in seen: continue
273
+ seen.add(key); kept.append(s)
274
+ t = " ".join(kept)
275
+ t = re.sub(_DANGLING, "", t).strip(" -,:;")
276
+ return t
277
+
278
+ def _ensure_min_answer(ans: str) -> str:
279
+ if len(ans) >= MIN_USEFUL_CHARS: return ans
280
+ tail = " If you want, I can add a short checklist of assumptions, units, and typical parameter ranges."
281
+ return (ans + tail) if not ans.endswith(".") else (ans + tail)
282
+
283
+ # ================== RELEVANCE / GATING ==================
284
+ def _rel_score(text: str, title: str = "", cfg: Dict[str, Any] | None = None) -> int:
285
+ cfg = cfg or REL_CFG
286
+ blob = (title + " " + text).lower()
287
+ pos = sum(1 for k in cfg.get("positive_terms", []) if k.lower() in blob)
288
+ neg = sum(1 for k in cfg.get("negative_terms", []) if k.lower() in blob)
289
+ w_pos = int(cfg.get("weights", {}).get("positive", 2))
290
+ w_neg = int(cfg.get("weights", {}).get("negative", 1))
291
+ return pos * w_pos - neg * w_neg
292
+
293
+ @lru_cache(maxsize=4096)
294
+ def _mesh_by_pmid(pmid: str) -> List[str]:
295
+ try:
296
+ xml = _get_with_backoff(
297
+ "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi",
298
+ _ncbi_params({"db":"pubmed","id":str(pmid)})
299
+ )
300
+ root = ET.fromstring(xml)
301
+ heads = []
302
+ for mh in root.findall(".//MeshHeading"):
303
+ dn = mh.find("DescriptorName")
304
+ if dn is not None and dn.text:
305
+ heads.append(dn.text.strip())
306
+ return heads
307
+ except Exception:
308
+ return []
309
+
310
+ @lru_cache(maxsize=4096)
311
+ def _authors_by_pmid(pmid: str) -> List[str]:
312
+ try:
313
+ xml = _get_with_backoff(
314
+ "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi",
315
+ _ncbi_params({"db":"pubmed","id":str(pmid)})
316
+ )
317
+ root = ET.fromstring(xml)
318
+ names = []
319
+ for docsum in root.findall(".//DocSum"):
320
+ for item in docsum.findall("Item"):
321
+ if item.get("Name") == "AuthorList":
322
+ for au in item.findall("Item"):
323
+ if au.text:
324
+ last = au.text.split(",")[0].split(" ")[-1]
325
+ names.append(last)
326
+ return names
327
+ except Exception:
328
+ return []
329
+
330
+ def _boost_by_author(pmid: str | int, rel_base: int, cfg: Dict[str, Any] | None = None) -> int:
331
+ cfg = cfg or REL_CFG
332
+ wl = set(cfg.get("author_whitelist", []))
333
+ if not pmid or not wl: return rel_base
334
+ names = _authors_by_pmid(str(pmid))
335
+ return rel_base + int(cfg.get("author_weight", 3)) if any(n in wl for n in names) else rel_base
336
+
337
+ def _mesh_boost(pmid: str | int, rel_base: int, cfg: Dict[str, Any] | None = None) -> int:
338
+ cfg = cfg or REL_CFG
339
+ if not pmid: return rel_base
340
+ targets = set(x.lower() for x in cfg.get("mesh_positive", []))
341
+ weight = int(cfg.get("mesh_weight", 2))
342
+ heads = [h.lower() for h in _mesh_by_pmid(str(pmid))]
343
+ hit = sum(1 for h in heads if h in targets)
344
+ return rel_base + hit * weight
345
+
346
+ _MSK_MUST = re.compile(
347
+ r"\b(femur|femoral|hip|proximal\s+femur|ctra|qct|ct-?based|rigidity|bending|torsional|axial|failure\s+load)\b",
348
+ re.I
349
+ )
350
+ _CT_RIGIDITY_TOKENS = re.compile(r"\b(qct|ct[-\s]?based|ctra|rigidity|bending|torsion|hounsfield|finite\s+element|fe[am])\b", re.I)
351
+ _FE_TOKENS = re.compile(r"\b(fe|fea|finite\s+element|micromotion|boundary\s+conditions|nonlinear|yield|ultimate|fracture\s+load)\b", re.I)
352
+ _ANATOMY_OR_HISTORY = re.compile(
353
+ r"(?:\bhistory\b.*\b(femur|hip|bone)\b|\bwhat\s+is\s+the\s+(femur|hip)\b|\banatomy\b.*\b(hip|femur)\b)",
354
+ re.I
355
+ )
356
+ _PAPERS_INTENT = re.compile(r"\b(key\s+papers|suggest\s+papers|landmark|seminal|important|top\s+papers)\b", re.I)
357
+
358
+ def fetch_pubmed_chunks(query_or_pmid: str, max_papers: int = 3) -> List[Dict[str, Any]]:
359
+ retries = 1
360
+ chunks: List[Dict[str, Any]] = []
361
+
362
+ def _efetch(pmid: str):
363
+ try:
364
+ xml = _get_with_backoff(
365
+ "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi",
366
+ _ncbi_params({"db":"pubmed","id":pmid})
367
  )
368
+ tree = ET.fromstring(xml)
369
+ paras = [a.text for a in tree.findall(".//AbstractText") if a is not None and a.text]
370
+ if paras:
371
+ text = "\n".join(paras)
372
+ chunks.append({"text": text, "source": "pubmed", "pmid": pmid})
373
+ except Exception:
374
+ pass
375
+
376
+ if query_or_pmid.isdigit():
377
+ _efetch(query_or_pmid); return chunks
378
 
379
+ pmids: List[str] = []
380
+ for attempt in range(retries + 1):
381
+ try:
382
+ xml = _get_with_backoff(
383
+ "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi",
384
+ _ncbi_params({"db":"pubmed","term":query_or_pmid, "retmax":max_papers})
385
+ )
386
+ root = ET.fromstring(xml)
387
+ pmids = [e.text for e in root.findall(".//Id") if e is not None and e.text]
388
+ break
389
+ except Exception:
390
+ if attempt == retries: return []
391
+ time.sleep(0.5 * (2 ** attempt))
392
+
393
+ for pmid in pmids[:max_papers]:
394
+ _efetch(pmid)
395
+ return chunks
396
+
397
+ STOPWORDS = set("the a an of and for with without to on in by from into over under how what why where when is are was were be been being this that these those it its as about".split())
398
+
399
+ def _parse_year(y: str) -> int:
400
+ try:
401
+ return int(re.findall(r"\d{4}", y or "")[0])
402
+ except Exception:
403
+ return 0
404
+
405
+ def _is_msk_paper(title: str, journal: str, year: str = "") -> bool:
406
+ t = f"{title or ''} {journal or ''}".lower()
407
+ must_body = any(k in t for k in ["femur","femoral","hip","proximal femur","long bone","tibia","humerus"])
408
+ must_method = any(k in t for k in ["ct","qct","finite element","structural rigidity","ctra","rigidity","bending","torsion"])
409
+ if not (must_body and must_method): return False
410
+ year_i = _parse_year(year)
411
+ if year_i and not (2000 <= year_i <= 2025): return False
412
+ return True
413
+
414
+ @lru_cache(maxsize=4096)
415
+ def fetch_pubmed_citations(query: str, max_results: int = 5) -> List[str]:
416
+ try:
417
+ xml = _get_with_backoff(
418
+ "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi",
419
+ _ncbi_params({"db":"pubmed","term":query, "retmax":max_results})
420
  )
421
+ root = ET.fromstring(xml)
422
+ pmids = [elem.text for elem in root.findall(".//Id") if elem is not None and elem.text]
423
+ if not pmids: return []
424
+ except Exception:
425
+ return []
426
 
427
+ try:
428
+ xml = _get_with_backoff(
429
+ "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi",
430
+ _ncbi_params({"db":"pubmed","id":",".join(pmids)})
431
  )
432
+ summary_root = ET.fromstring(xml)
433
+ except Exception:
434
+ return []
435
+
436
+ citations: List[str] = []
437
+ for docsum in summary_root.findall(".//DocSum"):
438
+ pmid = docsum.findtext("Id", default="")
439
+ title = journal = year = doi = ""
440
+ authors: List[str] = []
441
+ for item in docsum.findall("Item"):
442
+ name = item.get("Name", "")
443
+ if name == "Title": title = item.text or ""
444
+ elif name == "FullJournalName": journal = item.text or ""
445
+ elif name == "PubDate": year = (item.text or "").split()[0]
446
+ elif name == "AuthorList":
447
+ for au in item.findall("Item"):
448
+ if au.text: authors.append(au.text)
449
+ elif name == "ArticleIds":
450
+ for sub in item.findall("Item"):
451
+ if sub.get("Name") == "doi":
452
+ doi = sub.text or ""
453
+ if not _is_msk_paper(title, journal, year): continue
454
+ first_author = authors[0] if authors else ""
455
+ auth_str = f"{first_author} et al." if first_author else ""
456
+ parts = [p for p in [auth_str, title, journal, year] if p]
457
+ cit = ", ".join(parts).strip().rstrip(",")
458
+ if pmid: cit += f"; PMID:{pmid}"
459
+ if doi: cit += f" DOI:{doi}"
460
+ if cit: citations.append(cit)
461
+ return citations[:max_results]
462
+
463
+ def _compact_terms(q: str) -> str:
464
+ words = re.findall(r"[A-Za-z0-9\-]+", q.lower())
465
+ keep = [w for w in words if w not in STOPWORDS and len(w) > 2]
466
+ return " ".join(keep)[:200]
467
+
468
+ def _biomechish(q: str) -> bool:
469
+ return bool(re.search(r"\b(femur|femoral|hip|bone|qct|ctra|rigidity|bending|torsion|elastic modulus|finite\s+element|fea)\b", q, re.I))
470
+ def _is_fe_override(q: str) -> bool:
471
+ return bool(_FE_TOKENS.search(q))
472
+
473
+ _CONTRA_NO_EFFECT = re.compile(r"\b(no\s+significant\s+difference|no\s+effect|not\s+significant)\b", re.I)
474
+ _CONTRA_CHANGE = re.compile(r"\b(increase[ds]?|decrease[ds]?|higher|lower|greater|reduced?)\b", re.I)
475
+ def _has_conflict(text: str) -> bool:
476
+ return bool(_CONTRA_NO_EFFECT.search(text) and _CONTRA_CHANGE.search(text))
477
+
478
+ HARDCODED_CITS = {
479
+ "EA": [
480
+ "Morgan EF et al., Mechanical properties of cortical bone…, J Biomech, 2003; PMID:12547357",
481
+ "Turner CH, Burr DB., Experimental techniques for bone mechanics, Bone, 1993; PMID:8252072"
482
+ ],
483
+ "EI": [
484
+ "Courtney AC et al., Age-related reductions in the strength of the femur…, J Bone Miner Res, 1995; PMID:7584933",
485
+ "Bell KL et al., Regional Heterogeneity of the Proximal Femur…, Bone, 1999; PMID:10574202"
486
+ ],
487
+ "GJ": [
488
+ "Cowin SC., Bone Mechanics Handbook (torsion of bone cross-sections), CRC Press, 2001.",
489
+ "Vollmer M et al., Long bone torsion testing methods, J Biomech, 1987; PMID:3670157"
490
+ ]
491
+ }
492
+
493
+ def _fallback_cits_for(term: str) -> List[str]:
494
+ return HARDCODED_CITS.get(term.upper(), [])
495
+
496
+ def detect_lab(q: str) -> str:
497
+ ql = q.lower()
498
+ if "freedman" in ql: return "freedman"
499
+ if "alboro" in ql or "alborno" in ql: return "alboro"
500
+ return "nazarian"
501
+
502
+ def build_lab_query(core_q: str, lab: str = "nazarian") -> str:
503
+ topics = [
504
+ "femur","femoral neck","hip","proximal femur",
505
+ "CT","QCT","micro-CT","rigidity","CTRA","structural rigidity",
506
+ "bending","torsional","axial","failure load","modulus","Hounsfield"
507
+ ]
508
+ ta = " OR ".join(f'"{t}"[Title/Abstract]' for t in topics)
509
+ if lab == "freedman":
510
+ author = '("Freedman BA"[Author] OR "Freedman"[Author])'
511
+ elif lab == "alboro":
512
+ author = '("Alboro"[Author] OR "Alborno"[Author])'
513
+ else:
514
+ author = '("Nazarian A"[Author] OR "Ara Nazarian"[Full Author Name])'
515
+ date = '("2000"[Date - Publication] : "3000"[Date - Publication])'
516
+ return f"{author} AND ({ta}) AND {date}"
517
+
518
+ def retrieve_context(query: str, top_k: int = 10) -> List[Dict[str, Any]]:
519
+ q = query.strip()
520
+ if _ANATOMY_OR_HISTORY.search(q) and not _biomechish(q):
521
+ wiki = wiki_summary_allow(q, sentences=4)
522
+ if wiki:
523
+ dlog("WIKI", "Wikipedia biomechanics fallback hit")
524
+ return [{"text": wiki, "source": "wikipedia"}]
525
+
526
+ pm = re.search(r"pmid[:\s]*(\d+)", q, re.IGNORECASE)
527
+ if pm:
528
+ dlog("PMID", f"PMID inline {pm.group(1)}")
529
+ return fetch_pubmed_chunks(pm.group(1), max_papers=1)
530
+
531
+ if not (_CT_RIGIDITY_TOKENS.search(q) or _is_fe_override(q)):
532
+ dlog("FALLBACK", "No CT/rigidity/FE tokens → try PubMed/Wiki")
533
+ results = fetch_pubmed_chunks(q)
534
+ if results:
535
+ dlog("PUBMED", "PubMed search hit")
536
+ return results
537
+ if _biomechish(q):
538
+ wiki = wiki_summary_allow(q, sentences=3)
539
+ if wiki:
540
+ dlog("WIKI", "Wikipedia biomechanics fallback hit")
541
+ return [{"text": wiki, "source": "wikipedia"}]
542
+ dlog("RETRIEVAL", "No results found")
543
+ return []
544
+
545
+ # FAISS path
546
+ q_emb = embed_model.encode([q], convert_to_numpy=True).astype("float32")
547
+ if _IS_IP:
548
+ faiss.normalize_L2(q_emb)
549
+ D, I = index.search(q_emb, top_k)
550
+ results: List[Dict[str, Any]] = []
551
+ for dist, idx_ in zip(D[0], I[0]):
552
+ if idx_ < 0: continue
553
+ item = all_chunks[idx_].copy()
554
+ item["score"] = float(dist)
555
+ item["text"] = _hydrate_text(item)
556
+ if not item["text"]: continue
557
+ results.append(item)
558
+
559
+ if results:
560
+ scored: List[Dict[str, Any]] = []
561
+ for it in results:
562
+ rel = _rel_score(it.get("text", ""), it.get("title", ""), REL_CFG)
563
+ rel = _boost_by_author(it.get("pmid"), rel, REL_CFG)
564
+ rel = _mesh_boost(it.get("pmid"), rel, REL_CFG)
565
+ it["_rel"] = rel
566
+ scored.append(it)
567
+ results = sorted(scored, key=lambda x: (x.get("_rel", 0), x.get("score", 0)), reverse=True)
568
+ min_rel = int(REL_CFG.get("min_rel_to_use_faiss", 3))
569
+ positives = [
570
+ r for r in results
571
+ if r.get("_rel", 0) >= min_rel and _MSK_MUST.search((r.get("title","")+" "+r.get("text","")))
572
+ ]
573
+ positives = _dedup_by_pmid_or_title(positives)
574
+ if positives:
575
+ dlog("FAISS", f"hit={len(positives)} (top rel={positives[0].get('_rel')} score={positives[0].get('score'):.3f})")
576
+ return positives[:top_k]
577
+ else:
578
+ dlog("FALLBACK", "FAISS results off-topic → PubMed fallback")
579
+
580
+ results = fetch_pubmed_chunks(q)
581
+ if results:
582
+ dlog("PUBMED", "PubMed search hit")
583
+ return results
584
+
585
+ if _biomechish(q):
586
+ wiki = wiki_summary_allow(q, sentences=3)
587
+ if wiki:
588
+ dlog("WIKI", "Wikipedia biomechanics fallback hit")
589
+ return [{"text": wiki, "source": "wikipedia"}]
590
+
591
+ dlog("RETRIEVAL", "No results at all")
592
+ return []
593
+
594
+ def build_prompt(chunks: List[Dict[str, Any]], question: str) -> str:
595
+ header = (
596
+ "You are Askstein (orthopedic biomechanics). Use ONLY the [Context] to answer. "
597
+ "If the context is insufficient, say 'I don’t know based on the provided context.' "
598
+ "Stay within musculoskeletal CT-based rigidity (EA, EI, GJ), femur/hip, CTRA/QCT, or FE modeling of these. "
599
+ "Do not discuss cardiology, neurology, or unrelated domains."
600
+ )
601
+ cleaned = []
602
+ per_chunk_chars = 1600
603
+ for c in chunks:
604
+ t = _to_text(c)
605
+ if t: cleaned.append(t[:per_chunk_chars])
606
+ context = "\n\n".join(cleaned)
607
+ return f"{header}\n\n[Context]:\n{context}\n\n[Question]:\n{question}\n"
608
+
609
+ def _decode_generated(out_ids, in_len: int) -> str:
610
+ gen = out_ids[0][in_len:]
611
+ return tokenizer_lm.decode(gen, skip_special_tokens=True).lstrip(". \n").strip()
612
+
613
+ def _synthesize_answer(chunks: List[Dict[str, Any]], question: str) -> str:
614
+ prompt = build_prompt(chunks, question)
615
+ inputs = tokenizer_lm(prompt, return_tensors="pt").to(device)
616
+ in_len = inputs["input_ids"].shape[-1]
617
+ out = _generate(inputs, grounded=True)
618
+ answer = _decode_generated(out, in_len)
619
+ return _post_clean(answer)
620
 
621
+ def _answer_from_chunks(chunks: List[Dict[str, Any]], question: str) -> str:
622
+ joined = " ".join(_to_text(c) for c in chunks if _to_text(c))
623
+ if _has_conflict(joined):
624
+ dlog("SYNTH", "Conflict detected summarize")
625
+ return _synthesize_answer(chunks, question)
626
+ return _synthesize_answer(chunks, question)
627
+
628
+ def deterministic_definitions_text(core_q: str) -> Optional[str]:
629
+ q_lower = core_q.lower()
630
+ if "define axial rigidity" in q_lower or "what is axial rigidity" in q_lower:
631
+ return ("Axial rigidity (EA) is Σ(Eᵢ·dAᵢ) across a CT slice; units: N. "
632
+ "Modulus E per voxel comes from a density–modulus calibration; areas dAᵢ are voxel areas.")
633
+ if "define bending rigidity" in q_lower or "what is bending rigidity" in q_lower:
634
+ return ("Bending rigidity (EI) is Σ(Eᵢ·dAᵢ·yᵢ²) about a given axis; units: N·mm². "
635
+ "yᵢ is distance to the neutral axis; computed slice-by-slice from QCT.")
636
+ if ("define torsional rigidity" in q_lower) or ("what is torsional rigidity" in q_lower) or ("define gj" in q_lower):
637
+ return ("Torsional rigidity (GJ) = shear modulus G times polar moment J. "
638
+ "In QCT, J ≈ Σ(dAᵢ·rᵢ²) about the centroid; G ≈ E/(2(1+ν)).")
639
+ if "qct" in q_lower and ("torsional" in q_lower or "gj" in q_lower):
640
+ return ("From QCT, torsional rigidity is estimated as GJ, where J ≈ Σ(dAᵢ·rᵢ²) about the slice centroid and "
641
+ "G = E/(2(1+ν)) from the voxel E map (ν≈0.3). Compute per-slice and report the minimum.")
642
+ if re.search(r"\b(outline|steps|workflow|protocol)\b.*\b(ct|qct).*(rigidity|ea|ei|gj)", q_lower):
643
+ return (
644
+ "CT-based structural rigidity (CTRA/QCT) workflow:\n"
645
+ "1) Acquire QCT (≤1 mm; density phantom).\n"
646
+ "2) Preprocess & segment bone.\n"
647
+ "3) HU→ρ; ρ→E calibration.\n"
648
+ "4) Cross-sections along neck axis.\n"
649
+ "5) EA, EI_x/EI_y, GJ (G≈E/(2(1+ν))).\n"
650
+ "6) Extract minima & validate vs FEA/mech tests."
651
+ )
652
+ if re.search(r"\b(modulus)\b.*\brigidity\b|\bdefine\s+modulus\b", q_lower):
653
+ return ("Elastic modulus (E) is a material property (Pa). "
654
+ "Rigidity is structural (EA, EI, GJ). Modulus ≠ rigidity.")
655
+ return None
656
+
657
+ def ask(question: str) -> str:
658
+ q = question.strip()
659
+ m = re.search(r"pmid[:\s]*(\d+)", q, re.IGNORECASE)
660
+ if m:
661
+ pmid = m.group(1)
662
+ chunks = fetch_pubmed_chunks(pmid, max_papers=1)
663
+ return "\n".join(c.get("text", "") for c in chunks) or "Sorry, no abstract found."
664
+
665
+ if _PAPERS_INTENT.search(q):
666
+ core_q = re.sub(_PAPERS_INTENT, "", q, flags=re.I).strip() or "CT/QCT structural rigidity femur hip finite element"
667
+ compact = _compact_terms(core_q)
668
+ pm_query = (
669
+ f'(({compact}) AND (hip[TiAb] OR femur[TiAb] OR femoral[TiAb])) AND '
670
+ '("Finite Element Analysis"[MeSH Terms] OR finite element[TiAb] OR QCT[TiAb] OR CT[TiAb] OR rigidity[TiAb]) '
671
+ 'AND ("2000"[DP] : "2025"[DP])'
672
  )
673
+ cits = fetch_pubmed_citations(pm_query, max_results=5)
674
+ return "Recommended papers:\n" + "\n".join(f"- {c}" for c in cits) if cits else "Sorry, no good matches."
675
+
676
+ comp = re.match(r"(.+?)\s+and\s+(?:cite|references?|studies?|papers?)", q, flags=re.IGNORECASE)
677
+ if comp:
678
+ core_q = comp.group(1).strip()
679
+ det_text = deterministic_definitions_text(core_q)
680
+ used_term = None
681
+ if det_text:
682
+ explanation = det_text
683
+ lq = core_q.lower()
684
+ if ("torsional" in lq) or ("gj" in lq):
685
+ used_term = "GJ"
686
+ pm_query = ('(torsion[TiAb] OR "polar moment"[TiAb] OR GJ[TiAb]) AND '
687
+ '("Bone and Bones"[MeSH] OR Femur[TiAb]) AND '
688
+ '("Finite Element Analysis"[MeSH] OR QCT[TiAb] OR CT[TiAb]) AND '
689
+ '("2000"[DP] : "2025"[DP])')
690
+ elif ("bending" in lq) or ("ei" in lq):
691
+ used_term = "EI"
692
+ pm_query = ('(bending[TiAb] OR "second moment"[TiAb] OR EI[TiAb]) AND '
693
+ '("Bone and Bones"[MeSH] OR Femur[TiAb]) AND '
694
+ '("Finite Element Analysis"[MeSH] OR QCT[TiAb] OR CT[TiAb]) AND '
695
+ '("2000"[DP] : "2025"[DP])')
696
+ else:
697
+ used_term = "EA"
698
+ pm_query = ('("axial rigidity"[TiAb] OR EA[TiAb] OR "axial stiffness"[TiAb]) AND '
699
+ '("Bone and Bones"[MeSH] OR Femur[TiAb]) AND '
700
+ '("Finite Element Analysis"[MeSH] OR QCT[TiAb] OR CT[TiAb]) AND '
701
+ '("2000"[DP] : "2025"[DP])')
702
+ citations = fetch_pubmed_citations(pm_query, max_results=5)
703
+ if not citations and used_term:
704
+ dlog("CITE", f"PubMed empty → fallback {used_term}")
705
+ citations = _fallback_cits_for(used_term)
706
+ else:
707
+ explanation = _answer_from_chunks(retrieve_context(core_q, top_k=5), core_q)
708
+ pm_query = f'"{core_q}"[Title/Abstract]'
709
+ citations = fetch_pubmed_citations(pm_query, max_results=5)
710
+ if not citations:
711
+ lab = detect_lab(core_q)
712
+ pm_query = build_lab_query(core_q, lab=lab)
713
+ citations = fetch_pubmed_citations(pm_query, max_results=5)
714
+ if not citations:
715
+ compact = _compact_terms(core_q)
716
+ pm_query = (
717
+ f'({compact}) AND ("Bone and Bones"[MeSH] OR Femur[TiAb] OR Hip[TiAb] '
718
+ f'OR Rigidity[TiAb] OR "Tomography, X-Ray Computed"[MeSH] OR "Finite Element Analysis"[MeSH]) '
719
+ f'NOT (heart[TiAb] OR cardiac[TiAb] OR brain[TiAb] OR skull[TiAb] OR EGFR[TiAb]) '
720
+ f'AND ("2000"[DP] : "2025"[DP])'
721
+ )
722
+ citations = fetch_pubmed_citations(pm_query, max_results=5)
723
+ resp = explanation
724
+ if citations:
725
+ resp += "\n\nCitations:\n" + "\n".join(citations)
726
+ else:
727
+ resp += f"\n\nSorry, no relevant citations found for “{core_q}.”"
728
+ return _ensure_min_answer(_post_clean(resp))
729
+
730
+ det_answer = deterministic_definitions_text(q)
731
+ if det_answer:
732
+ dlog("ASK", "Deterministic definition/workflow fired")
733
+ return det_answer
734
+
735
+ if not (_MSK_MUST.search(q) or _is_fe_override(q)):
736
+ chunks = retrieve_context(q, top_k=5)
737
+ if chunks:
738
+ dlog("CLEAN", "Post-clean applied")
739
+ answer = _answer_from_chunks(chunks, q)
740
+ return _ensure_min_answer(_post_clean(answer)) or "I don’t know."
741
+ return "I don’t know based on the provided context."
742
+
743
+ chunks = retrieve_context(q, top_k=5)
744
+ if not chunks:
745
+ return "I don’t know based on the provided context."
746
+ dlog("CLEAN", "Post-clean applied")
747
+ answer = _answer_from_chunks(chunks, q)
748
+ return _ensure_min_answer(_post_clean(answer))
749
+
750
+ # ================== UI: NAME GATE + PER-ANSWER FEEDBACK ==================
751
+ def _now_iso():
752
+ return datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
753
+
754
+ def init_session():
755
+ return {
756
+ "session_id": str(uuid.uuid4()),
757
+ "first_name": "",
758
+ "last_name": "",
759
+ "last_q": "",
760
+ "last_a": "",
761
+ }
762
+
763
+ def enter_app(first_name, last_name, state):
764
+ first_name = (first_name or "").strip()
765
+ last_name = (last_name or "").strip()
766
+ if not first_name or not last_name:
767
+ return gr.update(visible=True), gr.update(visible=False), state, "Please enter both first and last name."
768
+ state["first_name"] = first_name
769
+ state["last_name"] = last_name
770
+ return gr.update(visible=False), gr.update(visible=True), state, f"Welcome, {first_name}! You can start chatting."
771
+
772
+ def predict(message, chat_history, state):
773
+ answer = ask(message)
774
+ chat_history = chat_history + [(message, answer)]
775
+ state["last_q"] = message
776
+ state["last_a"] = answer
777
+ return (
778
+ chat_history,
779
+ "", # clear input
780
+ gr.update(visible=True), # show feedback pane
781
+ gr.update(value=None), # reset rating
782
+ gr.update(value=""), # reset comment
783
+ state
784
+ )
785
 
786
+ def _push_feedback_to_hub():
787
+ """Optional: upload feedback.csv to Space repo path analytics/feedback.csv"""
788
+ if not (PUSH_FEEDBACK and HF_TOKEN and SPACE_REPO_ID and os.path.exists(FEEDBACK_PATH)):
789
+ return
790
+ try:
791
+ api = HfApi()
792
+ api.upload_file(
793
+ path_or_fileobj=FEEDBACK_PATH,
794
+ path_in_repo="analytics/feedback.csv",
795
+ repo_id=SPACE_REPO_ID,
796
+ repo_type="space",
797
+ token=HF_TOKEN
798
  )
799
+ dlog("FEEDBACK", "Uploaded analytics/feedback.csv to Hub")
800
+ except Exception as e:
801
+ dlog("FEEDBACK", f"Hub upload failed: {e}")
802
+
803
+ def save_feedback(rating, comment, state):
804
+ if rating is None:
805
+ return "Please select a rating (1–5).", gr.update(visible=True)
806
+ row = {
807
+ "timestamp_utc": _now_iso(),
808
+ "session_id": state["session_id"],
809
+ "first_name": state["first_name"],
810
+ "last_name": state["last_name"],
811
+ "question": state["last_q"],
812
+ "answer": state["last_a"],
813
+ "rating": rating,
814
+ "comment": (comment or "").strip(),
815
+ }
816
+ header = ["timestamp_utc","session_id","first_name","last_name","question","answer","rating","comment"]
817
+ try:
818
+ file_exists = os.path.exists(FEEDBACK_PATH)
819
+ with open(FEEDBACK_PATH, "a", newline="", encoding="utf-8") as f:
820
+ w = csv.DictWriter(f, fieldnames=header)
821
+ if not file_exists:
822
+ w.writeheader()
823
+ w.writerow(row)
824
+ _push_feedback_to_hub()
825
+ return "Thanks for the feedback! ✅", gr.update(visible=False)
826
+ except Exception as e:
827
+ return f"Failed to save feedback: {e}", gr.update(visible=True)
828
+
829
+ with gr.Blocks(theme="soft") as demo:
830
+ gr.Markdown("# Askstein — Orthopedic Biomechanics Chat (CT/QCT Rigidity, FE)")
831
+ gr.Markdown("Grounded answers (FAISS + PubMed). Please enter your name to continue.")
832
+
833
+ state = gr.State(init_session())
834
+
835
+ # ---- Gate ----
836
+ gate = gr.Group(visible=True)
837
+ with gate:
838
+ with gr.Row():
839
+ first_tb = gr.Textbox(label="First name", placeholder="e.g., Shubh", scale=1)
840
+ last_tb = gr.Textbox(label="Last name", placeholder="e.g., Laiwala", scale=1)
841
+ enter_btn = gr.Button("Enter", variant="primary")
842
+ gate_msg = gr.Markdown("", elem_classes=["text-sm"])
843
+
844
+ # ---- App (hidden until gate passes) ----
845
+ app = gr.Group(visible=False)
846
+ with app:
847
+ chat = gr.Chatbot(label="Askstein", height=430, type="tuples")
848
+ with gr.Row():
849
+ user_in = gr.Textbox(placeholder="Ask a biomechanics question…", scale=5)
850
+ send_btn = gr.Button("Send", variant="primary", scale=1)
851
+ clear_btn = gr.Button("Clear chat")
852
+
853
+ feedback_grp = gr.Group(visible=False)
854
+ with feedback_grp:
855
+ gr.Markdown("### How helpful was this answer?")
856
+ rating = gr.Radio(choices=[1,2,3,4,5], label="Rating (1=poor, 5=great)")
857
+ comment = gr.Textbox(label="Optional comment", placeholder="What was good or missing?")
858
+ submit_fb = gr.Button("Submit feedback")
859
+ fb_status = gr.Markdown("")
860
+
861
+ # Wiring
862
+ enter_btn.click(
863
+ fn=enter_app,
864
+ inputs=[first_tb, last_tb, state],
865
+ outputs=[gate, app, state, gate_msg],
866
+ )
867
+
868
+ send_btn.click(predict, inputs=[user_in, chat, state],
869
+ outputs=[chat, user_in, feedback_grp, rating, comment, state])
870
+ user_in.submit(predict, inputs=[user_in, chat, state],
871
+ outputs=[chat, user_in, feedback_grp, rating, comment, state])
872
+
873
+ clear_btn.click(lambda: ([], "", gr.update(visible=False), None, "", init_session()),
874
+ inputs=None,
875
+ outputs=[chat, user_in, feedback_grp, rating, comment, state])
876
 
877
+ submit_fb.click(
878
+ fn=save_feedback,
879
+ inputs=[rating, comment, state],
880
+ outputs=[fb_status, feedback_grp],
881
+ )
882
 
883
+ demo.queue(max_size=32).launch()
 
884