crazycrazypete commited on
Commit
0fbe5f9
·
verified ·
1 Parent(s): 4b14094

Upload folder using huggingface_hub

Browse files
Updates/app_latest_working.py ADDED
@@ -0,0 +1,1619 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import json
4
+ import math
5
+ import hashlib
6
+ import tempfile
7
+ from dataclasses import dataclass
8
+ from datetime import datetime, date
9
+ from typing import Any, Dict, List, Optional, Tuple
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+
14
+ import fitz # PyMuPDF
15
+ import faiss
16
+ from sentence_transformers import SentenceTransformer
17
+ from rapidfuzz import fuzz, process
18
+
19
+ import gradio as gr
20
+ from openai import OpenAI
21
+
22
+
23
+ # ============================
24
+ # Settings
25
+ # ============================
26
+ TODAY = date(2026, 1, 18)
27
+ OPENAI_MODEL = "gpt-5.2"
28
+ OPENAI_REASONING = {"effort": "high"}
29
+ MATCH_OK = 80
30
+
31
+ EMBED_MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2"
32
+ PARSEC_CONTEXT_BEFORE = 900
33
+ PARSEC_CONTEXT_AFTER = 1600
34
+
35
+
36
+ # ============================
37
+ # OpenAI client (HF Space secret: OPENAI_API_KEY)
38
+ # ============================
39
+ API_KEY = os.getenv("OPENAI_API_KEY", "").strip()
40
+ client = OpenAI(api_key=API_KEY) if API_KEY else None
41
+
42
+ # ----------------------------
43
+ # Gradio state helpers
44
+ # Keep state as a JSON STRING to avoid schema issues on Hugging Face.
45
+ # ----------------------------
46
+ def state_load(st_json: str) -> Dict[str, Any]:
47
+ try:
48
+ if not st_json:
49
+ return {}
50
+ return json.loads(st_json) if isinstance(st_json, str) else {}
51
+ except Exception:
52
+ return {}
53
+
54
+ def state_dump(st: Dict[str, Any]) -> str:
55
+ try:
56
+ return json.dumps(st or {}, ensure_ascii=False)
57
+ except Exception:
58
+ return "{}"
59
+
60
+
61
+
62
+ # ============================
63
+ # Helpers
64
+ # ============================
65
+ def norm_text(s: Any) -> str:
66
+ try:
67
+ if s is None or (isinstance(s, float) and math.isnan(s)) or pd.isna(s):
68
+ return ""
69
+ except Exception:
70
+ pass
71
+ s = str(s).strip().lower()
72
+ s = re.sub(r"[^a-z0-9\s\-\/]", " ", s)
73
+ s = re.sub(r"\s+", " ", s).strip()
74
+ return s
75
+
76
+ def safe_str(v: Any) -> str:
77
+ if v is None or (isinstance(v, float) and pd.isna(v)) or pd.isna(v):
78
+ return ""
79
+ return str(v).strip()
80
+
81
+ def is_5g(modem_type: Any) -> bool:
82
+ s = norm_text(modem_type)
83
+ return ("5g" in s) or ("nr" in s)
84
+
85
+ def json_load_safe(s: str) -> Dict[str, Any]:
86
+ try:
87
+ return json.loads(s)
88
+ except Exception:
89
+ return {}
90
+
91
+ def gpt_json(system: str, payload: Dict[str, Any], max_tokens: int = 600) -> Dict[str, Any]:
92
+ if client is None:
93
+ return {}
94
+ resp = client.responses.create(
95
+ model=OPENAI_MODEL,
96
+ reasoning=OPENAI_REASONING,
97
+ input=[{"role":"system","content":system},{"role":"user","content":json.dumps(payload)}],
98
+ max_output_tokens=max_tokens,
99
+ )
100
+ return json_load_safe(getattr(resp, "output_text", "") or "")
101
+
102
+
103
+ def gpt_answer_md(system: str, user: str, max_tokens: int = 650) -> str:
104
+ """Return a rep-friendly markdown answer."""
105
+ if client is None:
106
+ return "No API key is configured, so I can't answer detailed questions right now."
107
+ resp = client.responses.create(
108
+ model=OPENAI_MODEL,
109
+ reasoning=OPENAI_REASONING,
110
+ input=[
111
+ {"role": "system", "content": system},
112
+ {"role": "user", "content": user},
113
+ ],
114
+ max_output_tokens=max_tokens,
115
+ )
116
+ return (getattr(resp, "output_text", "") or "").strip()
117
+
118
+
119
+ # ============================
120
+ # Load data
121
+ # ============================
122
+ EOS_PATH = "routers_eos_eol_by_sku.csv"
123
+ DEC_PATH = "dec2025routers.csv"
124
+ PARSEC_PDF = "ParsecCatalog.pdf"
125
+
126
+ if not os.path.exists(EOS_PATH):
127
+ raise FileNotFoundError(f"Missing {EOS_PATH} in repo.")
128
+ if not os.path.exists(DEC_PATH):
129
+ raise FileNotFoundError(f"Missing {DEC_PATH} in repo.")
130
+ if not os.path.exists(PARSEC_PDF):
131
+ raise FileNotFoundError(f"Missing {PARSEC_PDF} in repo.")
132
+
133
+ df_eos = pd.read_csv(EOS_PATH).copy()
134
+ df_dec = pd.read_csv(DEC_PATH).copy()
135
+
136
+
137
+ def _canonize_eos_columns(df: pd.DataFrame) -> pd.DataFrame:
138
+ """Normalize lifecycle CSV column names (case-insensitive) and create expected columns."""
139
+ # Map various header spellings to canonical names used by the app
140
+ mapping = {}
141
+ for c in df.columns:
142
+ k = str(c).strip().lower().replace(" ", "_")
143
+ if k in {"sku", "model", "device", "device_sku"}:
144
+ mapping[c] = "sku"
145
+ elif k in {"manufacturer", "make", "vendor"}:
146
+ mapping[c] = "manufacturer"
147
+ elif k in {"device_type", "type"}:
148
+ mapping[c] = "device_type"
149
+ elif k in {"end_of_sale", "eos", "end_sale", "end_of_sales"}:
150
+ mapping[c] = "end_of_sale"
151
+ elif k in {"end_of_life", "eol", "end_life"}:
152
+ mapping[c] = "end_of_life"
153
+ elif k in {"suggested_replacement", "replacement_4g", "lte_replacement", "replacement_lte", "replacement"}:
154
+ mapping[c] = "suggested_replacement"
155
+ elif k in {"advanced_5g_option", "replacement_5g", "fiveg_replacement", "5g_replacement", "upgrade_5g"}:
156
+ mapping[c] = "advanced_5g_option"
157
+ elif k in {"region", "market"}:
158
+ mapping[c] = "region"
159
+ elif k in {"notes", "note"}:
160
+ mapping[c] = "notes"
161
+ elif k in {"description", "device_description", "name"}:
162
+ mapping[c] = "description"
163
+
164
+ df = df.rename(columns=mapping).copy()
165
+
166
+ # Create expected columns if missing
167
+ if "sku" not in df.columns:
168
+ # Try the common capitalized header as a fallback
169
+ if "SKU" in df.columns:
170
+ df["sku"] = df["SKU"].astype(str)
171
+ else:
172
+ df["sku"] = ""
173
+
174
+ if "manufacturer" not in df.columns:
175
+ df["manufacturer"] = ""
176
+
177
+ if "device_type" not in df.columns:
178
+ df["device_type"] = ""
179
+
180
+ if "description" not in df.columns:
181
+ # If the simplified file removed description, use SKU as description (still searchable)
182
+ df["description"] = df["sku"].astype(str)
183
+
184
+ if "notes" not in df.columns:
185
+ df["notes"] = ""
186
+
187
+ if "region" not in df.columns:
188
+ df["region"] = ""
189
+
190
+ if "suggested_replacement" not in df.columns:
191
+ df["suggested_replacement"] = ""
192
+
193
+ if "advanced_5g_option" not in df.columns:
194
+ df["advanced_5g_option"] = ""
195
+
196
+ if "end_of_sale" not in df.columns:
197
+ df["end_of_sale"] = ""
198
+
199
+ if "end_of_life" not in df.columns:
200
+ df["end_of_life"] = ""
201
+
202
+ return df
203
+
204
+ df_eos = _canonize_eos_columns(df_eos)
205
+
206
+
207
+ def region_ok(x: Any) -> bool:
208
+ s = str(x or "").strip().lower()
209
+ if not s:
210
+ return True
211
+ if "not specified" in s:
212
+ return True
213
+ if "north america" in s:
214
+ return True
215
+ if re.search(r"\busa\b", s):
216
+ return True
217
+ if re.search(r"\bunited\s+states\b", s):
218
+ return True
219
+ if re.search(r"\bu\.?s\.?\b", s):
220
+ return True
221
+ return False
222
+
223
+ if "region" in df_eos.columns:
224
+ df_eos = df_eos[df_eos["region"].apply(region_ok)].reset_index(drop=True)
225
+
226
+ # Maker mapping (includes Teltonika)
227
+ CANON_MAKER = {
228
+ "CRADLEPOINT": {"cradlepoint", "ericsson", "ericsson enterprise wireless"},
229
+ "SIERRA": {"sierra", "sierra wireless", "semtech", "airlink"},
230
+ "FEENEY": {"feeney", "feeney wireless", "inseego"},
231
+ "DIGI": {"digi", "accelerated", "accelerated concepts"},
232
+ "CISCO_MERAKI": {"meraki", "cisco meraki"},
233
+ "CISCO": {"cisco"},
234
+ "TELTONIKA": {"teltonika"},
235
+ }
236
+
237
+ def canon_maker_from_text(s: Any) -> str:
238
+ t = norm_text(s)
239
+ for canon, terms in CANON_MAKER.items():
240
+ for term in terms:
241
+ if term in t:
242
+ return canon
243
+ return "UNKNOWN"
244
+
245
+ df_eos["_canon_make"] = df_eos["manufacturer"].apply(canon_maker_from_text) if "manufacturer" in df_eos.columns else "UNKNOWN"
246
+ df_eos["_norm_sku"] = df_eos["sku"].apply(norm_text) if "sku" in df_eos.columns else ""
247
+ df_eos["_norm_desc"] = df_eos["description"].apply(norm_text) if "description" in df_eos.columns else ""
248
+ df_eos["_norm_notes"] = df_eos["notes"].apply(norm_text) if "notes" in df_eos.columns else ""
249
+
250
+ df_dec["_canon_make"] = df_dec["Make"].apply(canon_maker_from_text) if "Make" in df_dec.columns else "UNKNOWN"
251
+ df_dec["_norm_model"] = df_dec["Model"].apply(norm_text) if "Model" in df_dec.columns else ""
252
+ df_dec["_is5g"] = df_dec["Modem Type"].apply(is_5g) if "Modem Type" in df_dec.columns else False
253
+
254
+
255
+ # ============================
256
+ # Date helpers
257
+ # ============================
258
+ @dataclass
259
+ class ParsedDate:
260
+ raw: str
261
+ kind: str
262
+ value: Optional[date]
263
+
264
+ def parse_date_field(x: Any) -> ParsedDate:
265
+ raw = str(x or "").strip()
266
+ if not raw:
267
+ return ParsedDate(raw="", kind="missing", value=None)
268
+
269
+ # Common US formats: M/D/YY or M/D/YYYY (e.g., 6/24/24, 9/30/21)
270
+ for fmt in ("%m/%d/%y", "%m/%d/%Y", "%-m/%-d/%y", "%-m/%-d/%Y"):
271
+ try:
272
+ dt = datetime.strptime(raw, fmt).date()
273
+ return ParsedDate(raw=raw, kind="full", value=dt)
274
+ except Exception:
275
+ pass
276
+
277
+ # ISO-ish: YYYY
278
+ if re.fullmatch(r"\d{4}", raw):
279
+ y = int(raw)
280
+ if y == TODAY.year:
281
+ return ParsedDate(raw=raw, kind="year", value=date(y, 1, 1))
282
+ if y < TODAY.year:
283
+ return ParsedDate(raw=raw, kind="year", value=date(y, 1, 1))
284
+ return ParsedDate(raw=raw, kind="year", value=date(y, 12, 31))
285
+
286
+ # YYYY-MM
287
+ if re.fullmatch(r"\d{4}-\d{2}", raw):
288
+ try:
289
+ y, m = raw.split("-")
290
+ return ParsedDate(raw=raw, kind="year_month", value=date(int(y), int(m), 1))
291
+ except Exception:
292
+ return ParsedDate(raw=raw, kind="bad", value=None)
293
+
294
+ # YYYY-MM-DD
295
+ if re.fullmatch(r"\d{4}-\d{2}-\d{2}", raw):
296
+ try:
297
+ dt = datetime.strptime(raw, "%Y-%m-%d").date()
298
+ return ParsedDate(raw=raw, kind="full", value=dt)
299
+ except Exception:
300
+ return ParsedDate(raw=raw, kind="bad", value=None)
301
+
302
+ # Last resort: leave as raw (unparsed)
303
+ return ParsedDate(raw=raw, kind="bad", value=None)
304
+
305
+ if re.fullmatch(r"\d{4}-\d{2}-\d{2}", raw):
306
+ try:
307
+ dt = datetime.strptime(raw, "%Y-%m-%d").date()
308
+ return ParsedDate(raw=raw, kind="full", value=dt)
309
+ except Exception:
310
+ return ParsedDate(raw=raw, kind="bad", value=None)
311
+
312
+ return ParsedDate(raw=raw, kind="bad", value=None)
313
+
314
+ def display_date(pd_: ParsedDate) -> str:
315
+ if pd_.kind == "missing":
316
+ return "Not listed"
317
+ if pd_.kind == "bad":
318
+ return pd_.raw or "Not listed"
319
+ return pd_.raw
320
+
321
+ def status_from_eos_eol(eos: ParsedDate, eol: ParsedDate) -> str:
322
+ if eos.value is None and eol.value is None:
323
+ return "Unknown"
324
+ if eol.value is not None and eol.value <= TODAY:
325
+ return "End of Life"
326
+ if eos.value is not None and eos.value <= TODAY:
327
+ return "End of Sale"
328
+ return "Active"
329
+
330
+ def row_to_dates_and_status(row: pd.Series) -> Tuple[str, str, str]:
331
+ eos = parse_date_field(row.get("end_of_sale"))
332
+ eol = parse_date_field(row.get("end_of_life"))
333
+ return display_date(eos), display_date(eol), status_from_eos_eol(eos, eol)
334
+
335
+
336
+ # ============================
337
+ # Embeddings + Parsec index
338
+ # ============================
339
+ embedder = SentenceTransformer(EMBED_MODEL_NAME)
340
+
341
+ def extract_pdf_text_pages(path: str) -> List[str]:
342
+ doc = fitz.open(path)
343
+ return [doc[i].get_text("text") for i in range(len(doc))]
344
+
345
+ def build_parsec_cards(pages: List[str]) -> List[str]:
346
+ cards = []
347
+ for p in pages:
348
+ for m in re.finditer(r"Standard\s+SKU:", p):
349
+ start = max(0, m.start() - PARSEC_CONTEXT_BEFORE)
350
+ end = min(len(p), m.start() + PARSEC_CONTEXT_AFTER)
351
+ c = p[start:end].strip()
352
+ if len(c) >= 200:
353
+ cards.append(c)
354
+ out, seen = [], set()
355
+ for c in cards:
356
+ h = hashlib.sha1(c.encode("utf-8")).hexdigest()
357
+ if h not in seen:
358
+ seen.add(h); out.append(c)
359
+ return out
360
+
361
+ parsec_cards = build_parsec_cards(extract_pdf_text_pages(PARSEC_PDF))
362
+ parsec_emb = embedder.encode(parsec_cards, batch_size=64, show_progress_bar=False, normalize_embeddings=True)
363
+ parsec_emb = np.asarray(parsec_emb, dtype=np.float32)
364
+ parsec_index = faiss.IndexFlatIP(parsec_emb.shape[1])
365
+ parsec_index.add(parsec_emb)
366
+
367
+
368
+ # ============================
369
+ # Device resolution
370
+ # ============================
371
+ def label_for_row(i: int) -> str:
372
+ r = df_eos.iloc[i]
373
+ return f"{r.get('sku','')} — {r.get('manufacturer','')} — {r.get('description','')}"[:220]
374
+
375
+ EOS_LABELS = [label_for_row(i) for i in range(len(df_eos))]
376
+ EOS_CORPUS = []
377
+ for _, r in df_eos.iterrows():
378
+ EOS_CORPUS.append(" ".join([r.get("_norm_sku",""), r.get("_canon_make",""), r.get("_norm_desc",""), r.get("_norm_notes","")]))
379
+
380
+ def local_candidates(query: str, top_k: int = 6) -> List[Tuple[int, int, str]]:
381
+ q = norm_text(query)
382
+ hits = process.extract(q, EOS_CORPUS, scorer=fuzz.WRatio, limit=top_k)
383
+ return [(int(idx), int(score), EOS_LABELS[int(idx)]) for _, score, idx in hits]
384
+
385
+ def gpt_choose_device(user_text: str, candidates: List[Tuple[int,int,str]]) -> Dict[str, Any]:
386
+ if client is None:
387
+ return {}
388
+ sys = "Pick which router the user meant. Never invent. Return strict JSON only."
389
+ payload = {
390
+ "user_input": user_text,
391
+ "candidates": [{"row_idx": i, "score": s, "label": lbl} for (i,s,lbl) in candidates],
392
+ "rules": [
393
+ "If one is clearly correct, return mode='ok' with row_idx.",
394
+ "If two are plausible, return mode='pick' with top 2 options."
395
+ ],
396
+ "output_schema": {"mode":"ok|pick","row_idx":"int","options":[{"row_idx":"int","label":"string"}]}
397
+ }
398
+ return gpt_json(sys, payload, max_tokens=280)
399
+
400
+ def resolve_device(user_text: str) -> Dict[str, Any]:
401
+ q = norm_text(user_text)
402
+ exact = df_eos.index[df_eos["_norm_sku"] == q].tolist()
403
+ if len(exact) == 1:
404
+ return {"mode":"ok","row_idx": int(exact[0])}
405
+ if len(exact) > 1:
406
+ opts = [{"row_idx": int(i), "label": EOS_LABELS[int(i)]} for i in exact[:2]]
407
+ return {"mode":"pick","options": opts}
408
+
409
+ cands = local_candidates(user_text, top_k=6)
410
+ if not cands:
411
+ return {"mode":"not_found"}
412
+
413
+ if cands[0][1] >= 95 and (len(cands) == 1 or (cands[0][1] - cands[1][1]) >= 8):
414
+ return {"mode":"ok","row_idx": cands[0][0]}
415
+
416
+ g = gpt_choose_device(user_text, cands)
417
+ if g.get("mode") == "ok" and isinstance(g.get("row_idx"), int):
418
+ return {"mode":"ok","row_idx": int(g["row_idx"])}
419
+
420
+ if g.get("mode") == "pick":
421
+ opts = g.get("options", []) or []
422
+ opts2 = [{"row_idx": int(o["row_idx"]), "label": str(o["label"])} for o in opts[:2] if "row_idx" in o]
423
+ if opts2:
424
+ return {"mode":"pick","options": opts2}
425
+
426
+ if len(cands) > 1:
427
+ return {"mode":"pick","options":[{"row_idx":cands[0][0],"label":cands[0][2]},{"row_idx":cands[1][0],"label":cands[1][2]}]}
428
+ return {"mode":"pick","options":[{"row_idx":cands[0][0],"label":cands[0][2]}]}
429
+
430
+
431
+ # ============================
432
+ # Replacements — lifecycle CSV source of truth
433
+ # ============================
434
+ def extract_model_token(text: str) -> str:
435
+ s = safe_str(text)
436
+ if not s:
437
+ return ""
438
+ parts = [p.strip() for p in s.split("|") if p.strip()]
439
+ candidates = parts[::-1] if parts else [s]
440
+ for cand in candidates:
441
+ m = re.search(r"\bRUT[A-Z]?\d{2,4}\b", cand.upper())
442
+ if m:
443
+ return m.group(0).upper()
444
+ m = re.search(r"\bIX\d{2}\b", cand, flags=re.IGNORECASE)
445
+ if m:
446
+ return m.group(0).upper()
447
+ m = re.search(r"\b(R\d{3,4}|E\d{3,4}|S\d{3,4})\b", cand, flags=re.IGNORECASE)
448
+ if m:
449
+ return m.group(0).upper()
450
+ m = re.search(r"\b[A-Z]{1,6}\d{2,4}[A-Z]?\b", cand.upper())
451
+ if m:
452
+ return m.group(0).upper()
453
+ return candidates[0][:60]
454
+
455
+ def device_is_4g(row: pd.Series) -> bool:
456
+ # Detect LTE/4G even when the description uses "Cat 4 / Cat6 / Cat 12" without saying "LTE"
457
+ t = norm_text(row.get("description","")) + " " + norm_text(row.get("notes","")) + " " + norm_text(row.get("sku",""))
458
+
459
+ # If it explicitly says 5G/NR, treat as not 4G-only
460
+ if ("5g" in t) or ("nr" in t):
461
+ return False
462
+
463
+ # Classic signals
464
+ if ("lte" in t) or ("4g" in t):
465
+ return True
466
+
467
+ # LTE category signals (Cat 1..20 are LTE categories; Cat M1/M2 are LTE-M)
468
+ if re.search(r"\bcat\s*[-]?\s*(m1|m2)\b", t):
469
+ return True
470
+
471
+ m = re.search(r"\bcat\s*[-]?\s*(\d{1,2})\b", t)
472
+ if m:
473
+ try:
474
+ cat = int(m.group(1))
475
+ if 0 < cat <= 20:
476
+ return True
477
+ except Exception:
478
+ pass
479
+
480
+ # If "cat" appears at all, it's almost always LTE-family
481
+ if "cat" in t:
482
+ return True
483
+
484
+ return False
485
+
486
+ # If it explicitly says 5G/NR, treat as not 4G-only
487
+ if ("5g" in t) or ("nr" in t):
488
+ return False
489
+
490
+ # Classic signals
491
+ if ("lte" in t) or ("4g" in t):
492
+ return True
493
+
494
+ # LTE category signals (Cat 1..20 are LTE categories; Cat M1/M2 are LTE-M)
495
+ if re.search(r"\bcat\s*[-]?\s*(m1|m2)\b", t):
496
+ return True
497
+
498
+ m = re.search(r"\bcat\s*[-]?\s*(\d{1,2})\b", t)
499
+ if m:
500
+ try:
501
+ cat = int(m.group(1))
502
+ if 0 < cat <= 20:
503
+ return True
504
+ except Exception:
505
+ pass
506
+
507
+ # If "cat" appears at all, it's almost always LTE-family
508
+ if "cat" in t:
509
+ return True
510
+
511
+ return False
512
+
513
+
514
+ def candidate_5g_models_from_lifecycle(manufacturer: str) -> List[str]:
515
+ mfr = norm_text(manufacturer)
516
+ pool = df_eos[df_eos["manufacturer"].astype(str).str.lower().eq(mfr)].copy() if "manufacturer" in df_eos.columns else df_eos.copy()
517
+ vals = pool["advanced_5g_option"].tolist() if "advanced_5g_option" in pool.columns else []
518
+ out, seen = [], set()
519
+ for v in vals:
520
+ tok = extract_model_token(v)
521
+ if tok and tok.lower() != "nan" and tok not in seen:
522
+ seen.add(tok); out.append(tok)
523
+ return out
524
+
525
+ def candidate_4g_models_from_lifecycle(manufacturer: str) -> List[str]:
526
+ mfr = norm_text(manufacturer)
527
+ pool = df_eos[df_eos["manufacturer"].astype(str).str.lower().eq(mfr)].copy() if "manufacturer" in df_eos.columns else df_eos.copy()
528
+ vals = pool["suggested_replacement"].tolist() if "suggested_replacement" in pool.columns else []
529
+ out, seen = [], set()
530
+ for v in vals:
531
+ tok = extract_model_token(v)
532
+ if tok and tok.lower() != "nan" and tok not in seen:
533
+ seen.add(tok); out.append(tok)
534
+ return out
535
+
536
+ def gpt_pick_from_candidates(old_row: pd.Series, candidates: List[str], need: str) -> str:
537
+ if client is None or not candidates:
538
+ return ""
539
+ sys = "Pick the best replacement model. Choose only from candidates. Return strict JSON only."
540
+ payload = {
541
+ "old_device": {
542
+ "sku": str(old_row.get("sku","")),
543
+ "manufacturer": str(old_row.get("manufacturer","")),
544
+ "description": str(old_row.get("description","")),
545
+ "need": need,
546
+ },
547
+ "candidates": candidates[:40],
548
+ "output_schema": {"choice":"string"}
549
+ }
550
+ out = gpt_json(sys, payload, max_tokens=240) or {}
551
+ choice = str(out.get("choice","") or "").strip()
552
+ return choice if choice in candidates else ""
553
+
554
+ def fallback_5g_from_dec(canon_make: str) -> str:
555
+ pool5 = df_dec[(df_dec["_canon_make"] == canon_make) & (df_dec["_is5g"] == True)]
556
+ return str(pool5.iloc[0]["Model"]).strip() if not pool5.empty else ""
557
+
558
+ def pick_replacements_lifecycle(row: pd.Series, status: str, use_gpt: bool = True) -> Dict[str, Any]:
559
+ canon = str(row.get("_canon_make","UNKNOWN"))
560
+ manufacturer = str(row.get("manufacturer","") or "")
561
+
562
+ sug_raw = safe_str(row.get("suggested_replacement",""))
563
+ adv_raw = safe_str(row.get("advanced_5g_option",""))
564
+
565
+ has_4g_alt = bool(sug_raw.strip())
566
+ has_5g_alt = bool(adv_raw.strip())
567
+
568
+ # Treat as 4G if the description indicates LTE OR lifecycle provides a 4G suggested replacement
569
+ is_4g = device_is_4g(row) or has_4g_alt
570
+
571
+ # Provide 5G option if the unit is 4G, EOS/EOL, or lifecycle explicitly provides advanced_5g_option
572
+ want_5g = is_4g or (status in {"End of Sale","End of Life"}) or has_5g_alt
573
+
574
+ # 4G alternative: show whenever lifecycle provides it (or device appears 4G)
575
+ repl_4g = "Not applicable"
576
+ if is_4g or has_4g_alt:
577
+ repl_4g = extract_model_token(sug_raw)
578
+ if not repl_4g:
579
+ cand4 = candidate_4g_models_from_lifecycle(manufacturer)
580
+ repl_4g = (gpt_pick_from_candidates(row, cand4, "4G alternative") if (use_gpt and client) else "") or (cand4[0] if cand4 else "")
581
+ if not repl_4g:
582
+ repl_4g = "Not applicable"
583
+
584
+ # 5G replacement: prefer lifecycle advanced_5g_option whenever present
585
+ repl_5g = "Not listed"
586
+ if want_5g:
587
+ repl_5g = extract_model_token(adv_raw)
588
+ if not repl_5g:
589
+ cand5 = candidate_5g_models_from_lifecycle(manufacturer)
590
+ repl_5g = (gpt_pick_from_candidates(row, cand5, "5G replacement/upgrade") if (use_gpt and client) else "") or (cand5[0] if cand5 else "")
591
+ if not repl_5g:
592
+ repl_5g = fallback_5g_from_dec(canon) or "Not listed"
593
+
594
+ if repl_5g.lower() == "nan":
595
+ repl_5g = "Not listed"
596
+
597
+ return {"repl_4g": repl_4g, "repl_5g": repl_5g, "sources": ["lifecycle_csv"] + (["gpt"] if (use_gpt and client) else [])}
598
+
599
+
600
+ # ============================
601
+ # Antennas (Parsec-only)
602
+ # ============================
603
+ PARSEC_FAMILY_WORDS = {"chinook","labrador","boxer","bloodhound","husky","beagle","mastiff","collie","shepherd","belgian","australian","terrier","pyrenees"}
604
+ BAD_NAME_MARKERS = {"customization","standard connectors","connectors","features","benefits","specifications","mechanical","electrical","mounting","accessories","description:","standard sku"}
605
+
606
+ def clean_line(s: str) -> str:
607
+ s = re.sub(r"\s+", " ", str(s or "").strip())
608
+ if re.fullmatch(r"-[a-z0-9]+", s.lower()):
609
+ return ""
610
+ return s
611
+
612
+ def is_bad_name_line(line: str) -> bool:
613
+ low = line.lower()
614
+ if any(m in low for m in BAD_NAME_MARKERS):
615
+ return True
616
+ if re.search(r"\b-[a-z0-9]{1,4}\b", low) and len(low) <= 25:
617
+ return True
618
+ return False
619
+
620
+ def family_from_line(line: str) -> str:
621
+ low = line.lower()
622
+ for fam in PARSEC_FAMILY_WORDS:
623
+ if fam in low:
624
+ return fam.capitalize()
625
+ return ""
626
+
627
+ def parsec_connectors_from_card(t: str) -> str:
628
+ m = re.search(r"Standard\s+Connectors:\s*(.+)", t, flags=re.IGNORECASE)
629
+ if m:
630
+ return re.sub(r"\s+", " ", m.group(1).strip())[:80]
631
+ return ""
632
+
633
+ def parsec_mounts_from_card(t: str) -> List[str]:
634
+ mounts = []
635
+ for m in re.finditer(r"Mount:\s*(.+)", t, flags=re.IGNORECASE):
636
+ val = re.sub(r"\s+", " ", m.group(1).strip())
637
+ parts = [p.strip().lower() for p in val.split(",") if p.strip()]
638
+ mounts.extend(parts)
639
+ out = []
640
+ seen = set()
641
+ for x in mounts:
642
+ if x not in seen:
643
+ seen.add(x); out.append(x)
644
+ return out
645
+
646
+ def parsec_name_from_card(card_text: str) -> str:
647
+ lines = [clean_line(ln) for ln in str(card_text or "").splitlines()]
648
+ lines = [ln for ln in lines if ln]
649
+
650
+ for ln in lines:
651
+ if is_bad_name_line(ln):
652
+ continue
653
+ fam = family_from_line(ln)
654
+ if fam:
655
+ return fam
656
+
657
+ sku_i = None
658
+ for i, ln in enumerate(lines):
659
+ if "standard sku" in ln.lower():
660
+ sku_i = i
661
+ break
662
+ if sku_i is not None:
663
+ window = lines[max(0, sku_i - 12):sku_i]
664
+ for ln in reversed(window):
665
+ if is_bad_name_line(ln):
666
+ continue
667
+ if 3 <= len(ln) <= 40 and re.search(r"[A-Za-z]", ln):
668
+ return ln.split()[0].capitalize()
669
+
670
+ return "Parsec antenna"
671
+
672
+ def parsec_part_from_card(t: str) -> str:
673
+ m = re.search(r"Standard\s+SKU:\s*([A-Z0-9]+)", t)
674
+ return m.group(1).strip() if m else ""
675
+
676
+ def parsec_desc_from_card(t: str) -> str:
677
+ m = re.search(r"Description:\s*(.+?)(?:\n|$)", t, flags=re.IGNORECASE)
678
+ return re.sub(r"\s+"," ",m.group(1).strip())[:220] if m else ""
679
+
680
+ def parsec_retrieve(query: str, top_k: int = 12) -> List[Dict[str, Any]]:
681
+ qv = embedder.encode([query], normalize_embeddings=True)
682
+ qv = np.asarray(qv, dtype=np.float32)
683
+ scores, ids = parsec_index.search(qv, top_k)
684
+ out: List[Dict[str, Any]] = []
685
+ for sc, i in zip(scores[0].tolist(), ids[0].tolist()):
686
+ if 0 <= int(i) < len(parsec_cards):
687
+ card = parsec_cards[int(i)]
688
+ out.append({
689
+ "score": float(sc),
690
+ "name": parsec_name_from_card(card),
691
+ "part_number": parsec_part_from_card(card),
692
+ "description": parsec_desc_from_card(card),
693
+ "connectors": parsec_connectors_from_card(card),
694
+ "mounts": parsec_mounts_from_card(card),
695
+ "_card": card.lower(),
696
+ })
697
+ return out
698
+
699
+ def choose_best_parsec(cands: List[Dict[str, Any]], mode: str) -> Dict[str, Any]:
700
+ best = None
701
+ best_score = -1e9
702
+
703
+ for c in cands:
704
+ card = c.get("_card","")
705
+ mounts = c.get("mounts", []) or []
706
+ score = float(c.get("score", 0.0))
707
+
708
+ if "omni" in card:
709
+ score += 0.6
710
+ if "directional" in card:
711
+ score -= 1.5
712
+
713
+ if mode == "vehicle":
714
+ if any("magnetic" in m for m in mounts):
715
+ score += 3.0
716
+ if any("through" in m for m in mounts):
717
+ score += 2.0
718
+ if any("wall" in m for m in mounts) or any("pole" in m for m in mounts):
719
+ score -= 1.2
720
+ if "app: fixed" in card and "mobile" not in card:
721
+ score -= 2.0
722
+
723
+ if mode == "stationary":
724
+ if any("wall" in m for m in mounts):
725
+ score += 2.0
726
+ if any("pole" in m for m in mounts):
727
+ score += 1.8
728
+
729
+ if score > best_score:
730
+ best_score = score
731
+ best = c
732
+
733
+ if not best:
734
+ return {"name":"Parsec antenna","part_number":"","description":"","connectors":"","mounts":[]}
735
+
736
+ best = dict(best)
737
+ best.pop("_card", None)
738
+ return best
739
+
740
+
741
+ def infer_mimo_for_5g(repl_5g_model: str) -> str:
742
+ """Rule: every 5G router uses a 4x4 antenna."""
743
+ return "4x4"
744
+
745
+ # If the model name hints 5G, lean 4x4
746
+ if "5g" in model.lower() or model.upper().startswith(("R", "E", "S", "IX", "RUTM")):
747
+ default = "4x4"
748
+ else:
749
+ default = "2x2"
750
+
751
+ # Use dec2025routers.csv if we can match the model under the same maker family
752
+ try:
753
+ pool = df_dec[df_dec["_canon_make"] == canon_make].copy()
754
+ if pool.empty:
755
+ return default
756
+ hit = process.extractOne(norm_text(model), pool["_norm_model"].tolist(), scorer=fuzz.WRatio)
757
+ if not hit or hit[1] < MATCH_OK:
758
+ return default
759
+ row = pool.iloc[int(hit[2])]
760
+ txt2 = (str(row.get("Antennas (internal/external/both)", "")) + " " + str(row.get("Modem Type", "")) + " " + str(row.get("Special notes",""))).lower()
761
+ if "4x4" in txt2 or "4 x 4" in txt2 or "4x 4" in txt2:
762
+ return "4x4"
763
+ if "2x2" in txt2 or "2 x 2" in txt2:
764
+ return "2x2"
765
+ # If modem type includes 5G, lean 4x4
766
+ if "5g" in txt2 or "nr" in txt2:
767
+ return "4x4"
768
+ return default
769
+ except Exception:
770
+ return default
771
+
772
+ def antenna_options_for(router_model: str, tech: str, mimo: str) -> Dict[str, Any]:
773
+ q_stationary = f"{router_model} {tech} {mimo} omni stationary pole wall fixed site Parsec"
774
+ q_vehicle = f"{router_model} {tech} {mimo} omni vehicle mobile magnetic through-bolt Parsec"
775
+
776
+ cand_stationary = parsec_retrieve(q_stationary, top_k=12)
777
+ cand_vehicle = parsec_retrieve(q_vehicle, top_k=12)
778
+
779
+ s = choose_best_parsec(cand_stationary, mode="stationary")
780
+ v = choose_best_parsec(cand_vehicle, mode="vehicle")
781
+
782
+ s.update({"mimo": mimo, "why": "Stationary omni best match."})
783
+ v.update({"mimo": mimo, "why": "Vehicle omni best match."})
784
+
785
+ return {"stationary_omni": s, "vehicle_omni": v, "sources":["parsec_rag"]}
786
+
787
+
788
+ # ============================
789
+ # Install-ready checklist
790
+ # ============================
791
+ def install_ready_checklist(current_sku: str, repl: Dict[str,Any], ant: Dict[str,Any]) -> str:
792
+ st = ant.get("stationary_omni", {})
793
+ vh = ant.get("vehicle_omni", {})
794
+ if client is not None:
795
+ sys = "Create a short, install-ready checklist for a Verizon rep. Return markdown only."
796
+ payload = {"current_device": current_sku, "replacements": repl, "antennas": {"stationary": st, "vehicle": vh}}
797
+ resp = client.responses.create(
798
+ model=OPENAI_MODEL,
799
+ reasoning=OPENAI_REASONING,
800
+ input=[{"role":"system","content":sys},{"role":"user","content":json.dumps(payload)}],
801
+ max_output_tokens=520,
802
+ )
803
+ return (getattr(resp, "output_text", "") or "").strip()
804
+ return "\n".join([
805
+ "### Install-ready checklist",
806
+ f"- Current device: {current_sku}",
807
+ f"- 5G replacement: {repl.get('repl_5g','')}",
808
+ f"- 4G alternative: {repl.get('repl_4g','Not applicable')}",
809
+ f"- Stationary omni antenna: {st.get('name','')} (PN {st.get('part_number','')})",
810
+ f"- Vehicle omni antenna: {vh.get('name','')} (PN {vh.get('part_number','')})",
811
+ "- Next steps: confirm mounting + cable lengths + power; place order; schedule install.",
812
+ ])
813
+
814
+
815
+ # ============================
816
+ # Batch mode (NO GPT)
817
+ # ============================
818
+ def parse_batch_inputs(text_blob: str, file_obj: Any) -> List[str]:
819
+ items: List[str] = []
820
+ if file_obj is not None:
821
+ try:
822
+ path = file_obj.name if hasattr(file_obj, "name") else str(file_obj)
823
+ df = pd.read_csv(path)
824
+ col = df.columns[0]
825
+ items.extend([str(x).strip() for x in df[col].tolist() if str(x).strip()])
826
+ except Exception:
827
+ pass
828
+ if text_blob:
829
+ for ln in str(text_blob).splitlines():
830
+ ln = ln.strip()
831
+ if ln:
832
+ items.append(ln)
833
+ seen=set()
834
+ out=[]
835
+ for x in items:
836
+ k=norm_text(x)
837
+ if k and k not in seen:
838
+ seen.add(k); out.append(x)
839
+ return out
840
+
841
+ def run_batch(text_blob: str, file_obj: Any, include_antennas: bool):
842
+ inputs = parse_batch_inputs(text_blob, file_obj)
843
+ if not inputs:
844
+ return "", None, None, ""
845
+
846
+ rows=[]
847
+ for item in inputs:
848
+ res = resolve_device(item)
849
+ if res.get("mode") != "ok":
850
+ rows.append({"Input": item, "Matched":"", "Status":"Needs review", "EOS":"", "EOL":"", "4G alternative":"", "5G replacement":"", "Notes":"Not found/ambiguous"})
851
+ continue
852
+
853
+ life_row = df_eos.iloc[int(res["row_idx"])]
854
+ eos, eol, status = row_to_dates_and_status(life_row)
855
+ repl = pick_replacements_lifecycle(life_row, status, use_gpt=False)
856
+
857
+ rows.append({
858
+ "Input": item,
859
+ "Matched": str(life_row.get("sku","")),
860
+ "Status": status,
861
+ "EOS": eos,
862
+ "EOL": eol,
863
+ "4G alternative": repl.get("repl_4g",""),
864
+ "5G replacement": repl.get("repl_5g",""),
865
+ "Notes": "",
866
+ })
867
+
868
+ out_df = pd.DataFrame(rows)
869
+ counts = out_df["Status"].value_counts(dropna=False).to_dict()
870
+ top_5g = out_df["5G replacement"].value_counts(dropna=False).head(5).to_dict()
871
+ summary = f"Rows: {len(out_df)} | " + " | ".join([f"{k}: {v}" for k,v in counts.items()])
872
+ rollup = "Top 5G recommendations:\n" + "\n".join([f"- {k}: {v}" for k,v in top_5g.items() if str(k).strip()])
873
+
874
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
875
+ out_df.to_csv(tmp.name, index=False)
876
+
877
+ return summary, out_df, tmp.name, rollup
878
+
879
+
880
+ # ============================
881
+ # Replacement feature table + manufacturer link (5G device)
882
+ # ============================
883
+
884
+ FEATURE_COLS = ["Device", "Modem technology", "WiFi", "Ports", "Antennas", "Ruggedness", "Use case"]
885
+
886
+ # Manufacturer domains used for best-effort link resolution (no non-maker domains).
887
+ MAKER_DOMAINS = {
888
+ "CRADLEPOINT": ["cradlepoint.com", "ericsson.com"],
889
+ "SIERRA": ["semtech.com", "airlink.com"],
890
+ "FEENEY": ["inseego.com"],
891
+ "DIGI": ["digi.com"],
892
+ "CISCO_MERAKI": ["meraki.cisco.com", "cisco.com"],
893
+ "CISCO": ["cisco.com"],
894
+ "TELTONIKA": ["teltonika-networks.com"],
895
+ "UNKNOWN": [],
896
+ }
897
+
898
+ HTTP_HEADERS = {
899
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
900
+ "(KHTML, like Gecko) Chrome/120.0 Safari/537.36"
901
+ }
902
+ HTTP_TIMEOUT = 12
903
+
904
+ def _best_effort_manufacturer_url(model: str, canon_make: str) -> str:
905
+ """Try to find a manufacturer page or datasheet link using simple on-domain searches.
906
+ If we can't confirm a page, return the manufacturer homepage for the maker family.
907
+ """
908
+ model = str(model or "").strip()
909
+ if not model or model in {"Not listed", "Not applicable"}:
910
+ return ""
911
+
912
+ domains = MAKER_DOMAINS.get(canon_make, []) or []
913
+ if not domains:
914
+ return ""
915
+
916
+ # Candidate on-domain search URLs (common patterns across sites).
917
+ # We keep these on the manufacturer domain (no Google/Bing).
918
+ q = re.sub(r"\s+", "+", model)
919
+ url_candidates = []
920
+ for d in domains:
921
+ url_candidates += [
922
+ f"https://{d}/search?q={q}",
923
+ f"https://{d}/search?query={q}",
924
+ f"https://{d}/?s={q}",
925
+ f"https://www.{d}/search?q={q}",
926
+ f"https://www.{d}/search?query={q}",
927
+ f"https://www.{d}/?s={q}",
928
+ ]
929
+
930
+ # Also try a few direct product patterns for known makers (best effort).
931
+ if canon_make == "TELTONIKA":
932
+ slug = model.lower()
933
+ url_candidates += [
934
+ f"https://teltonika-networks.com/products/routers/{slug}",
935
+ f"https://teltonika-networks.com/product/{slug}",
936
+ "https://teltonika-networks.com/products/routers/",
937
+ ]
938
+ if canon_make == "DIGI":
939
+ url_candidates += [
940
+ "https://www.digi.com/products/networking/cellular-routers",
941
+ f"https://www.digi.com/search?q={q}",
942
+ ]
943
+ if canon_make == "CRADLEPOINT":
944
+ url_candidates += [
945
+ "https://cradlepoint.com/products/",
946
+ f"https://cradlepoint.com/?s={q}",
947
+ ]
948
+ if canon_make in {"CISCO", "CISCO_MERAKI"}:
949
+ url_candidates += [
950
+ f"https://www.cisco.com/c/en/us/search.html?q={q}",
951
+ ]
952
+
953
+ # Try to confirm a working page (HTTP 200 and model string somewhere in HTML).
954
+ for u in url_candidates[:18]:
955
+ try:
956
+ import requests
957
+ r = requests.get(u, headers=HTTP_HEADERS, timeout=HTTP_TIMEOUT, allow_redirects=True)
958
+ if r.status_code != 200:
959
+ continue
960
+ html = (r.text or "").lower()
961
+ if model.lower() in html or "datasheet" in html or "data sheet" in html:
962
+ return r.url
963
+ except Exception:
964
+ continue
965
+
966
+ # Fallback: maker homepage
967
+ d0 = domains[0]
968
+ return f"https://{d0}"
969
+
970
+ def _features_from_dec(model: str, canon_make: str) -> Dict[str, str]:
971
+ """Lookup a router model in dec2025routers.csv and return the key feature fields."""
972
+ if not model or model in {"Not listed", "Not applicable"}:
973
+ return {k: "Not listed" for k in FEATURE_COLS[1:]}
974
+
975
+ pool = df_dec[df_dec["_canon_make"] == canon_make].copy()
976
+ if pool.empty:
977
+ return {k: "Not listed" for k in FEATURE_COLS[1:]}
978
+
979
+ hit = process.extractOne(norm_text(model), pool["_norm_model"].tolist(), scorer=fuzz.WRatio)
980
+ if not hit or hit[1] < MATCH_OK:
981
+ return {k: "Not listed" for k in FEATURE_COLS[1:]}
982
+
983
+ r = pool.iloc[int(hit[2])]
984
+ ports = f"WAN: {r.get('WAN ports and speed','')} | LAN: {r.get('LAN ports and speed','')}"
985
+ return {
986
+ "Modem technology": str(r.get("Modem Type","")) or "Not listed",
987
+ "WiFi": str(r.get("WiFi type","")) or "Not listed",
988
+ "Ports": ports.strip() if ports.strip() else "Not listed",
989
+ "Antennas": str(r.get("Antennas (internal/external/both)","")) or "Not listed",
990
+ "Ruggedness": str(r.get("Ruggedization","")) or "Not listed",
991
+ "Use case": str(r.get("Primary use case","")) or "Not listed",
992
+ }
993
+
994
+ def _gpt_fill_feature_row(device_label: str, model: str, canon_make: str, row: Dict[str, str]) -> Dict[str, str]:
995
+ """If dec can't supply values, ask GPT to fill missing ones (best guess)."""
996
+ if client is None:
997
+ return row
998
+
999
+ missing = [k for k,v in row.items() if (not v) or str(v).strip().lower() in {"not listed","nan",""}]
1000
+ if not missing:
1001
+ return row
1002
+
1003
+ sys = "Fill missing router feature fields for a Verizon rep. Return strict JSON only."
1004
+ payload = {
1005
+ "device_label": device_label,
1006
+ "model": model,
1007
+ "maker_family": canon_make,
1008
+ "known": row,
1009
+ "fill_only": missing,
1010
+ "rules": [
1011
+ "Fill only the requested fields.",
1012
+ "Best guess if needed. Short phrases only.",
1013
+ "Return JSON only."
1014
+ ],
1015
+ "output_schema": {k: "string" for k in missing}
1016
+ }
1017
+ out = gpt_json(sys, payload, max_tokens=260) or {}
1018
+ for k in missing:
1019
+ val = str(out.get(k, "") or "").strip()
1020
+ if val:
1021
+ row[k] = val
1022
+ return row
1023
+
1024
+ def build_replacement_features_table(repl_4g: str, repl_5g: str, canon_make: str) -> pd.DataFrame:
1025
+ rows = []
1026
+
1027
+ # 4G
1028
+ row4 = _features_from_dec(repl_4g, canon_make)
1029
+ row4 = _gpt_fill_feature_row("4G alternative", repl_4g, canon_make, row4)
1030
+ rows.append({"Device": "4G alternative", **row4})
1031
+
1032
+ # 5G
1033
+ row5 = _features_from_dec(repl_5g, canon_make)
1034
+ row5 = _gpt_fill_feature_row("5G replacement", repl_5g, canon_make, row5)
1035
+ rows.append({"Device": "5G replacement", **row5})
1036
+
1037
+ df = pd.DataFrame(rows, columns=FEATURE_COLS)
1038
+ return df
1039
+
1040
+
1041
+ # ============================
1042
+ # Verizon fit badges (small table) for recommended devices
1043
+ # ============================
1044
+
1045
+ FIT_COLS = ["Device", "Fit badges", "Ethernet ports", "Battery"]
1046
+
1047
+ def _parse_ethernet_ports(wan_field: str, lan_field: str) -> str:
1048
+ """Best-effort total ethernet ports based on WAN/LAN text."""
1049
+ def _count(field: str) -> int:
1050
+ s = str(field or "")
1051
+ # Common forms: "1x GbE", "2 x 10/100", "WAN: 1", etc.
1052
+ nums = [int(x) for x in re.findall(r"(\\d+)\\s*x", s.lower())]
1053
+ if nums:
1054
+ return sum(nums)
1055
+ # Fallback: if it contains 'port' with a number
1056
+ m = re.search(r"(\\d+)\\s*port", s.lower())
1057
+ if m:
1058
+ return int(m.group(1))
1059
+ # If it contains '1' and 'wan' in short text, guess 1
1060
+ if "wan" in s.lower() and re.search(r"\\b1\\b", s):
1061
+ return 1
1062
+ return 0
1063
+
1064
+ total = _count(wan_field) + _count(lan_field)
1065
+ return str(total) if total > 0 else "Not listed"
1066
+
1067
+ def _battery_badge(battery_field: str) -> str:
1068
+ s = str(battery_field or "").strip().lower()
1069
+ if not s or s in {"none", "no", "n/a", "not listed"}:
1070
+ return "No"
1071
+ return "Yes"
1072
+
1073
+ def _bool_badge(flag: bool) -> str:
1074
+ return "Yes" if flag else "No"
1075
+
1076
+ def _dual_sim_from_row_text(*fields: str) -> bool:
1077
+ txt = " ".join([str(x or "") for x in fields]).lower()
1078
+ return ("dual sim" in txt) or ("2 sim" in txt) or ("two sim" in txt) or ("dual-sim" in txt)
1079
+
1080
+ def _throughput_high(throughput_field: str) -> bool:
1081
+ t = str(throughput_field or "").lower()
1082
+ # Heuristic: anything mentioning gbps or >=1000 mbps
1083
+ if "gbps" in t:
1084
+ return True
1085
+ m = re.search(r"(\\d+(?:\\.\\d+)?)\\s*mbps", t)
1086
+ if m:
1087
+ try:
1088
+ return float(m.group(1)) >= 1000.0
1089
+ except Exception:
1090
+ pass
1091
+ return False
1092
+
1093
+ def _gpt_fit_badges(model: str, canon_make: str, is_5g: bool, dec_row: Optional[pd.Series]) -> Tuple[str, str, str]:
1094
+ """
1095
+ GPT-based fill for Fit badges / Ethernet ports / Battery, used when dec is missing or incomplete.
1096
+ Returns (badges_csv, ethernet_ports, battery_yesno).
1097
+ """
1098
+ if client is None:
1099
+ return ("Not listed", "Not listed", "Not listed")
1100
+
1101
+ dec_ctx = {}
1102
+ if dec_row is not None:
1103
+ try:
1104
+ dec_ctx = {
1105
+ "Model": str(dec_row.get("Model","")),
1106
+ "Modem Type": str(dec_row.get("Modem Type","")),
1107
+ "Ruggedization": str(dec_row.get("Ruggedization","")),
1108
+ "WAN ports and speed": str(dec_row.get("WAN ports and speed","")),
1109
+ "LAN ports and speed": str(dec_row.get("LAN ports and speed","")),
1110
+ "Antennas": str(dec_row.get("Antennas (internal/external/both)","")),
1111
+ "WiFi type": str(dec_row.get("WiFi type","")),
1112
+ "Primary use case": str(dec_row.get("Primary use case","")),
1113
+ "Serial port": str(dec_row.get("Serial port (yes/no)","")),
1114
+ "VPN": str(dec_row.get("VPN capabilities","")),
1115
+ "Throughput": str(dec_row.get("Router throughput","")),
1116
+ "Battery": str(dec_row.get("Battery (internal/removable/none/optional)","")),
1117
+ "Special notes": str(dec_row.get("Special notes","")),
1118
+ "Summary": str(dec_row.get("summary and use case","")),
1119
+ }
1120
+ except Exception:
1121
+ dec_ctx = {}
1122
+
1123
+ sys = (
1124
+ "You are helping a Verizon rep. Based on the provided router context, output fit badges and a couple quick traits.\n"
1125
+ "Return STRICT JSON only.\n"
1126
+ "Badges must be chosen from this set only:\n"
1127
+ "['Vehicle','Fixed site','Wi‑Fi','Rugged','Dual‑SIM','4x4 MIMO','High throughput','Serial'].\n"
1128
+ "Rules:\n"
1129
+ "- If is_5g is true, ALWAYS include '4x4 MIMO'.\n"
1130
+ "- Ethernet ports: return a single integer as a string if you can infer total ethernet ports, otherwise 'Not listed'.\n"
1131
+ "- Battery: return 'Yes' or 'No' if you can infer, otherwise 'Not listed'.\n"
1132
+ "- If uncertain between Vehicle vs Fixed site, pick the most likely based on use case/ruggedization.\n"
1133
+ )
1134
+
1135
+ payload = {
1136
+ "model": model,
1137
+ "maker_family": canon_make,
1138
+ "is_5g": bool(is_5g),
1139
+ "dec_context": dec_ctx,
1140
+ "output_schema": {
1141
+ "badges": ["string"],
1142
+ "ethernet_ports": "string",
1143
+ "battery": "Yes|No|Not listed"
1144
+ }
1145
+ }
1146
+
1147
+ out = gpt_json(sys, payload, max_tokens=260) or {}
1148
+
1149
+ badges = out.get("badges", []) or []
1150
+ allowed = {"Vehicle","Fixed site","Wi‑Fi","Rugged","Dual‑SIM","4x4 MIMO","High throughput","Serial"}
1151
+ clean = []
1152
+ for b in badges:
1153
+ bs = str(b).strip()
1154
+ if bs in allowed:
1155
+ clean.append(bs)
1156
+
1157
+ if is_5g and "4x4 MIMO" not in clean:
1158
+ clean.append("4x4 MIMO")
1159
+
1160
+ eth = str(out.get("ethernet_ports","") or "").strip()
1161
+ if not eth or eth.lower() in {"nan","none"}:
1162
+ eth = "Not listed"
1163
+ m = re.search(r"\d+", eth)
1164
+ eth = m.group(0) if m else ("Not listed" if eth == "Not listed" else eth)
1165
+
1166
+ bat = str(out.get("battery","") or "").strip()
1167
+ if not bat:
1168
+ bat = "Not listed"
1169
+ if bat.lower().startswith("y"):
1170
+ bat = "Yes"
1171
+ elif bat.lower().startswith("n"):
1172
+ bat = "No"
1173
+ elif bat not in {"Yes","No","Not listed"}:
1174
+ bat = "Not listed"
1175
+
1176
+ dedup=[]
1177
+ seen=set()
1178
+ for b in clean:
1179
+ if b not in seen:
1180
+ seen.add(b); dedup.append(b)
1181
+ badges_csv = ", ".join(dedup) if dedup else "Not listed"
1182
+ return (badges_csv, eth, bat)
1183
+
1184
+
1185
+ def _fit_badges_for_model(model: str, canon_make: str, is_5g: bool) -> Tuple[str, str, str]:
1186
+ """Return (badges_csv, ethernet_ports, battery_yesno). Uses dec2025routers.csv first, then GPT fill."""
1187
+ model = str(model or "").strip()
1188
+ if not model or model in {"Not listed", "Not applicable"}:
1189
+ return ("Not listed", "Not listed", "Not listed")
1190
+
1191
+ pool = df_dec[df_dec["_canon_make"] == canon_make].copy()
1192
+ row = None
1193
+ if not pool.empty:
1194
+ hit = process.extractOne(norm_text(model), pool["_norm_model"].tolist(), scorer=fuzz.WRatio)
1195
+ if hit and hit[1] >= MATCH_OK:
1196
+ row = pool.iloc[int(hit[2])]
1197
+
1198
+ badges = []
1199
+ eth = "Not listed"
1200
+ bat_yes = "Not listed"
1201
+
1202
+ if row is not None:
1203
+ use_case = str(row.get("Primary use case","") or "").lower()
1204
+ rugged = str(row.get("Ruggedization","") or "").lower()
1205
+
1206
+ if any(k in use_case for k in ["vehicle","mobile","fleet","in-vehicle"]) or "vehicle" in rugged:
1207
+ badges.append("Vehicle")
1208
+ else:
1209
+ badges.append("Fixed site")
1210
+
1211
+ wifi = str(row.get("WiFi type","") or "").strip()
1212
+ if wifi and wifi.lower() not in {"none","no","n/a"}:
1213
+ badges.append("Wi‑Fi")
1214
+
1215
+ if any(k in rugged for k in ["rugged","industrial","ip","harsh"]):
1216
+ badges.append("Rugged")
1217
+
1218
+ notes_blob = " ".join([
1219
+ str(row.get("Special notes","") or ""),
1220
+ str(row.get("summary and use case","") or ""),
1221
+ ]).lower()
1222
+ if "dual" in notes_blob and "sim" in notes_blob:
1223
+ badges.append("Dual‑SIM")
1224
+
1225
+ if is_5g:
1226
+ badges.append("4x4 MIMO")
1227
+
1228
+ thr = str(row.get("Router throughput","") or "").lower()
1229
+ m = re.search(r"(\d+(\.\d+)?)\s*gb", thr)
1230
+ if m:
1231
+ try:
1232
+ if float(m.group(1)) >= 1.0:
1233
+ badges.append("High throughput")
1234
+ except Exception:
1235
+ pass
1236
+
1237
+ serial = str(row.get("Serial port (yes/no)","") or "").strip().lower()
1238
+ if serial in {"yes","y","true"}:
1239
+ badges.append("Serial")
1240
+
1241
+ wan = str(row.get("WAN ports and speed","") or "")
1242
+ lan = str(row.get("LAN ports and speed","") or "")
1243
+ m1 = re.search(r"(\d+)\s*x", wan.lower())
1244
+ m2 = re.search(r"(\d+)\s*x", lan.lower())
1245
+ if m1 or m2:
1246
+ total = (int(m1.group(1)) if m1 else 0) + (int(m2.group(1)) if m2 else 0)
1247
+ eth = str(total) if total > 0 else "Not listed"
1248
+
1249
+ bat = str(row.get("Battery (internal/removable/none/optional)","") or "")
1250
+ bat_l = bat.lower().strip()
1251
+ if bat_l:
1252
+ if "none" in bat_l:
1253
+ bat_yes = "No"
1254
+ else:
1255
+ bat_yes = "Yes"
1256
+
1257
+ # Use GPT when anything is missing (instead of best-effort inference)
1258
+ if (row is None) or (eth == "Not listed") or (bat_yes == "Not listed") or (not badges):
1259
+ g_badges, g_eth, g_bat = _gpt_fit_badges(model, canon_make, is_5g, row)
1260
+
1261
+ if badges:
1262
+ if is_5g and "4x4 MIMO" not in badges:
1263
+ badges.append("4x4 MIMO")
1264
+ dedup=[]
1265
+ seen=set()
1266
+ for b in badges:
1267
+ if b not in seen:
1268
+ seen.add(b); dedup.append(b)
1269
+ badges_csv = ", ".join(dedup)
1270
+ else:
1271
+ badges_csv = g_badges
1272
+
1273
+ eth = eth if eth != "Not listed" else g_eth
1274
+ bat_yes = bat_yes if bat_yes != "Not listed" else g_bat
1275
+ return (badges_csv or "Not listed", eth or "Not listed", bat_yes or "Not listed")
1276
+
1277
+ dedup=[]
1278
+ seen=set()
1279
+ for b in badges:
1280
+ if b not in seen:
1281
+ seen.add(b); dedup.append(b)
1282
+ badges_csv = ", ".join(dedup) if dedup else "Not listed"
1283
+ return (badges_csv, eth, bat_yes)
1284
+
1285
+ def build_fit_table(repl_4g: str, repl_5g: str, canon_make: str) -> pd.DataFrame:
1286
+ rows = []
1287
+ # 4G alt row (is_5g False)
1288
+ b4, eth4, bat4 = _fit_badges_for_model(repl_4g, canon_make, is_5g=False)
1289
+ rows.append({"Device": "4G alternative", "Fit badges": b4, "Ethernet ports": eth4, "Battery": bat4})
1290
+ # 5G row (is_5g True)
1291
+ b5, eth5, bat5 = _fit_badges_for_model(repl_5g, canon_make, is_5g=True)
1292
+ rows.append({"Device": "5G replacement", "Fit badges": b5, "Ethernet ports": eth5, "Battery": bat5})
1293
+ return pd.DataFrame(rows, columns=FIT_COLS)
1294
+
1295
+ # ============================
1296
+ # Output
1297
+ # ============================
1298
+ def assemble_output(life_row: pd.Series, status: str, eos: str, eol: str, repl: Dict[str,Any], ant: Dict[str,Any]) -> str:
1299
+ current_name = f"{life_row.get('sku','')} — {life_row.get('description','')}".strip(" —")
1300
+ st = ant.get("stationary_omni", {})
1301
+ vh = ant.get("vehicle_omni", {})
1302
+
1303
+ lines = []
1304
+ lines.append(f"1. Current device: **{current_name}**")
1305
+ lines.append(f"2. Status: **{status}**")
1306
+ lines.append(f"3. End of Sale date: **{eos}**")
1307
+ lines.append(f"4. End of Life date: **{eol}**")
1308
+ lines.append(f"5. 4G alternative (lifecycle): **{repl.get('repl_4g','Not applicable')}**")
1309
+ lines.append(f"6. 5G replacement (lifecycle): **{repl.get('repl_5g','Not listed')}**")
1310
+ lines.append("7. Antenna options (Parsec-only):")
1311
+ conn_s = f" | Conn: {st.get('connectors','')}" if st.get("connectors") else ""
1312
+ conn_v = f" | Conn: {vh.get('connectors','')}" if vh.get("connectors") else ""
1313
+ lines.append(f" - Stationary (Omni): **{st.get('name','')}** (Part #: {st.get('part_number','')}) — {st.get('description','')} — MIMO: {st.get('mimo','')}{conn_s}")
1314
+ lines.append(f" - Vehicle (Omni): **{vh.get('name','')}** (Part #: {vh.get('part_number','')}) — {vh.get('description','')} — MIMO: {vh.get('mimo','')}{conn_v}")
1315
+
1316
+ lines.append("\nSources (debug):")
1317
+ for s in repl.get("sources", []) if isinstance(repl.get("sources"), list) else []:
1318
+ lines.append(f"- {s}")
1319
+ lines.append("- ParsecCatalog.pdf (local RAG)")
1320
+ lines.append("- routers_eos_eol_by_sku.csv (replacements)")
1321
+ return "\n".join(lines)
1322
+
1323
+
1324
+ # ============================
1325
+ # Customer-ready email summary (single lookup only)
1326
+ # ============================
1327
+
1328
+ def build_customer_email(life_row: pd.Series, status: str, eos: str, eol: str, repl: Dict[str,Any], ant: Dict[str,Any], link5: str) -> str:
1329
+ """Email-style summary the rep can paste to a customer (lightly sales-y)."""
1330
+ current = f"{life_row.get('sku','')} — {life_row.get('description','')}".strip(" —")
1331
+ repl5 = str(repl.get("repl_5g","") or "").strip()
1332
+ repl4 = str(repl.get("repl_4g","") or "").strip()
1333
+
1334
+ st = ant.get("stationary_omni", {}) or {}
1335
+ vh = ant.get("vehicle_omni", {}) or {}
1336
+
1337
+ lines = []
1338
+ lines.append("Subject: Router replacement recommendation")
1339
+ lines.append("")
1340
+ lines.append("Hi there,")
1341
+ lines.append("")
1342
+ lines.append(f"We reviewed your current router (**{current}**) and recommend the following path forward:")
1343
+ lines.append("")
1344
+ lines.append(f"- **Status:** {status}")
1345
+ lines.append(f"- **End of Sale:** {eos}")
1346
+ lines.append(f"- **End of Life:** {eol}")
1347
+ lines.append("")
1348
+ lines.append("**Recommended replacement (5G):**")
1349
+ lines.append(f"- {repl5 if repl5 else 'Not listed'}")
1350
+ if link5:
1351
+ lines.append(f"- Manufacturer page (best effort): {link5}")
1352
+ lines.append("")
1353
+ lines.append("**Optional 4G alternative (if needed):**")
1354
+ lines.append(f"- {repl4 if repl4 and repl4.lower() != 'not applicable' else 'Not applicable'}")
1355
+ lines.append("")
1356
+ lines.append("**Antenna suggestions (Parsec):**")
1357
+ lines.append(f"- Stationary (Omni): {st.get('name','')} (PN {st.get('part_number','')})")
1358
+ lines.append(f"- Vehicle (Omni): {vh.get('name','')} (PN {vh.get('part_number','')})")
1359
+ lines.append("")
1360
+ lines.append("If you’d like, we can confirm the best-fit option for your install environment and provide pricing.")
1361
+ lines.append("")
1362
+ lines.append("Contact Peter Dunn @ 786.999.9127 or peter.dunn@masterstelecom.com for pricing.")
1363
+ lines.append("")
1364
+ lines.append("Thanks,")
1365
+ lines.append("Peter Dunn")
1366
+ return "\n".join(lines)
1367
+
1368
+ def generate_customer_email(st_json: str) -> str:
1369
+ st = state_load(st_json)
1370
+ if not st or "row_idx" not in st:
1371
+ return "Run a lookup first."
1372
+ try:
1373
+ life_row = df_eos.iloc[int(st["row_idx"])]
1374
+ except Exception:
1375
+ return "Run a lookup first."
1376
+
1377
+ eos, eol, status = row_to_dates_and_status(life_row)
1378
+ repl = st.get("repl", {}) or {}
1379
+ ant = st.get("ant", {}) or {}
1380
+
1381
+ canon_make = str(life_row.get("_canon_make","UNKNOWN"))
1382
+ url5 = _best_effort_manufacturer_url(str(repl.get("repl_5g","") or ""), canon_make)
1383
+ return build_customer_email(life_row, status, eos, eol, repl, ant, url5)
1384
+
1385
+ # ============================
1386
+ # Gradio callbacks
1387
+ # IMPORTANT: no dict state and ALL events have api_name=False (prevents api_info schema generation)
1388
+ # ============================
1389
+ def run_lookup(user_text: str, st_json: str):
1390
+ user_text = str(user_text or "").strip()
1391
+ if not user_text:
1392
+ return "Enter a router SKU/model.", "", None, None, "", gr.update(visible=False), gr.update(visible=False), "{}", "", ""
1393
+
1394
+ res = resolve_device(user_text)
1395
+
1396
+ if res.get("mode") == "pick":
1397
+ opts = res.get("options", [])
1398
+ choices = [o["label"] for o in opts]
1399
+ st2 = {"mode":"pick","options": opts, "raw": user_text}
1400
+ return "Did you mean A or B? Pick one, then click Use selection.", "", None, None, "", gr.update(choices=choices, value=None, visible=True), gr.update(visible=True), state_dump(st2), "", ""
1401
+
1402
+ if res.get("mode") != "ok":
1403
+ return "Not found.", "", None, None, "", gr.update(visible=False), gr.update(visible=False), "{}", "", ""
1404
+
1405
+ life_row = df_eos.iloc[int(res["row_idx"])]
1406
+ eos, eol, status = row_to_dates_and_status(life_row)
1407
+
1408
+ repl = pick_replacements_lifecycle(life_row, status, use_gpt=True)
1409
+ canon_make = str(life_row.get("_canon_make","UNKNOWN"))
1410
+ mimo = infer_mimo_for_5g(repl.get("repl_5g",""))
1411
+ tech = "5G" if repl.get("repl_5g") and repl.get("repl_5g") != "Not listed" else ("4G" if device_is_4g(life_row) else "Unknown")
1412
+ ant = antenna_options_for(repl.get("repl_5g") or str(life_row.get("sku","")), tech, mimo)
1413
+
1414
+ output = assemble_output(life_row, status, eos, eol, repl, ant)
1415
+ st_out = {"row_idx": int(res["row_idx"]), "repl": repl, "ant": ant, "raw": user_text}
1416
+ url5 = _best_effort_manufacturer_url(repl.get('repl_5g',''), canon_make)
1417
+ link = f"**5G manufacturer page (best effort):** {url5}" if url5 else ""
1418
+ feat_df = build_replacement_features_table(repl.get('repl_4g',''), repl.get('repl_5g',''), canon_make)
1419
+ fit = build_fit_table(repl.get('repl_4g',''), repl.get('repl_5g',''), canon_make)
1420
+ return output, link, feat_df, fit, "", gr.update(visible=False), gr.update(visible=False), state_dump(st_out), "", ""
1421
+
1422
+ def use_selection(selected_label: str, st_json: str):
1423
+ st = state_load(st_json)
1424
+ if not st or st.get("mode") != "pick":
1425
+ return "Run a search first.", "", None, None, "", gr.update(visible=False), gr.update(visible=False), "{}", "", ""
1426
+
1427
+ if not selected_label:
1428
+ return "Pick A or B first.", "", None, None, "", gr.update(visible=True), gr.update(visible=True), st_json, "", ""
1429
+
1430
+ chosen_row = None
1431
+ for o in st.get("options", []):
1432
+ if o.get("label") == selected_label:
1433
+ chosen_row = int(o["row_idx"])
1434
+ break
1435
+ if chosen_row is None:
1436
+ return "Pick a valid option.", "", None, None, "", gr.update(visible=True), gr.update(visible=True), st_json, "", ""
1437
+
1438
+ life_row = df_eos.iloc[int(chosen_row)]
1439
+ eos, eol, status = row_to_dates_and_status(life_row)
1440
+
1441
+ repl = pick_replacements_lifecycle(life_row, status, use_gpt=True)
1442
+ canon_make = str(life_row.get("_canon_make","UNKNOWN"))
1443
+ mimo = infer_mimo_for_5g(repl.get("repl_5g",""))
1444
+ tech = "5G" if repl.get("repl_5g") and repl.get("repl_5g") != "Not listed" else ("4G" if device_is_4g(life_row) else "Unknown")
1445
+ ant = antenna_options_for(repl.get("repl_5g") or str(life_row.get("sku","")), tech, mimo)
1446
+
1447
+ output = assemble_output(life_row, status, eos, eol, repl, ant)
1448
+ st_out = {"row_idx": int(chosen_row), "repl": repl, "ant": ant, "raw": st.get("raw","")}
1449
+ url5 = _best_effort_manufacturer_url(repl.get('repl_5g',''), canon_make)
1450
+ link = f"**5G manufacturer page (best effort):** {url5}" if url5 else ""
1451
+ feat_df = build_replacement_features_table(repl.get('repl_4g',''), repl.get('repl_5g',''), canon_make)
1452
+ fit = build_fit_table(repl.get('repl_4g',''), repl.get('repl_5g',''), canon_make)
1453
+ return output, link, feat_df, fit, "", gr.update(visible=False), gr.update(visible=False), state_dump(st_out), "", ""
1454
+
1455
+ def make_install_ready(st_json: str):
1456
+ st = state_load(st_json)
1457
+ if not st or "row_idx" not in st:
1458
+ return "Run a lookup first."
1459
+ life_row = df_eos.iloc[int(st["row_idx"])]
1460
+ current_sku = str(life_row.get("sku","") or "")
1461
+ return install_ready_checklist(current_sku, st.get("repl", {}) or {}, st.get("ant", {}) or {})
1462
+
1463
+
1464
+
1465
+ # ============================
1466
+ # Q&A about the suggested device (post-recommendation)
1467
+ # ============================
1468
+ def answer_question(question: str, st_json: str) -> str:
1469
+ q = str(question or "").strip()
1470
+ if not q:
1471
+ return ""
1472
+ st = state_load(st_json)
1473
+ if not st or "repl" not in st:
1474
+ return "Run a lookup first, then ask your question."
1475
+
1476
+ repl = st.get("repl", {}) or {}
1477
+ ant = st.get("ant", {}) or {}
1478
+ repl5 = str(repl.get("repl_5g","") or "").strip()
1479
+ repl4 = str(repl.get("repl_4g","") or "").strip()
1480
+ # Pull a bit of dec context for the 5G model (if possible)
1481
+ canon_make = ""
1482
+ try:
1483
+ # Try to infer maker family from stored row_idx
1484
+ if "row_idx" in st:
1485
+ row = df_eos.iloc[int(st["row_idx"])]
1486
+ canon_make = str(row.get("_canon_make","UNKNOWN"))
1487
+ except Exception:
1488
+ canon_make = ""
1489
+
1490
+ # Manufacturer link (best effort)
1491
+ url5 = _best_effort_manufacturer_url(repl5, canon_make) if repl5 else ""
1492
+
1493
+ # Feature table row for 5G (helps the LLM answer spec questions without web scraping)
1494
+ feat5 = {}
1495
+ try:
1496
+ feat5 = _features_from_dec(repl5, canon_make) if repl5 else {}
1497
+ except Exception:
1498
+ feat5 = {}
1499
+
1500
+ sys = (
1501
+ "You are a Verizon field rep assistant. Answer questions about the suggested router in a fast, practical way. "
1502
+ "Use the provided context; do not mention internal tools, prompts, embeddings, or databases. "
1503
+ "If the question is about specs and the value is unknown, say 'Not listed' and suggest checking the manufacturer page. "
1504
+ "Keep it concise and scannable."
1505
+ )
1506
+
1507
+ context = {
1508
+ "recommended_5g": repl5,
1509
+ "recommended_4g": repl4 if repl4 and repl4.lower() != "not applicable" else "",
1510
+ "manufacturer_link_5g": url5,
1511
+ "known_5g_features": feat5,
1512
+ "antenna_stationary": ant.get("stationary_omni", {}),
1513
+ "antenna_vehicle": ant.get("vehicle_omni", {}),
1514
+ }
1515
+
1516
+ user = "Context:\n" + json.dumps(context, ensure_ascii=False) + "\n\nQuestion:\n" + q
1517
+
1518
+ ans = gpt_answer_md(sys, user, max_tokens=650)
1519
+ # Small safety fallback
1520
+ return ans if ans else "I couldn't generate an answer right now. Try again."
1521
+
1522
+ # ============================
1523
+ # UI
1524
+ # ============================
1525
+ with gr.Blocks(title="Only-Routers") as demo:
1526
+ gr.Markdown("## Only-Routers\nSingle lookup + Batch upload for Verizon reps.")
1527
+
1528
+ with gr.Tabs():
1529
+ with gr.Tab("Single"):
1530
+ # Inputs
1531
+ user_text = gr.Textbox(
1532
+ label="Router SKU or model",
1533
+ placeholder="Examples: IBR650B, AER1600, ES450, WR21, RUT240",
1534
+ lines=1,
1535
+ )
1536
+ st = gr.State("{}") # JSON string state
1537
+
1538
+ # Actions
1539
+ check_btn = gr.Button("Check", variant="primary")
1540
+ pick_dd = gr.Dropdown(label="Pick A or B", choices=[], visible=False)
1541
+ use_btn = gr.Button("Use selection", visible=False)
1542
+
1543
+ # Main outputs
1544
+ output_md = gr.Markdown()
1545
+ link_md = gr.Markdown()
1546
+ features_df = gr.Dataframe(headers=FEATURE_COLS, interactive=False, wrap=True)
1547
+ fit_df = gr.Dataframe(headers=FIT_COLS, interactive=False, wrap=True)
1548
+ qa_md = gr.Markdown()
1549
+
1550
+ # Post-recommendation Q&A
1551
+ gr.Markdown("### Questions about the suggested device?")
1552
+ question_box = gr.Textbox(
1553
+ label="Ask a question (optional)",
1554
+ placeholder="Example: Does the 5G device support dual-SIM? How many ethernet ports? Does it support Wi‑Fi?",
1555
+ lines=2,
1556
+ )
1557
+ ask_btn = gr.Button("Ask", variant="secondary")
1558
+
1559
+ # Install-ready checklist
1560
+ install_btn = gr.Button("Make install-ready checklist")
1561
+ install_md = gr.Markdown()
1562
+
1563
+ # Customer-ready email summary
1564
+ gr.Markdown("### Customer-ready email")
1565
+ email_btn = gr.Button("Generate customer email")
1566
+ customer_email_box = gr.Textbox(label="Email draft", lines=10)
1567
+
1568
+ # Wiring (api_name=False avoids HF/Gradio API schema issues)
1569
+ check_btn.click(
1570
+ fn=run_lookup,
1571
+ inputs=[user_text, st],
1572
+ outputs=[output_md, link_md, features_df, fit_df, qa_md, pick_dd, use_btn, st, install_md, customer_email_box],
1573
+ api_name=False,
1574
+ )
1575
+ use_btn.click(
1576
+ fn=use_selection,
1577
+ inputs=[pick_dd, st],
1578
+ outputs=[output_md, link_md, features_df, fit_df, qa_md, pick_dd, use_btn, st, install_md, customer_email_box],
1579
+ api_name=False,
1580
+ )
1581
+ ask_btn.click(
1582
+ fn=answer_question,
1583
+ inputs=[question_box, st],
1584
+ outputs=[qa_md],
1585
+ api_name=False,
1586
+ )
1587
+ install_btn.click(
1588
+ fn=make_install_ready,
1589
+ inputs=[st],
1590
+ outputs=[install_md],
1591
+ api_name=False,
1592
+ )
1593
+ email_btn.click(
1594
+ fn=generate_customer_email,
1595
+ inputs=[st],
1596
+ outputs=[customer_email_box],
1597
+ api_name=False,
1598
+ )
1599
+
1600
+ with gr.Tab("Batch"):
1601
+ gr.Markdown("Paste one per line or upload a CSV (first column). Batch runs fast (no GPT).")
1602
+ batch_text = gr.Textbox(label="Paste devices (one per line)", lines=8, placeholder="WR21\nRUT240\nIBR650B")
1603
+ batch_file = gr.File(label="Upload CSV", file_types=[".csv"])
1604
+ include_ant = gr.Checkbox(label="Include antenna picks (slower)", value=False)
1605
+ run_btn = gr.Button("Run batch", variant="primary")
1606
+
1607
+ summary_md = gr.Markdown()
1608
+ rollup_md = gr.Markdown()
1609
+ table = gr.Dataframe(interactive=False, wrap=True)
1610
+ dl = gr.File(label="Download results CSV")
1611
+
1612
+ run_btn.click(
1613
+ fn=run_batch,
1614
+ inputs=[batch_text, batch_file, include_ant],
1615
+ outputs=[summary_md, table, dl, rollup_md],
1616
+ api_name=False,
1617
+ )
1618
+
1619
+ demo.launch(show_api=False)
app.py CHANGED
@@ -967,6 +967,25 @@ def _best_effort_manufacturer_url(model: str, canon_make: str) -> str:
967
  d0 = domains[0]
968
  return f"https://{d0}"
969
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
970
  def _features_from_dec(model: str, canon_make: str) -> Dict[str, str]:
971
  """Lookup a router model in dec2025routers.csv and return the key feature fields."""
972
  if not model or model in {"Not listed", "Not applicable"}:
@@ -991,7 +1010,7 @@ def _features_from_dec(model: str, canon_make: str) -> Dict[str, str]:
991
  "Use case": str(r.get("Primary use case","")) or "Not listed",
992
  }
993
 
994
- def _gpt_fill_feature_row(device_label: str, model: str, canon_make: str, row: Dict[str, str]) -> Dict[str, str]:
995
  """If dec can't supply values, ask GPT to fill missing ones (best guess)."""
996
  if client is None:
997
  return row
@@ -1000,6 +1019,31 @@ def _gpt_fill_feature_row(device_label: str, model: str, canon_make: str, row: D
1000
  if not missing:
1001
  return row
1002
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1003
  sys = "Fill missing router feature fields for a Verizon rep. Return strict JSON only."
1004
  payload = {
1005
  "device_label": device_label,
@@ -1024,20 +1068,22 @@ def _gpt_fill_feature_row(device_label: str, model: str, canon_make: str, row: D
1024
  def build_replacement_features_table(repl_4g: str, repl_5g: str, canon_make: str) -> pd.DataFrame:
1025
  rows = []
1026
 
1027
- # 4G
1028
  row4 = _features_from_dec(repl_4g, canon_make)
1029
- row4 = _gpt_fill_feature_row("4G alternative", repl_4g, canon_make, row4)
 
 
1030
  rows.append({"Device": "4G alternative", **row4})
1031
 
1032
- # 5G
1033
  row5 = _features_from_dec(repl_5g, canon_make)
1034
- row5 = _gpt_fill_feature_row("5G replacement", repl_5g, canon_make, row5)
 
 
1035
  rows.append({"Device": "5G replacement", **row5})
1036
 
1037
  df = pd.DataFrame(rows, columns=FEATURE_COLS)
1038
  return df
1039
-
1040
-
1041
  # ============================
1042
  # Verizon fit badges (small table) for recommended devices
1043
  # ============================
 
967
  d0 = domains[0]
968
  return f"https://{d0}"
969
 
970
+ def _fetch_page_text(url: str, max_chars: int = 12000) -> str:
971
+ """Fetch page HTML and return a simplified text blob for GPT (best effort)."""
972
+ if not url:
973
+ return ""
974
+ try:
975
+ import requests
976
+ r = requests.get(url, headers=HTTP_HEADERS, timeout=HTTP_TIMEOUT, allow_redirects=True)
977
+ if r.status_code != 200:
978
+ return ""
979
+ html = r.text or ""
980
+ html = re.sub(r"(?is)<script.*?>.*?</script>", " ", html)
981
+ html = re.sub(r"(?is)<style.*?>.*?</style>", " ", html)
982
+ text = re.sub(r"(?is)<[^>]+>", " ", html)
983
+ text = re.sub(r"\s+", " ", text).strip()
984
+ return text[:max_chars]
985
+ except Exception:
986
+ return ""
987
+
988
+
989
  def _features_from_dec(model: str, canon_make: str) -> Dict[str, str]:
990
  """Lookup a router model in dec2025routers.csv and return the key feature fields."""
991
  if not model or model in {"Not listed", "Not applicable"}:
 
1010
  "Use case": str(r.get("Primary use case","")) or "Not listed",
1011
  }
1012
 
1013
+ def _gpt_fill_feature_row(device_label: str, model: str, canon_make: str, row: Dict[str, str], manufacturer_url: str = "", page_text: str = "") -> Dict[str, str]:
1014
  """If dec can't supply values, ask GPT to fill missing ones (best guess)."""
1015
  if client is None:
1016
  return row
 
1019
  if not missing:
1020
  return row
1021
 
1022
+ sys = (
1023
+ "Fill missing router feature fields for a Verizon rep. Return strict JSON only. "
1024
+ "Use manufacturer page text when available. If still unknown, make a best-guess."
1025
+ )
1026
+ payload = {
1027
+ "device_label": device_label,
1028
+ "model": model,
1029
+ "maker_family": canon_make,
1030
+ "manufacturer_url": manufacturer_url,
1031
+ "manufacturer_page_text": page_text[:8000],
1032
+ "known": row,
1033
+ "fill_only": missing,
1034
+ "rules": ["Fill only requested fields.", "Short phrases only.", "Return JSON only."],
1035
+ "output_schema": {k: "string" for k in missing},
1036
+ }
1037
+ out = gpt_json(sys, payload, max_tokens=320) or {}
1038
+ for k in missing:
1039
+ val = str(out.get(k, "") or "").strip()
1040
+ if val:
1041
+ row[k] = val
1042
+ return row
1043
+ missing = [k for k,v in row.items() if (not v) or str(v).strip().lower() in {"not listed","nan",""}]
1044
+ if not missing:
1045
+ return row
1046
+
1047
  sys = "Fill missing router feature fields for a Verizon rep. Return strict JSON only."
1048
  payload = {
1049
  "device_label": device_label,
 
1068
  def build_replacement_features_table(repl_4g: str, repl_5g: str, canon_make: str) -> pd.DataFrame:
1069
  rows = []
1070
 
1071
+ # 4G alternative row
1072
  row4 = _features_from_dec(repl_4g, canon_make)
1073
+ url4 = _best_effort_manufacturer_url(repl_4g, canon_make) if repl_4g else ""
1074
+ txt4 = _fetch_page_text(url4) if url4 else ""
1075
+ row4 = _gpt_fill_feature_row("4G alternative", repl_4g, canon_make, row4, manufacturer_url=url4, page_text=txt4)
1076
  rows.append({"Device": "4G alternative", **row4})
1077
 
1078
+ # 5G replacement row
1079
  row5 = _features_from_dec(repl_5g, canon_make)
1080
+ url5 = _best_effort_manufacturer_url(repl_5g, canon_make) if repl_5g else ""
1081
+ txt5 = _fetch_page_text(url5) if url5 else ""
1082
+ row5 = _gpt_fill_feature_row("5G replacement", repl_5g, canon_make, row5, manufacturer_url=url5, page_text=txt5)
1083
  rows.append({"Device": "5G replacement", **row5})
1084
 
1085
  df = pd.DataFrame(rows, columns=FEATURE_COLS)
1086
  return df
 
 
1087
  # ============================
1088
  # Verizon fit badges (small table) for recommended devices
1089
  # ============================
only-routers_ai_poc_hf_fixed_v10_3.ipynb ADDED
@@ -0,0 +1,1699 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "bb819d45",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Only-Routers (v10.3)\n",
9
+ "\n",
10
+ "4G feature row now uses manufacturer page fetch + GPT fill (same as 5G)."
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": null,
16
+ "id": "cf67e3c9",
17
+ "metadata": {},
18
+ "outputs": [],
19
+ "source": [
20
+ "import os\n",
21
+ "import re\n",
22
+ "import json\n",
23
+ "import math\n",
24
+ "import hashlib\n",
25
+ "import tempfile\n",
26
+ "from dataclasses import dataclass\n",
27
+ "from datetime import datetime, date\n",
28
+ "from typing import Any, Dict, List, Optional, Tuple\n",
29
+ "\n",
30
+ "import numpy as np\n",
31
+ "import pandas as pd\n",
32
+ "\n",
33
+ "import fitz # PyMuPDF\n",
34
+ "import faiss\n",
35
+ "from sentence_transformers import SentenceTransformer\n",
36
+ "from rapidfuzz import fuzz, process\n",
37
+ "\n",
38
+ "import gradio as gr\n",
39
+ "from openai import OpenAI\n",
40
+ "\n",
41
+ "\n",
42
+ "# ============================\n",
43
+ "# Settings\n",
44
+ "# ============================\n",
45
+ "TODAY = date(2026, 1, 18)\n",
46
+ "OPENAI_MODEL = \"gpt-5.2\"\n",
47
+ "OPENAI_REASONING = {\"effort\": \"high\"}\n",
48
+ "MATCH_OK = 80\n",
49
+ "\n",
50
+ "EMBED_MODEL_NAME = \"sentence-transformers/all-MiniLM-L6-v2\"\n",
51
+ "PARSEC_CONTEXT_BEFORE = 900\n",
52
+ "PARSEC_CONTEXT_AFTER = 1600\n",
53
+ "\n",
54
+ "\n",
55
+ "# ============================\n",
56
+ "# OpenAI client (HF Space secret: OPENAI_API_KEY)\n",
57
+ "# ============================\n",
58
+ "API_KEY = os.getenv(\"OPENAI_API_KEY\", \"\").strip()\n",
59
+ "client = OpenAI(api_key=API_KEY) if API_KEY else None\n",
60
+ "\n",
61
+ "# ----------------------------\n",
62
+ "# Gradio state helpers\n",
63
+ "# Keep state as a JSON STRING to avoid schema issues on Hugging Face.\n",
64
+ "# ----------------------------\n",
65
+ "def state_load(st_json: str) -> Dict[str, Any]:\n",
66
+ " try:\n",
67
+ " if not st_json:\n",
68
+ " return {}\n",
69
+ " return json.loads(st_json) if isinstance(st_json, str) else {}\n",
70
+ " except Exception:\n",
71
+ " return {}\n",
72
+ "\n",
73
+ "def state_dump(st: Dict[str, Any]) -> str:\n",
74
+ " try:\n",
75
+ " return json.dumps(st or {}, ensure_ascii=False)\n",
76
+ " except Exception:\n",
77
+ " return \"{}\"\n",
78
+ "\n",
79
+ "\n",
80
+ "\n",
81
+ "# ============================\n",
82
+ "# Helpers\n",
83
+ "# ============================\n",
84
+ "def norm_text(s: Any) -> str:\n",
85
+ " try:\n",
86
+ " if s is None or (isinstance(s, float) and math.isnan(s)) or pd.isna(s):\n",
87
+ " return \"\"\n",
88
+ " except Exception:\n",
89
+ " pass\n",
90
+ " s = str(s).strip().lower()\n",
91
+ " s = re.sub(r\"[^a-z0-9\\s\\-\\/]\", \" \", s)\n",
92
+ " s = re.sub(r\"\\s+\", \" \", s).strip()\n",
93
+ " return s\n",
94
+ "\n",
95
+ "def safe_str(v: Any) -> str:\n",
96
+ " if v is None or (isinstance(v, float) and pd.isna(v)) or pd.isna(v):\n",
97
+ " return \"\"\n",
98
+ " return str(v).strip()\n",
99
+ "\n",
100
+ "def is_5g(modem_type: Any) -> bool:\n",
101
+ " s = norm_text(modem_type)\n",
102
+ " return (\"5g\" in s) or (\"nr\" in s)\n",
103
+ "\n",
104
+ "def json_load_safe(s: str) -> Dict[str, Any]:\n",
105
+ " try:\n",
106
+ " return json.loads(s)\n",
107
+ " except Exception:\n",
108
+ " return {}\n",
109
+ "\n",
110
+ "def gpt_json(system: str, payload: Dict[str, Any], max_tokens: int = 600) -> Dict[str, Any]:\n",
111
+ " if client is None:\n",
112
+ " return {}\n",
113
+ " resp = client.responses.create(\n",
114
+ " model=OPENAI_MODEL,\n",
115
+ " reasoning=OPENAI_REASONING,\n",
116
+ " input=[{\"role\":\"system\",\"content\":system},{\"role\":\"user\",\"content\":json.dumps(payload)}],\n",
117
+ " max_output_tokens=max_tokens,\n",
118
+ " )\n",
119
+ " return json_load_safe(getattr(resp, \"output_text\", \"\") or \"\")\n",
120
+ "\n",
121
+ "\n",
122
+ "def gpt_answer_md(system: str, user: str, max_tokens: int = 650) -> str:\n",
123
+ " \"\"\"Return a rep-friendly markdown answer.\"\"\"\n",
124
+ " if client is None:\n",
125
+ " return \"No API key is configured, so I can't answer detailed questions right now.\"\n",
126
+ " resp = client.responses.create(\n",
127
+ " model=OPENAI_MODEL,\n",
128
+ " reasoning=OPENAI_REASONING,\n",
129
+ " input=[\n",
130
+ " {\"role\": \"system\", \"content\": system},\n",
131
+ " {\"role\": \"user\", \"content\": user},\n",
132
+ " ],\n",
133
+ " max_output_tokens=max_tokens,\n",
134
+ " )\n",
135
+ " return (getattr(resp, \"output_text\", \"\") or \"\").strip()\n",
136
+ "\n",
137
+ "\n",
138
+ "# ============================\n",
139
+ "# Load data\n",
140
+ "# ============================\n",
141
+ "EOS_PATH = \"routers_eos_eol_by_sku.csv\"\n",
142
+ "DEC_PATH = \"dec2025routers.csv\"\n",
143
+ "PARSEC_PDF = \"ParsecCatalog.pdf\"\n",
144
+ "\n",
145
+ "if not os.path.exists(EOS_PATH):\n",
146
+ " raise FileNotFoundError(f\"Missing {EOS_PATH} in repo.\")\n",
147
+ "if not os.path.exists(DEC_PATH):\n",
148
+ " raise FileNotFoundError(f\"Missing {DEC_PATH} in repo.\")\n",
149
+ "if not os.path.exists(PARSEC_PDF):\n",
150
+ " raise FileNotFoundError(f\"Missing {PARSEC_PDF} in repo.\")\n",
151
+ "\n",
152
+ "df_eos = pd.read_csv(EOS_PATH).copy()\n",
153
+ "df_dec = pd.read_csv(DEC_PATH).copy()\n",
154
+ "\n",
155
+ "\n",
156
+ "def _canonize_eos_columns(df: pd.DataFrame) -> pd.DataFrame:\n",
157
+ " \"\"\"Normalize lifecycle CSV column names (case-insensitive) and create expected columns.\"\"\"\n",
158
+ " # Map various header spellings to canonical names used by the app\n",
159
+ " mapping = {}\n",
160
+ " for c in df.columns:\n",
161
+ " k = str(c).strip().lower().replace(\" \", \"_\")\n",
162
+ " if k in {\"sku\", \"model\", \"device\", \"device_sku\"}:\n",
163
+ " mapping[c] = \"sku\"\n",
164
+ " elif k in {\"manufacturer\", \"make\", \"vendor\"}:\n",
165
+ " mapping[c] = \"manufacturer\"\n",
166
+ " elif k in {\"device_type\", \"type\"}:\n",
167
+ " mapping[c] = \"device_type\"\n",
168
+ " elif k in {\"end_of_sale\", \"eos\", \"end_sale\", \"end_of_sales\"}:\n",
169
+ " mapping[c] = \"end_of_sale\"\n",
170
+ " elif k in {\"end_of_life\", \"eol\", \"end_life\"}:\n",
171
+ " mapping[c] = \"end_of_life\"\n",
172
+ " elif k in {\"suggested_replacement\", \"replacement_4g\", \"lte_replacement\", \"replacement_lte\", \"replacement\"}:\n",
173
+ " mapping[c] = \"suggested_replacement\"\n",
174
+ " elif k in {\"advanced_5g_option\", \"replacement_5g\", \"fiveg_replacement\", \"5g_replacement\", \"upgrade_5g\"}:\n",
175
+ " mapping[c] = \"advanced_5g_option\"\n",
176
+ " elif k in {\"region\", \"market\"}:\n",
177
+ " mapping[c] = \"region\"\n",
178
+ " elif k in {\"notes\", \"note\"}:\n",
179
+ " mapping[c] = \"notes\"\n",
180
+ " elif k in {\"description\", \"device_description\", \"name\"}:\n",
181
+ " mapping[c] = \"description\"\n",
182
+ "\n",
183
+ " df = df.rename(columns=mapping).copy()\n",
184
+ "\n",
185
+ " # Create expected columns if missing\n",
186
+ " if \"sku\" not in df.columns:\n",
187
+ " # Try the common capitalized header as a fallback\n",
188
+ " if \"SKU\" in df.columns:\n",
189
+ " df[\"sku\"] = df[\"SKU\"].astype(str)\n",
190
+ " else:\n",
191
+ " df[\"sku\"] = \"\"\n",
192
+ "\n",
193
+ " if \"manufacturer\" not in df.columns:\n",
194
+ " df[\"manufacturer\"] = \"\"\n",
195
+ "\n",
196
+ " if \"device_type\" not in df.columns:\n",
197
+ " df[\"device_type\"] = \"\"\n",
198
+ "\n",
199
+ " if \"description\" not in df.columns:\n",
200
+ " # If the simplified file removed description, use SKU as description (still searchable)\n",
201
+ " df[\"description\"] = df[\"sku\"].astype(str)\n",
202
+ "\n",
203
+ " if \"notes\" not in df.columns:\n",
204
+ " df[\"notes\"] = \"\"\n",
205
+ "\n",
206
+ " if \"region\" not in df.columns:\n",
207
+ " df[\"region\"] = \"\"\n",
208
+ "\n",
209
+ " if \"suggested_replacement\" not in df.columns:\n",
210
+ " df[\"suggested_replacement\"] = \"\"\n",
211
+ "\n",
212
+ " if \"advanced_5g_option\" not in df.columns:\n",
213
+ " df[\"advanced_5g_option\"] = \"\"\n",
214
+ "\n",
215
+ " if \"end_of_sale\" not in df.columns:\n",
216
+ " df[\"end_of_sale\"] = \"\"\n",
217
+ "\n",
218
+ " if \"end_of_life\" not in df.columns:\n",
219
+ " df[\"end_of_life\"] = \"\"\n",
220
+ "\n",
221
+ " return df\n",
222
+ "\n",
223
+ "df_eos = _canonize_eos_columns(df_eos)\n",
224
+ "\n",
225
+ "\n",
226
+ "def region_ok(x: Any) -> bool:\n",
227
+ " s = str(x or \"\").strip().lower()\n",
228
+ " if not s:\n",
229
+ " return True\n",
230
+ " if \"not specified\" in s:\n",
231
+ " return True\n",
232
+ " if \"north america\" in s:\n",
233
+ " return True\n",
234
+ " if re.search(r\"\\busa\\b\", s):\n",
235
+ " return True\n",
236
+ " if re.search(r\"\\bunited\\s+states\\b\", s):\n",
237
+ " return True\n",
238
+ " if re.search(r\"\\bu\\.?s\\.?\\b\", s):\n",
239
+ " return True\n",
240
+ " return False\n",
241
+ "\n",
242
+ "if \"region\" in df_eos.columns:\n",
243
+ " df_eos = df_eos[df_eos[\"region\"].apply(region_ok)].reset_index(drop=True)\n",
244
+ "\n",
245
+ "# Maker mapping (includes Teltonika)\n",
246
+ "CANON_MAKER = {\n",
247
+ " \"CRADLEPOINT\": {\"cradlepoint\", \"ericsson\", \"ericsson enterprise wireless\"},\n",
248
+ " \"SIERRA\": {\"sierra\", \"sierra wireless\", \"semtech\", \"airlink\"},\n",
249
+ " \"FEENEY\": {\"feeney\", \"feeney wireless\", \"inseego\"},\n",
250
+ " \"DIGI\": {\"digi\", \"accelerated\", \"accelerated concepts\"},\n",
251
+ " \"CISCO_MERAKI\": {\"meraki\", \"cisco meraki\"},\n",
252
+ " \"CISCO\": {\"cisco\"},\n",
253
+ " \"TELTONIKA\": {\"teltonika\"},\n",
254
+ "}\n",
255
+ "\n",
256
+ "def canon_maker_from_text(s: Any) -> str:\n",
257
+ " t = norm_text(s)\n",
258
+ " for canon, terms in CANON_MAKER.items():\n",
259
+ " for term in terms:\n",
260
+ " if term in t:\n",
261
+ " return canon\n",
262
+ " return \"UNKNOWN\"\n",
263
+ "\n",
264
+ "df_eos[\"_canon_make\"] = df_eos[\"manufacturer\"].apply(canon_maker_from_text) if \"manufacturer\" in df_eos.columns else \"UNKNOWN\"\n",
265
+ "df_eos[\"_norm_sku\"] = df_eos[\"sku\"].apply(norm_text) if \"sku\" in df_eos.columns else \"\"\n",
266
+ "df_eos[\"_norm_desc\"] = df_eos[\"description\"].apply(norm_text) if \"description\" in df_eos.columns else \"\"\n",
267
+ "df_eos[\"_norm_notes\"] = df_eos[\"notes\"].apply(norm_text) if \"notes\" in df_eos.columns else \"\"\n",
268
+ "\n",
269
+ "df_dec[\"_canon_make\"] = df_dec[\"Make\"].apply(canon_maker_from_text) if \"Make\" in df_dec.columns else \"UNKNOWN\"\n",
270
+ "df_dec[\"_norm_model\"] = df_dec[\"Model\"].apply(norm_text) if \"Model\" in df_dec.columns else \"\"\n",
271
+ "df_dec[\"_is5g\"] = df_dec[\"Modem Type\"].apply(is_5g) if \"Modem Type\" in df_dec.columns else False\n",
272
+ "\n",
273
+ "\n",
274
+ "# ============================\n",
275
+ "# Date helpers\n",
276
+ "# ============================\n",
277
+ "@dataclass\n",
278
+ "class ParsedDate:\n",
279
+ " raw: str\n",
280
+ " kind: str\n",
281
+ " value: Optional[date]\n",
282
+ "\n",
283
+ "def parse_date_field(x: Any) -> ParsedDate:\n",
284
+ " raw = str(x or \"\").strip()\n",
285
+ " if not raw:\n",
286
+ " return ParsedDate(raw=\"\", kind=\"missing\", value=None)\n",
287
+ "\n",
288
+ " # Common US formats: M/D/YY or M/D/YYYY (e.g., 6/24/24, 9/30/21)\n",
289
+ " for fmt in (\"%m/%d/%y\", \"%m/%d/%Y\", \"%-m/%-d/%y\", \"%-m/%-d/%Y\"):\n",
290
+ " try:\n",
291
+ " dt = datetime.strptime(raw, fmt).date()\n",
292
+ " return ParsedDate(raw=raw, kind=\"full\", value=dt)\n",
293
+ " except Exception:\n",
294
+ " pass\n",
295
+ "\n",
296
+ " # ISO-ish: YYYY\n",
297
+ " if re.fullmatch(r\"\\d{4}\", raw):\n",
298
+ " y = int(raw)\n",
299
+ " if y == TODAY.year:\n",
300
+ " return ParsedDate(raw=raw, kind=\"year\", value=date(y, 1, 1))\n",
301
+ " if y < TODAY.year:\n",
302
+ " return ParsedDate(raw=raw, kind=\"year\", value=date(y, 1, 1))\n",
303
+ " return ParsedDate(raw=raw, kind=\"year\", value=date(y, 12, 31))\n",
304
+ "\n",
305
+ " # YYYY-MM\n",
306
+ " if re.fullmatch(r\"\\d{4}-\\d{2}\", raw):\n",
307
+ " try:\n",
308
+ " y, m = raw.split(\"-\")\n",
309
+ " return ParsedDate(raw=raw, kind=\"year_month\", value=date(int(y), int(m), 1))\n",
310
+ " except Exception:\n",
311
+ " return ParsedDate(raw=raw, kind=\"bad\", value=None)\n",
312
+ "\n",
313
+ " # YYYY-MM-DD\n",
314
+ " if re.fullmatch(r\"\\d{4}-\\d{2}-\\d{2}\", raw):\n",
315
+ " try:\n",
316
+ " dt = datetime.strptime(raw, \"%Y-%m-%d\").date()\n",
317
+ " return ParsedDate(raw=raw, kind=\"full\", value=dt)\n",
318
+ " except Exception:\n",
319
+ " return ParsedDate(raw=raw, kind=\"bad\", value=None)\n",
320
+ "\n",
321
+ " # Last resort: leave as raw (unparsed)\n",
322
+ " return ParsedDate(raw=raw, kind=\"bad\", value=None)\n",
323
+ "\n",
324
+ " if re.fullmatch(r\"\\d{4}-\\d{2}-\\d{2}\", raw):\n",
325
+ " try:\n",
326
+ " dt = datetime.strptime(raw, \"%Y-%m-%d\").date()\n",
327
+ " return ParsedDate(raw=raw, kind=\"full\", value=dt)\n",
328
+ " except Exception:\n",
329
+ " return ParsedDate(raw=raw, kind=\"bad\", value=None)\n",
330
+ "\n",
331
+ " return ParsedDate(raw=raw, kind=\"bad\", value=None)\n",
332
+ "\n",
333
+ "def display_date(pd_: ParsedDate) -> str:\n",
334
+ " if pd_.kind == \"missing\":\n",
335
+ " return \"Not listed\"\n",
336
+ " if pd_.kind == \"bad\":\n",
337
+ " return pd_.raw or \"Not listed\"\n",
338
+ " return pd_.raw\n",
339
+ "\n",
340
+ "def status_from_eos_eol(eos: ParsedDate, eol: ParsedDate) -> str:\n",
341
+ " if eos.value is None and eol.value is None:\n",
342
+ " return \"Unknown\"\n",
343
+ " if eol.value is not None and eol.value <= TODAY:\n",
344
+ " return \"End of Life\"\n",
345
+ " if eos.value is not None and eos.value <= TODAY:\n",
346
+ " return \"End of Sale\"\n",
347
+ " return \"Active\"\n",
348
+ "\n",
349
+ "def row_to_dates_and_status(row: pd.Series) -> Tuple[str, str, str]:\n",
350
+ " eos = parse_date_field(row.get(\"end_of_sale\"))\n",
351
+ " eol = parse_date_field(row.get(\"end_of_life\"))\n",
352
+ " return display_date(eos), display_date(eol), status_from_eos_eol(eos, eol)\n",
353
+ "\n",
354
+ "\n",
355
+ "# ============================\n",
356
+ "# Embeddings + Parsec index\n",
357
+ "# ============================\n",
358
+ "embedder = SentenceTransformer(EMBED_MODEL_NAME)\n",
359
+ "\n",
360
+ "def extract_pdf_text_pages(path: str) -> List[str]:\n",
361
+ " doc = fitz.open(path)\n",
362
+ " return [doc[i].get_text(\"text\") for i in range(len(doc))]\n",
363
+ "\n",
364
+ "def build_parsec_cards(pages: List[str]) -> List[str]:\n",
365
+ " cards = []\n",
366
+ " for p in pages:\n",
367
+ " for m in re.finditer(r\"Standard\\s+SKU:\", p):\n",
368
+ " start = max(0, m.start() - PARSEC_CONTEXT_BEFORE)\n",
369
+ " end = min(len(p), m.start() + PARSEC_CONTEXT_AFTER)\n",
370
+ " c = p[start:end].strip()\n",
371
+ " if len(c) >= 200:\n",
372
+ " cards.append(c)\n",
373
+ " out, seen = [], set()\n",
374
+ " for c in cards:\n",
375
+ " h = hashlib.sha1(c.encode(\"utf-8\")).hexdigest()\n",
376
+ " if h not in seen:\n",
377
+ " seen.add(h); out.append(c)\n",
378
+ " return out\n",
379
+ "\n",
380
+ "parsec_cards = build_parsec_cards(extract_pdf_text_pages(PARSEC_PDF))\n",
381
+ "parsec_emb = embedder.encode(parsec_cards, batch_size=64, show_progress_bar=False, normalize_embeddings=True)\n",
382
+ "parsec_emb = np.asarray(parsec_emb, dtype=np.float32)\n",
383
+ "parsec_index = faiss.IndexFlatIP(parsec_emb.shape[1])\n",
384
+ "parsec_index.add(parsec_emb)\n",
385
+ "\n",
386
+ "\n",
387
+ "# ============================\n",
388
+ "# Device resolution\n",
389
+ "# ============================\n",
390
+ "def label_for_row(i: int) -> str:\n",
391
+ " r = df_eos.iloc[i]\n",
392
+ " return f\"{r.get('sku','')} — {r.get('manufacturer','')} — {r.get('description','')}\"[:220]\n",
393
+ "\n",
394
+ "EOS_LABELS = [label_for_row(i) for i in range(len(df_eos))]\n",
395
+ "EOS_CORPUS = []\n",
396
+ "for _, r in df_eos.iterrows():\n",
397
+ " EOS_CORPUS.append(\" \".join([r.get(\"_norm_sku\",\"\"), r.get(\"_canon_make\",\"\"), r.get(\"_norm_desc\",\"\"), r.get(\"_norm_notes\",\"\")]))\n",
398
+ "\n",
399
+ "def local_candidates(query: str, top_k: int = 6) -> List[Tuple[int, int, str]]:\n",
400
+ " q = norm_text(query)\n",
401
+ " hits = process.extract(q, EOS_CORPUS, scorer=fuzz.WRatio, limit=top_k)\n",
402
+ " return [(int(idx), int(score), EOS_LABELS[int(idx)]) for _, score, idx in hits]\n",
403
+ "\n",
404
+ "def gpt_choose_device(user_text: str, candidates: List[Tuple[int,int,str]]) -> Dict[str, Any]:\n",
405
+ " if client is None:\n",
406
+ " return {}\n",
407
+ " sys = \"Pick which router the user meant. Never invent. Return strict JSON only.\"\n",
408
+ " payload = {\n",
409
+ " \"user_input\": user_text,\n",
410
+ " \"candidates\": [{\"row_idx\": i, \"score\": s, \"label\": lbl} for (i,s,lbl) in candidates],\n",
411
+ " \"rules\": [\n",
412
+ " \"If one is clearly correct, return mode='ok' with row_idx.\",\n",
413
+ " \"If two are plausible, return mode='pick' with top 2 options.\"\n",
414
+ " ],\n",
415
+ " \"output_schema\": {\"mode\":\"ok|pick\",\"row_idx\":\"int\",\"options\":[{\"row_idx\":\"int\",\"label\":\"string\"}]}\n",
416
+ " }\n",
417
+ " return gpt_json(sys, payload, max_tokens=280)\n",
418
+ "\n",
419
+ "def resolve_device(user_text: str) -> Dict[str, Any]:\n",
420
+ " q = norm_text(user_text)\n",
421
+ " exact = df_eos.index[df_eos[\"_norm_sku\"] == q].tolist()\n",
422
+ " if len(exact) == 1:\n",
423
+ " return {\"mode\":\"ok\",\"row_idx\": int(exact[0])}\n",
424
+ " if len(exact) > 1:\n",
425
+ " opts = [{\"row_idx\": int(i), \"label\": EOS_LABELS[int(i)]} for i in exact[:2]]\n",
426
+ " return {\"mode\":\"pick\",\"options\": opts}\n",
427
+ "\n",
428
+ " cands = local_candidates(user_text, top_k=6)\n",
429
+ " if not cands:\n",
430
+ " return {\"mode\":\"not_found\"}\n",
431
+ "\n",
432
+ " if cands[0][1] >= 95 and (len(cands) == 1 or (cands[0][1] - cands[1][1]) >= 8):\n",
433
+ " return {\"mode\":\"ok\",\"row_idx\": cands[0][0]}\n",
434
+ "\n",
435
+ " g = gpt_choose_device(user_text, cands)\n",
436
+ " if g.get(\"mode\") == \"ok\" and isinstance(g.get(\"row_idx\"), int):\n",
437
+ " return {\"mode\":\"ok\",\"row_idx\": int(g[\"row_idx\"])}\n",
438
+ "\n",
439
+ " if g.get(\"mode\") == \"pick\":\n",
440
+ " opts = g.get(\"options\", []) or []\n",
441
+ " opts2 = [{\"row_idx\": int(o[\"row_idx\"]), \"label\": str(o[\"label\"])} for o in opts[:2] if \"row_idx\" in o]\n",
442
+ " if opts2:\n",
443
+ " return {\"mode\":\"pick\",\"options\": opts2}\n",
444
+ "\n",
445
+ " if len(cands) > 1:\n",
446
+ " return {\"mode\":\"pick\",\"options\":[{\"row_idx\":cands[0][0],\"label\":cands[0][2]},{\"row_idx\":cands[1][0],\"label\":cands[1][2]}]}\n",
447
+ " return {\"mode\":\"pick\",\"options\":[{\"row_idx\":cands[0][0],\"label\":cands[0][2]}]}\n",
448
+ "\n",
449
+ "\n",
450
+ "# ============================\n",
451
+ "# Replacements — lifecycle CSV source of truth\n",
452
+ "# ============================\n",
453
+ "def extract_model_token(text: str) -> str:\n",
454
+ " s = safe_str(text)\n",
455
+ " if not s:\n",
456
+ " return \"\"\n",
457
+ " parts = [p.strip() for p in s.split(\"|\") if p.strip()]\n",
458
+ " candidates = parts[::-1] if parts else [s]\n",
459
+ " for cand in candidates:\n",
460
+ " m = re.search(r\"\\bRUT[A-Z]?\\d{2,4}\\b\", cand.upper())\n",
461
+ " if m:\n",
462
+ " return m.group(0).upper()\n",
463
+ " m = re.search(r\"\\bIX\\d{2}\\b\", cand, flags=re.IGNORECASE)\n",
464
+ " if m:\n",
465
+ " return m.group(0).upper()\n",
466
+ " m = re.search(r\"\\b(R\\d{3,4}|E\\d{3,4}|S\\d{3,4})\\b\", cand, flags=re.IGNORECASE)\n",
467
+ " if m:\n",
468
+ " return m.group(0).upper()\n",
469
+ " m = re.search(r\"\\b[A-Z]{1,6}\\d{2,4}[A-Z]?\\b\", cand.upper())\n",
470
+ " if m:\n",
471
+ " return m.group(0).upper()\n",
472
+ " return candidates[0][:60]\n",
473
+ "\n",
474
+ "def device_is_4g(row: pd.Series) -> bool:\n",
475
+ " # Detect LTE/4G even when the description uses \"Cat 4 / Cat6 / Cat 12\" without saying \"LTE\"\n",
476
+ " t = norm_text(row.get(\"description\",\"\")) + \" \" + norm_text(row.get(\"notes\",\"\")) + \" \" + norm_text(row.get(\"sku\",\"\"))\n",
477
+ "\n",
478
+ " # If it explicitly says 5G/NR, treat as not 4G-only\n",
479
+ " if (\"5g\" in t) or (\"nr\" in t):\n",
480
+ " return False\n",
481
+ "\n",
482
+ " # Classic signals\n",
483
+ " if (\"lte\" in t) or (\"4g\" in t):\n",
484
+ " return True\n",
485
+ "\n",
486
+ " # LTE category signals (Cat 1..20 are LTE categories; Cat M1/M2 are LTE-M)\n",
487
+ " if re.search(r\"\\bcat\\s*[-]?\\s*(m1|m2)\\b\", t):\n",
488
+ " return True\n",
489
+ "\n",
490
+ " m = re.search(r\"\\bcat\\s*[-]?\\s*(\\d{1,2})\\b\", t)\n",
491
+ " if m:\n",
492
+ " try:\n",
493
+ " cat = int(m.group(1))\n",
494
+ " if 0 < cat <= 20:\n",
495
+ " return True\n",
496
+ " except Exception:\n",
497
+ " pass\n",
498
+ "\n",
499
+ " # If \"cat\" appears at all, it's almost always LTE-family\n",
500
+ " if \"cat\" in t:\n",
501
+ " return True\n",
502
+ "\n",
503
+ " return False\n",
504
+ "\n",
505
+ " # If it explicitly says 5G/NR, treat as not 4G-only\n",
506
+ " if (\"5g\" in t) or (\"nr\" in t):\n",
507
+ " return False\n",
508
+ "\n",
509
+ " # Classic signals\n",
510
+ " if (\"lte\" in t) or (\"4g\" in t):\n",
511
+ " return True\n",
512
+ "\n",
513
+ " # LTE category signals (Cat 1..20 are LTE categories; Cat M1/M2 are LTE-M)\n",
514
+ " if re.search(r\"\\bcat\\s*[-]?\\s*(m1|m2)\\b\", t):\n",
515
+ " return True\n",
516
+ "\n",
517
+ " m = re.search(r\"\\bcat\\s*[-]?\\s*(\\d{1,2})\\b\", t)\n",
518
+ " if m:\n",
519
+ " try:\n",
520
+ " cat = int(m.group(1))\n",
521
+ " if 0 < cat <= 20:\n",
522
+ " return True\n",
523
+ " except Exception:\n",
524
+ " pass\n",
525
+ "\n",
526
+ " # If \"cat\" appears at all, it's almost always LTE-family\n",
527
+ " if \"cat\" in t:\n",
528
+ " return True\n",
529
+ "\n",
530
+ " return False\n",
531
+ "\n",
532
+ "\n",
533
+ "def candidate_5g_models_from_lifecycle(manufacturer: str) -> List[str]:\n",
534
+ " mfr = norm_text(manufacturer)\n",
535
+ " pool = df_eos[df_eos[\"manufacturer\"].astype(str).str.lower().eq(mfr)].copy() if \"manufacturer\" in df_eos.columns else df_eos.copy()\n",
536
+ " vals = pool[\"advanced_5g_option\"].tolist() if \"advanced_5g_option\" in pool.columns else []\n",
537
+ " out, seen = [], set()\n",
538
+ " for v in vals:\n",
539
+ " tok = extract_model_token(v)\n",
540
+ " if tok and tok.lower() != \"nan\" and tok not in seen:\n",
541
+ " seen.add(tok); out.append(tok)\n",
542
+ " return out\n",
543
+ "\n",
544
+ "def candidate_4g_models_from_lifecycle(manufacturer: str) -> List[str]:\n",
545
+ " mfr = norm_text(manufacturer)\n",
546
+ " pool = df_eos[df_eos[\"manufacturer\"].astype(str).str.lower().eq(mfr)].copy() if \"manufacturer\" in df_eos.columns else df_eos.copy()\n",
547
+ " vals = pool[\"suggested_replacement\"].tolist() if \"suggested_replacement\" in pool.columns else []\n",
548
+ " out, seen = [], set()\n",
549
+ " for v in vals:\n",
550
+ " tok = extract_model_token(v)\n",
551
+ " if tok and tok.lower() != \"nan\" and tok not in seen:\n",
552
+ " seen.add(tok); out.append(tok)\n",
553
+ " return out\n",
554
+ "\n",
555
+ "def gpt_pick_from_candidates(old_row: pd.Series, candidates: List[str], need: str) -> str:\n",
556
+ " if client is None or not candidates:\n",
557
+ " return \"\"\n",
558
+ " sys = \"Pick the best replacement model. Choose only from candidates. Return strict JSON only.\"\n",
559
+ " payload = {\n",
560
+ " \"old_device\": {\n",
561
+ " \"sku\": str(old_row.get(\"sku\",\"\")),\n",
562
+ " \"manufacturer\": str(old_row.get(\"manufacturer\",\"\")),\n",
563
+ " \"description\": str(old_row.get(\"description\",\"\")),\n",
564
+ " \"need\": need,\n",
565
+ " },\n",
566
+ " \"candidates\": candidates[:40],\n",
567
+ " \"output_schema\": {\"choice\":\"string\"}\n",
568
+ " }\n",
569
+ " out = gpt_json(sys, payload, max_tokens=240) or {}\n",
570
+ " choice = str(out.get(\"choice\",\"\") or \"\").strip()\n",
571
+ " return choice if choice in candidates else \"\"\n",
572
+ "\n",
573
+ "def fallback_5g_from_dec(canon_make: str) -> str:\n",
574
+ " pool5 = df_dec[(df_dec[\"_canon_make\"] == canon_make) & (df_dec[\"_is5g\"] == True)]\n",
575
+ " return str(pool5.iloc[0][\"Model\"]).strip() if not pool5.empty else \"\"\n",
576
+ "\n",
577
+ "def pick_replacements_lifecycle(row: pd.Series, status: str, use_gpt: bool = True) -> Dict[str, Any]:\n",
578
+ " canon = str(row.get(\"_canon_make\",\"UNKNOWN\"))\n",
579
+ " manufacturer = str(row.get(\"manufacturer\",\"\") or \"\")\n",
580
+ "\n",
581
+ " sug_raw = safe_str(row.get(\"suggested_replacement\",\"\"))\n",
582
+ " adv_raw = safe_str(row.get(\"advanced_5g_option\",\"\"))\n",
583
+ "\n",
584
+ " has_4g_alt = bool(sug_raw.strip())\n",
585
+ " has_5g_alt = bool(adv_raw.strip())\n",
586
+ "\n",
587
+ " # Treat as 4G if the description indicates LTE OR lifecycle provides a 4G suggested replacement\n",
588
+ " is_4g = device_is_4g(row) or has_4g_alt\n",
589
+ "\n",
590
+ " # Provide 5G option if the unit is 4G, EOS/EOL, or lifecycle explicitly provides advanced_5g_option\n",
591
+ " want_5g = is_4g or (status in {\"End of Sale\",\"End of Life\"}) or has_5g_alt\n",
592
+ "\n",
593
+ " # 4G alternative: show whenever lifecycle provides it (or device appears 4G)\n",
594
+ " repl_4g = \"Not applicable\"\n",
595
+ " if is_4g or has_4g_alt:\n",
596
+ " repl_4g = extract_model_token(sug_raw)\n",
597
+ " if not repl_4g:\n",
598
+ " cand4 = candidate_4g_models_from_lifecycle(manufacturer)\n",
599
+ " repl_4g = (gpt_pick_from_candidates(row, cand4, \"4G alternative\") if (use_gpt and client) else \"\") or (cand4[0] if cand4 else \"\")\n",
600
+ " if not repl_4g:\n",
601
+ " repl_4g = \"Not applicable\"\n",
602
+ "\n",
603
+ " # 5G replacement: prefer lifecycle advanced_5g_option whenever present\n",
604
+ " repl_5g = \"Not listed\"\n",
605
+ " if want_5g:\n",
606
+ " repl_5g = extract_model_token(adv_raw)\n",
607
+ " if not repl_5g:\n",
608
+ " cand5 = candidate_5g_models_from_lifecycle(manufacturer)\n",
609
+ " repl_5g = (gpt_pick_from_candidates(row, cand5, \"5G replacement/upgrade\") if (use_gpt and client) else \"\") or (cand5[0] if cand5 else \"\")\n",
610
+ " if not repl_5g:\n",
611
+ " repl_5g = fallback_5g_from_dec(canon) or \"Not listed\"\n",
612
+ "\n",
613
+ " if repl_5g.lower() == \"nan\":\n",
614
+ " repl_5g = \"Not listed\"\n",
615
+ "\n",
616
+ " return {\"repl_4g\": repl_4g, \"repl_5g\": repl_5g, \"sources\": [\"lifecycle_csv\"] + ([\"gpt\"] if (use_gpt and client) else [])}\n",
617
+ "\n",
618
+ "\n",
619
+ "# ============================\n",
620
+ "# Antennas (Parsec-only)\n",
621
+ "# ============================\n",
622
+ "PARSEC_FAMILY_WORDS = {\"chinook\",\"labrador\",\"boxer\",\"bloodhound\",\"husky\",\"beagle\",\"mastiff\",\"collie\",\"shepherd\",\"belgian\",\"australian\",\"terrier\",\"pyrenees\"}\n",
623
+ "BAD_NAME_MARKERS = {\"customization\",\"standard connectors\",\"connectors\",\"features\",\"benefits\",\"specifications\",\"mechanical\",\"electrical\",\"mounting\",\"accessories\",\"description:\",\"standard sku\"}\n",
624
+ "\n",
625
+ "def clean_line(s: str) -> str:\n",
626
+ " s = re.sub(r\"\\s+\", \" \", str(s or \"\").strip())\n",
627
+ " if re.fullmatch(r\"-[a-z0-9]+\", s.lower()):\n",
628
+ " return \"\"\n",
629
+ " return s\n",
630
+ "\n",
631
+ "def is_bad_name_line(line: str) -> bool:\n",
632
+ " low = line.lower()\n",
633
+ " if any(m in low for m in BAD_NAME_MARKERS):\n",
634
+ " return True\n",
635
+ " if re.search(r\"\\b-[a-z0-9]{1,4}\\b\", low) and len(low) <= 25:\n",
636
+ " return True\n",
637
+ " return False\n",
638
+ "\n",
639
+ "def family_from_line(line: str) -> str:\n",
640
+ " low = line.lower()\n",
641
+ " for fam in PARSEC_FAMILY_WORDS:\n",
642
+ " if fam in low:\n",
643
+ " return fam.capitalize()\n",
644
+ " return \"\"\n",
645
+ "\n",
646
+ "def parsec_connectors_from_card(t: str) -> str:\n",
647
+ " m = re.search(r\"Standard\\s+Connectors:\\s*(.+)\", t, flags=re.IGNORECASE)\n",
648
+ " if m:\n",
649
+ " return re.sub(r\"\\s+\", \" \", m.group(1).strip())[:80]\n",
650
+ " return \"\"\n",
651
+ "\n",
652
+ "def parsec_mounts_from_card(t: str) -> List[str]:\n",
653
+ " mounts = []\n",
654
+ " for m in re.finditer(r\"Mount:\\s*(.+)\", t, flags=re.IGNORECASE):\n",
655
+ " val = re.sub(r\"\\s+\", \" \", m.group(1).strip())\n",
656
+ " parts = [p.strip().lower() for p in val.split(\",\") if p.strip()]\n",
657
+ " mounts.extend(parts)\n",
658
+ " out = []\n",
659
+ " seen = set()\n",
660
+ " for x in mounts:\n",
661
+ " if x not in seen:\n",
662
+ " seen.add(x); out.append(x)\n",
663
+ " return out\n",
664
+ "\n",
665
+ "def parsec_name_from_card(card_text: str) -> str:\n",
666
+ " lines = [clean_line(ln) for ln in str(card_text or \"\").splitlines()]\n",
667
+ " lines = [ln for ln in lines if ln]\n",
668
+ "\n",
669
+ " for ln in lines:\n",
670
+ " if is_bad_name_line(ln):\n",
671
+ " continue\n",
672
+ " fam = family_from_line(ln)\n",
673
+ " if fam:\n",
674
+ " return fam\n",
675
+ "\n",
676
+ " sku_i = None\n",
677
+ " for i, ln in enumerate(lines):\n",
678
+ " if \"standard sku\" in ln.lower():\n",
679
+ " sku_i = i\n",
680
+ " break\n",
681
+ " if sku_i is not None:\n",
682
+ " window = lines[max(0, sku_i - 12):sku_i]\n",
683
+ " for ln in reversed(window):\n",
684
+ " if is_bad_name_line(ln):\n",
685
+ " continue\n",
686
+ " if 3 <= len(ln) <= 40 and re.search(r\"[A-Za-z]\", ln):\n",
687
+ " return ln.split()[0].capitalize()\n",
688
+ "\n",
689
+ " return \"Parsec antenna\"\n",
690
+ "\n",
691
+ "def parsec_part_from_card(t: str) -> str:\n",
692
+ " m = re.search(r\"Standard\\s+SKU:\\s*([A-Z0-9]+)\", t)\n",
693
+ " return m.group(1).strip() if m else \"\"\n",
694
+ "\n",
695
+ "def parsec_desc_from_card(t: str) -> str:\n",
696
+ " m = re.search(r\"Description:\\s*(.+?)(?:\\n|$)\", t, flags=re.IGNORECASE)\n",
697
+ " return re.sub(r\"\\s+\",\" \",m.group(1).strip())[:220] if m else \"\"\n",
698
+ "\n",
699
+ "def parsec_retrieve(query: str, top_k: int = 12) -> List[Dict[str, Any]]:\n",
700
+ " qv = embedder.encode([query], normalize_embeddings=True)\n",
701
+ " qv = np.asarray(qv, dtype=np.float32)\n",
702
+ " scores, ids = parsec_index.search(qv, top_k)\n",
703
+ " out: List[Dict[str, Any]] = []\n",
704
+ " for sc, i in zip(scores[0].tolist(), ids[0].tolist()):\n",
705
+ " if 0 <= int(i) < len(parsec_cards):\n",
706
+ " card = parsec_cards[int(i)]\n",
707
+ " out.append({\n",
708
+ " \"score\": float(sc),\n",
709
+ " \"name\": parsec_name_from_card(card),\n",
710
+ " \"part_number\": parsec_part_from_card(card),\n",
711
+ " \"description\": parsec_desc_from_card(card),\n",
712
+ " \"connectors\": parsec_connectors_from_card(card),\n",
713
+ " \"mounts\": parsec_mounts_from_card(card),\n",
714
+ " \"_card\": card.lower(),\n",
715
+ " })\n",
716
+ " return out\n",
717
+ "\n",
718
+ "def choose_best_parsec(cands: List[Dict[str, Any]], mode: str) -> Dict[str, Any]:\n",
719
+ " best = None\n",
720
+ " best_score = -1e9\n",
721
+ "\n",
722
+ " for c in cands:\n",
723
+ " card = c.get(\"_card\",\"\")\n",
724
+ " mounts = c.get(\"mounts\", []) or []\n",
725
+ " score = float(c.get(\"score\", 0.0))\n",
726
+ "\n",
727
+ " if \"omni\" in card:\n",
728
+ " score += 0.6\n",
729
+ " if \"directional\" in card:\n",
730
+ " score -= 1.5\n",
731
+ "\n",
732
+ " if mode == \"vehicle\":\n",
733
+ " if any(\"magnetic\" in m for m in mounts):\n",
734
+ " score += 3.0\n",
735
+ " if any(\"through\" in m for m in mounts):\n",
736
+ " score += 2.0\n",
737
+ " if any(\"wall\" in m for m in mounts) or any(\"pole\" in m for m in mounts):\n",
738
+ " score -= 1.2\n",
739
+ " if \"app: fixed\" in card and \"mobile\" not in card:\n",
740
+ " score -= 2.0\n",
741
+ "\n",
742
+ " if mode == \"stationary\":\n",
743
+ " if any(\"wall\" in m for m in mounts):\n",
744
+ " score += 2.0\n",
745
+ " if any(\"pole\" in m for m in mounts):\n",
746
+ " score += 1.8\n",
747
+ "\n",
748
+ " if score > best_score:\n",
749
+ " best_score = score\n",
750
+ " best = c\n",
751
+ "\n",
752
+ " if not best:\n",
753
+ " return {\"name\":\"Parsec antenna\",\"part_number\":\"\",\"description\":\"\",\"connectors\":\"\",\"mounts\":[]}\n",
754
+ "\n",
755
+ " best = dict(best)\n",
756
+ " best.pop(\"_card\", None)\n",
757
+ " return best\n",
758
+ "\n",
759
+ "\n",
760
+ "def infer_mimo_for_5g(repl_5g_model: str) -> str:\n",
761
+ " \"\"\"Rule: every 5G router uses a 4x4 antenna.\"\"\"\n",
762
+ " return \"4x4\"\n",
763
+ "\n",
764
+ " # If the model name hints 5G, lean 4x4\n",
765
+ " if \"5g\" in model.lower() or model.upper().startswith((\"R\", \"E\", \"S\", \"IX\", \"RUTM\")):\n",
766
+ " default = \"4x4\"\n",
767
+ " else:\n",
768
+ " default = \"2x2\"\n",
769
+ "\n",
770
+ " # Use dec2025routers.csv if we can match the model under the same maker family\n",
771
+ " try:\n",
772
+ " pool = df_dec[df_dec[\"_canon_make\"] == canon_make].copy()\n",
773
+ " if pool.empty:\n",
774
+ " return default\n",
775
+ " hit = process.extractOne(norm_text(model), pool[\"_norm_model\"].tolist(), scorer=fuzz.WRatio)\n",
776
+ " if not hit or hit[1] < MATCH_OK:\n",
777
+ " return default\n",
778
+ " row = pool.iloc[int(hit[2])]\n",
779
+ " txt2 = (str(row.get(\"Antennas (internal/external/both)\", \"\")) + \" \" + str(row.get(\"Modem Type\", \"\")) + \" \" + str(row.get(\"Special notes\",\"\"))).lower()\n",
780
+ " if \"4x4\" in txt2 or \"4 x 4\" in txt2 or \"4x 4\" in txt2:\n",
781
+ " return \"4x4\"\n",
782
+ " if \"2x2\" in txt2 or \"2 x 2\" in txt2:\n",
783
+ " return \"2x2\"\n",
784
+ " # If modem type includes 5G, lean 4x4\n",
785
+ " if \"5g\" in txt2 or \"nr\" in txt2:\n",
786
+ " return \"4x4\"\n",
787
+ " return default\n",
788
+ " except Exception:\n",
789
+ " return default\n",
790
+ "\n",
791
+ "def antenna_options_for(router_model: str, tech: str, mimo: str) -> Dict[str, Any]:\n",
792
+ " q_stationary = f\"{router_model} {tech} {mimo} omni stationary pole wall fixed site Parsec\"\n",
793
+ " q_vehicle = f\"{router_model} {tech} {mimo} omni vehicle mobile magnetic through-bolt Parsec\"\n",
794
+ "\n",
795
+ " cand_stationary = parsec_retrieve(q_stationary, top_k=12)\n",
796
+ " cand_vehicle = parsec_retrieve(q_vehicle, top_k=12)\n",
797
+ "\n",
798
+ " s = choose_best_parsec(cand_stationary, mode=\"stationary\")\n",
799
+ " v = choose_best_parsec(cand_vehicle, mode=\"vehicle\")\n",
800
+ "\n",
801
+ " s.update({\"mimo\": mimo, \"why\": \"Stationary omni best match.\"})\n",
802
+ " v.update({\"mimo\": mimo, \"why\": \"Vehicle omni best match.\"})\n",
803
+ "\n",
804
+ " return {\"stationary_omni\": s, \"vehicle_omni\": v, \"sources\":[\"parsec_rag\"]}\n",
805
+ "\n",
806
+ "\n",
807
+ "# ============================\n",
808
+ "# Install-ready checklist\n",
809
+ "# ============================\n",
810
+ "def install_ready_checklist(current_sku: str, repl: Dict[str,Any], ant: Dict[str,Any]) -> str:\n",
811
+ " st = ant.get(\"stationary_omni\", {})\n",
812
+ " vh = ant.get(\"vehicle_omni\", {})\n",
813
+ " if client is not None:\n",
814
+ " sys = \"Create a short, install-ready checklist for a Verizon rep. Return markdown only.\"\n",
815
+ " payload = {\"current_device\": current_sku, \"replacements\": repl, \"antennas\": {\"stationary\": st, \"vehicle\": vh}}\n",
816
+ " resp = client.responses.create(\n",
817
+ " model=OPENAI_MODEL,\n",
818
+ " reasoning=OPENAI_REASONING,\n",
819
+ " input=[{\"role\":\"system\",\"content\":sys},{\"role\":\"user\",\"content\":json.dumps(payload)}],\n",
820
+ " max_output_tokens=520,\n",
821
+ " )\n",
822
+ " return (getattr(resp, \"output_text\", \"\") or \"\").strip()\n",
823
+ " return \"\\n\".join([\n",
824
+ " \"### Install-ready checklist\",\n",
825
+ " f\"- Current device: {current_sku}\",\n",
826
+ " f\"- 5G replacement: {repl.get('repl_5g','')}\",\n",
827
+ " f\"- 4G alternative: {repl.get('repl_4g','Not applicable')}\",\n",
828
+ " f\"- Stationary omni antenna: {st.get('name','')} (PN {st.get('part_number','')})\",\n",
829
+ " f\"- Vehicle omni antenna: {vh.get('name','')} (PN {vh.get('part_number','')})\",\n",
830
+ " \"- Next steps: confirm mounting + cable lengths + power; place order; schedule install.\",\n",
831
+ " ])\n",
832
+ "\n",
833
+ "\n",
834
+ "# ============================\n",
835
+ "# Batch mode (NO GPT)\n",
836
+ "# ============================\n",
837
+ "def parse_batch_inputs(text_blob: str, file_obj: Any) -> List[str]:\n",
838
+ " items: List[str] = []\n",
839
+ " if file_obj is not None:\n",
840
+ " try:\n",
841
+ " path = file_obj.name if hasattr(file_obj, \"name\") else str(file_obj)\n",
842
+ " df = pd.read_csv(path)\n",
843
+ " col = df.columns[0]\n",
844
+ " items.extend([str(x).strip() for x in df[col].tolist() if str(x).strip()])\n",
845
+ " except Exception:\n",
846
+ " pass\n",
847
+ " if text_blob:\n",
848
+ " for ln in str(text_blob).splitlines():\n",
849
+ " ln = ln.strip()\n",
850
+ " if ln:\n",
851
+ " items.append(ln)\n",
852
+ " seen=set()\n",
853
+ " out=[]\n",
854
+ " for x in items:\n",
855
+ " k=norm_text(x)\n",
856
+ " if k and k not in seen:\n",
857
+ " seen.add(k); out.append(x)\n",
858
+ " return out\n",
859
+ "\n",
860
+ "def run_batch(text_blob: str, file_obj: Any, include_antennas: bool):\n",
861
+ " inputs = parse_batch_inputs(text_blob, file_obj)\n",
862
+ " if not inputs:\n",
863
+ " return \"\", None, None, \"\"\n",
864
+ "\n",
865
+ " rows=[]\n",
866
+ " for item in inputs:\n",
867
+ " res = resolve_device(item)\n",
868
+ " if res.get(\"mode\") != \"ok\":\n",
869
+ " rows.append({\"Input\": item, \"Matched\":\"\", \"Status\":\"Needs review\", \"EOS\":\"\", \"EOL\":\"\", \"4G alternative\":\"\", \"5G replacement\":\"\", \"Notes\":\"Not found/ambiguous\"})\n",
870
+ " continue\n",
871
+ "\n",
872
+ " life_row = df_eos.iloc[int(res[\"row_idx\"])]\n",
873
+ " eos, eol, status = row_to_dates_and_status(life_row)\n",
874
+ " repl = pick_replacements_lifecycle(life_row, status, use_gpt=False)\n",
875
+ "\n",
876
+ " rows.append({\n",
877
+ " \"Input\": item,\n",
878
+ " \"Matched\": str(life_row.get(\"sku\",\"\")),\n",
879
+ " \"Status\": status,\n",
880
+ " \"EOS\": eos,\n",
881
+ " \"EOL\": eol,\n",
882
+ " \"4G alternative\": repl.get(\"repl_4g\",\"\"),\n",
883
+ " \"5G replacement\": repl.get(\"repl_5g\",\"\"),\n",
884
+ " \"Notes\": \"\",\n",
885
+ " })\n",
886
+ "\n",
887
+ " out_df = pd.DataFrame(rows)\n",
888
+ " counts = out_df[\"Status\"].value_counts(dropna=False).to_dict()\n",
889
+ " top_5g = out_df[\"5G replacement\"].value_counts(dropna=False).head(5).to_dict()\n",
890
+ " summary = f\"Rows: {len(out_df)} | \" + \" | \".join([f\"{k}: {v}\" for k,v in counts.items()])\n",
891
+ " rollup = \"Top 5G recommendations:\\n\" + \"\\n\".join([f\"- {k}: {v}\" for k,v in top_5g.items() if str(k).strip()])\n",
892
+ "\n",
893
+ " tmp = tempfile.NamedTemporaryFile(delete=False, suffix=\".csv\")\n",
894
+ " out_df.to_csv(tmp.name, index=False)\n",
895
+ "\n",
896
+ " return summary, out_df, tmp.name, rollup\n",
897
+ "\n",
898
+ "\n",
899
+ "# ============================\n",
900
+ "# Replacement feature table + manufacturer link (5G device)\n",
901
+ "# ============================\n",
902
+ "\n",
903
+ "FEATURE_COLS = [\"Device\", \"Modem technology\", \"WiFi\", \"Ports\", \"Antennas\", \"Ruggedness\", \"Use case\"]\n",
904
+ "\n",
905
+ "# Manufacturer domains used for best-effort link resolution (no non-maker domains).\n",
906
+ "MAKER_DOMAINS = {\n",
907
+ " \"CRADLEPOINT\": [\"cradlepoint.com\", \"ericsson.com\"],\n",
908
+ " \"SIERRA\": [\"semtech.com\", \"airlink.com\"],\n",
909
+ " \"FEENEY\": [\"inseego.com\"],\n",
910
+ " \"DIGI\": [\"digi.com\"],\n",
911
+ " \"CISCO_MERAKI\": [\"meraki.cisco.com\", \"cisco.com\"],\n",
912
+ " \"CISCO\": [\"cisco.com\"],\n",
913
+ " \"TELTONIKA\": [\"teltonika-networks.com\"],\n",
914
+ " \"UNKNOWN\": [],\n",
915
+ "}\n",
916
+ "\n",
917
+ "HTTP_HEADERS = {\n",
918
+ " \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \"\n",
919
+ " \"(KHTML, like Gecko) Chrome/120.0 Safari/537.36\"\n",
920
+ "}\n",
921
+ "HTTP_TIMEOUT = 12\n",
922
+ "\n",
923
+ "def _best_effort_manufacturer_url(model: str, canon_make: str) -> str:\n",
924
+ " \"\"\"Try to find a manufacturer page or datasheet link using simple on-domain searches.\n",
925
+ " If we can't confirm a page, return the manufacturer homepage for the maker family.\n",
926
+ " \"\"\"\n",
927
+ " model = str(model or \"\").strip()\n",
928
+ " if not model or model in {\"Not listed\", \"Not applicable\"}:\n",
929
+ " return \"\"\n",
930
+ "\n",
931
+ " domains = MAKER_DOMAINS.get(canon_make, []) or []\n",
932
+ " if not domains:\n",
933
+ " return \"\"\n",
934
+ "\n",
935
+ " # Candidate on-domain search URLs (common patterns across sites).\n",
936
+ " # We keep these on the manufacturer domain (no Google/Bing).\n",
937
+ " q = re.sub(r\"\\s+\", \"+\", model)\n",
938
+ " url_candidates = []\n",
939
+ " for d in domains:\n",
940
+ " url_candidates += [\n",
941
+ " f\"https://{d}/search?q={q}\",\n",
942
+ " f\"https://{d}/search?query={q}\",\n",
943
+ " f\"https://{d}/?s={q}\",\n",
944
+ " f\"https://www.{d}/search?q={q}\",\n",
945
+ " f\"https://www.{d}/search?query={q}\",\n",
946
+ " f\"https://www.{d}/?s={q}\",\n",
947
+ " ]\n",
948
+ "\n",
949
+ " # Also try a few direct product patterns for known makers (best effort).\n",
950
+ " if canon_make == \"TELTONIKA\":\n",
951
+ " slug = model.lower()\n",
952
+ " url_candidates += [\n",
953
+ " f\"https://teltonika-networks.com/products/routers/{slug}\",\n",
954
+ " f\"https://teltonika-networks.com/product/{slug}\",\n",
955
+ " \"https://teltonika-networks.com/products/routers/\",\n",
956
+ " ]\n",
957
+ " if canon_make == \"DIGI\":\n",
958
+ " url_candidates += [\n",
959
+ " \"https://www.digi.com/products/networking/cellular-routers\",\n",
960
+ " f\"https://www.digi.com/search?q={q}\",\n",
961
+ " ]\n",
962
+ " if canon_make == \"CRADLEPOINT\":\n",
963
+ " url_candidates += [\n",
964
+ " \"https://cradlepoint.com/products/\",\n",
965
+ " f\"https://cradlepoint.com/?s={q}\",\n",
966
+ " ]\n",
967
+ " if canon_make in {\"CISCO\", \"CISCO_MERAKI\"}:\n",
968
+ " url_candidates += [\n",
969
+ " f\"https://www.cisco.com/c/en/us/search.html?q={q}\",\n",
970
+ " ]\n",
971
+ "\n",
972
+ " # Try to confirm a working page (HTTP 200 and model string somewhere in HTML).\n",
973
+ " for u in url_candidates[:18]:\n",
974
+ " try:\n",
975
+ " import requests\n",
976
+ " r = requests.get(u, headers=HTTP_HEADERS, timeout=HTTP_TIMEOUT, allow_redirects=True)\n",
977
+ " if r.status_code != 200:\n",
978
+ " continue\n",
979
+ " html = (r.text or \"\").lower()\n",
980
+ " if model.lower() in html or \"datasheet\" in html or \"data sheet\" in html:\n",
981
+ " return r.url\n",
982
+ " except Exception:\n",
983
+ " continue\n",
984
+ "\n",
985
+ " # Fallback: maker homepage\n",
986
+ " d0 = domains[0]\n",
987
+ " return f\"https://{d0}\"\n",
988
+ "\n",
989
+ "def _fetch_page_text(url: str, max_chars: int = 12000) -> str:\n",
990
+ " \"\"\"Fetch page HTML and return a simplified text blob for GPT (best effort).\"\"\"\n",
991
+ " if not url:\n",
992
+ " return \"\"\n",
993
+ " try:\n",
994
+ " import requests\n",
995
+ " r = requests.get(url, headers=HTTP_HEADERS, timeout=HTTP_TIMEOUT, allow_redirects=True)\n",
996
+ " if r.status_code != 200:\n",
997
+ " return \"\"\n",
998
+ " html = r.text or \"\"\n",
999
+ " html = re.sub(r\"(?is)<script.*?>.*?</script>\", \" \", html)\n",
1000
+ " html = re.sub(r\"(?is)<style.*?>.*?</style>\", \" \", html)\n",
1001
+ " text = re.sub(r\"(?is)<[^>]+>\", \" \", html)\n",
1002
+ " text = re.sub(r\"\\s+\", \" \", text).strip()\n",
1003
+ " return text[:max_chars]\n",
1004
+ " except Exception:\n",
1005
+ " return \"\"\n",
1006
+ "\n",
1007
+ "\n",
1008
+ "def _features_from_dec(model: str, canon_make: str) -> Dict[str, str]:\n",
1009
+ " \"\"\"Lookup a router model in dec2025routers.csv and return the key feature fields.\"\"\"\n",
1010
+ " if not model or model in {\"Not listed\", \"Not applicable\"}:\n",
1011
+ " return {k: \"Not listed\" for k in FEATURE_COLS[1:]}\n",
1012
+ "\n",
1013
+ " pool = df_dec[df_dec[\"_canon_make\"] == canon_make].copy()\n",
1014
+ " if pool.empty:\n",
1015
+ " return {k: \"Not listed\" for k in FEATURE_COLS[1:]}\n",
1016
+ "\n",
1017
+ " hit = process.extractOne(norm_text(model), pool[\"_norm_model\"].tolist(), scorer=fuzz.WRatio)\n",
1018
+ " if not hit or hit[1] < MATCH_OK:\n",
1019
+ " return {k: \"Not listed\" for k in FEATURE_COLS[1:]}\n",
1020
+ "\n",
1021
+ " r = pool.iloc[int(hit[2])]\n",
1022
+ " ports = f\"WAN: {r.get('WAN ports and speed','')} | LAN: {r.get('LAN ports and speed','')}\"\n",
1023
+ " return {\n",
1024
+ " \"Modem technology\": str(r.get(\"Modem Type\",\"\")) or \"Not listed\",\n",
1025
+ " \"WiFi\": str(r.get(\"WiFi type\",\"\")) or \"Not listed\",\n",
1026
+ " \"Ports\": ports.strip() if ports.strip() else \"Not listed\",\n",
1027
+ " \"Antennas\": str(r.get(\"Antennas (internal/external/both)\",\"\")) or \"Not listed\",\n",
1028
+ " \"Ruggedness\": str(r.get(\"Ruggedization\",\"\")) or \"Not listed\",\n",
1029
+ " \"Use case\": str(r.get(\"Primary use case\",\"\")) or \"Not listed\",\n",
1030
+ " }\n",
1031
+ "\n",
1032
+ "def _gpt_fill_feature_row(device_label: str, model: str, canon_make: str, row: Dict[str, str], manufacturer_url: str = \"\", page_text: str = \"\") -> Dict[str, str]:\n",
1033
+ " \"\"\"If dec can't supply values, ask GPT to fill missing ones (best guess).\"\"\"\n",
1034
+ " if client is None:\n",
1035
+ " return row\n",
1036
+ "\n",
1037
+ " missing = [k for k,v in row.items() if (not v) or str(v).strip().lower() in {\"not listed\",\"nan\",\"\"}]\n",
1038
+ " if not missing:\n",
1039
+ " return row\n",
1040
+ "\n",
1041
+ " sys = (\n",
1042
+ " \"Fill missing router feature fields for a Verizon rep. Return strict JSON only. \"\n",
1043
+ " \"Use manufacturer page text when available. If still unknown, make a best-guess.\"\n",
1044
+ " )\n",
1045
+ " payload = {\n",
1046
+ " \"device_label\": device_label,\n",
1047
+ " \"model\": model,\n",
1048
+ " \"maker_family\": canon_make,\n",
1049
+ " \"manufacturer_url\": manufacturer_url,\n",
1050
+ " \"manufacturer_page_text\": page_text[:8000],\n",
1051
+ " \"known\": row,\n",
1052
+ " \"fill_only\": missing,\n",
1053
+ " \"rules\": [\"Fill only requested fields.\", \"Short phrases only.\", \"Return JSON only.\"],\n",
1054
+ " \"output_schema\": {k: \"string\" for k in missing},\n",
1055
+ " }\n",
1056
+ " out = gpt_json(sys, payload, max_tokens=320) or {}\n",
1057
+ " for k in missing:\n",
1058
+ " val = str(out.get(k, \"\") or \"\").strip()\n",
1059
+ " if val:\n",
1060
+ " row[k] = val\n",
1061
+ " return row\n",
1062
+ " missing = [k for k,v in row.items() if (not v) or str(v).strip().lower() in {\"not listed\",\"nan\",\"\"}]\n",
1063
+ " if not missing:\n",
1064
+ " return row\n",
1065
+ "\n",
1066
+ " sys = \"Fill missing router feature fields for a Verizon rep. Return strict JSON only.\"\n",
1067
+ " payload = {\n",
1068
+ " \"device_label\": device_label,\n",
1069
+ " \"model\": model,\n",
1070
+ " \"maker_family\": canon_make,\n",
1071
+ " \"known\": row,\n",
1072
+ " \"fill_only\": missing,\n",
1073
+ " \"rules\": [\n",
1074
+ " \"Fill only the requested fields.\",\n",
1075
+ " \"Best guess if needed. Short phrases only.\",\n",
1076
+ " \"Return JSON only.\"\n",
1077
+ " ],\n",
1078
+ " \"output_schema\": {k: \"string\" for k in missing}\n",
1079
+ " }\n",
1080
+ " out = gpt_json(sys, payload, max_tokens=260) or {}\n",
1081
+ " for k in missing:\n",
1082
+ " val = str(out.get(k, \"\") or \"\").strip()\n",
1083
+ " if val:\n",
1084
+ " row[k] = val\n",
1085
+ " return row\n",
1086
+ "\n",
1087
+ "def build_replacement_features_table(repl_4g: str, repl_5g: str, canon_make: str) -> pd.DataFrame:\n",
1088
+ " rows = []\n",
1089
+ "\n",
1090
+ " # 4G alternative row\n",
1091
+ " row4 = _features_from_dec(repl_4g, canon_make)\n",
1092
+ " url4 = _best_effort_manufacturer_url(repl_4g, canon_make) if repl_4g else \"\"\n",
1093
+ " txt4 = _fetch_page_text(url4) if url4 else \"\"\n",
1094
+ " row4 = _gpt_fill_feature_row(\"4G alternative\", repl_4g, canon_make, row4, manufacturer_url=url4, page_text=txt4)\n",
1095
+ " rows.append({\"Device\": \"4G alternative\", **row4})\n",
1096
+ "\n",
1097
+ " # 5G replacement row\n",
1098
+ " row5 = _features_from_dec(repl_5g, canon_make)\n",
1099
+ " url5 = _best_effort_manufacturer_url(repl_5g, canon_make) if repl_5g else \"\"\n",
1100
+ " txt5 = _fetch_page_text(url5) if url5 else \"\"\n",
1101
+ " row5 = _gpt_fill_feature_row(\"5G replacement\", repl_5g, canon_make, row5, manufacturer_url=url5, page_text=txt5)\n",
1102
+ " rows.append({\"Device\": \"5G replacement\", **row5})\n",
1103
+ "\n",
1104
+ " df = pd.DataFrame(rows, columns=FEATURE_COLS)\n",
1105
+ " return df\n",
1106
+ "# ============================\n",
1107
+ "# Verizon fit badges (small table) for recommended devices\n",
1108
+ "# ============================\n",
1109
+ "\n",
1110
+ "FIT_COLS = [\"Device\", \"Fit badges\", \"Ethernet ports\", \"Battery\"]\n",
1111
+ "\n",
1112
+ "def _parse_ethernet_ports(wan_field: str, lan_field: str) -> str:\n",
1113
+ " \"\"\"Best-effort total ethernet ports based on WAN/LAN text.\"\"\"\n",
1114
+ " def _count(field: str) -> int:\n",
1115
+ " s = str(field or \"\")\n",
1116
+ " # Common forms: \"1x GbE\", \"2 x 10/100\", \"WAN: 1\", etc.\n",
1117
+ " nums = [int(x) for x in re.findall(r\"(\\\\d+)\\\\s*x\", s.lower())]\n",
1118
+ " if nums:\n",
1119
+ " return sum(nums)\n",
1120
+ " # Fallback: if it contains 'port' with a number\n",
1121
+ " m = re.search(r\"(\\\\d+)\\\\s*port\", s.lower())\n",
1122
+ " if m:\n",
1123
+ " return int(m.group(1))\n",
1124
+ " # If it contains '1' and 'wan' in short text, guess 1\n",
1125
+ " if \"wan\" in s.lower() and re.search(r\"\\\\b1\\\\b\", s):\n",
1126
+ " return 1\n",
1127
+ " return 0\n",
1128
+ "\n",
1129
+ " total = _count(wan_field) + _count(lan_field)\n",
1130
+ " return str(total) if total > 0 else \"Not listed\"\n",
1131
+ "\n",
1132
+ "def _battery_badge(battery_field: str) -> str:\n",
1133
+ " s = str(battery_field or \"\").strip().lower()\n",
1134
+ " if not s or s in {\"none\", \"no\", \"n/a\", \"not listed\"}:\n",
1135
+ " return \"No\"\n",
1136
+ " return \"Yes\"\n",
1137
+ "\n",
1138
+ "def _bool_badge(flag: bool) -> str:\n",
1139
+ " return \"Yes\" if flag else \"No\"\n",
1140
+ "\n",
1141
+ "def _dual_sim_from_row_text(*fields: str) -> bool:\n",
1142
+ " txt = \" \".join([str(x or \"\") for x in fields]).lower()\n",
1143
+ " return (\"dual sim\" in txt) or (\"2 sim\" in txt) or (\"two sim\" in txt) or (\"dual-sim\" in txt)\n",
1144
+ "\n",
1145
+ "def _throughput_high(throughput_field: str) -> bool:\n",
1146
+ " t = str(throughput_field or \"\").lower()\n",
1147
+ " # Heuristic: anything mentioning gbps or >=1000 mbps\n",
1148
+ " if \"gbps\" in t:\n",
1149
+ " return True\n",
1150
+ " m = re.search(r\"(\\\\d+(?:\\\\.\\\\d+)?)\\\\s*mbps\", t)\n",
1151
+ " if m:\n",
1152
+ " try:\n",
1153
+ " return float(m.group(1)) >= 1000.0\n",
1154
+ " except Exception:\n",
1155
+ " pass\n",
1156
+ " return False\n",
1157
+ "\n",
1158
+ "def _gpt_fit_badges(model: str, canon_make: str, is_5g: bool, dec_row: Optional[pd.Series]) -> Tuple[str, str, str]:\n",
1159
+ " \"\"\"\n",
1160
+ " GPT-based fill for Fit badges / Ethernet ports / Battery, used when dec is missing or incomplete.\n",
1161
+ " Returns (badges_csv, ethernet_ports, battery_yesno).\n",
1162
+ " \"\"\"\n",
1163
+ " if client is None:\n",
1164
+ " return (\"Not listed\", \"Not listed\", \"Not listed\")\n",
1165
+ "\n",
1166
+ " dec_ctx = {}\n",
1167
+ " if dec_row is not None:\n",
1168
+ " try:\n",
1169
+ " dec_ctx = {\n",
1170
+ " \"Model\": str(dec_row.get(\"Model\",\"\")),\n",
1171
+ " \"Modem Type\": str(dec_row.get(\"Modem Type\",\"\")),\n",
1172
+ " \"Ruggedization\": str(dec_row.get(\"Ruggedization\",\"\")),\n",
1173
+ " \"WAN ports and speed\": str(dec_row.get(\"WAN ports and speed\",\"\")),\n",
1174
+ " \"LAN ports and speed\": str(dec_row.get(\"LAN ports and speed\",\"\")),\n",
1175
+ " \"Antennas\": str(dec_row.get(\"Antennas (internal/external/both)\",\"\")),\n",
1176
+ " \"WiFi type\": str(dec_row.get(\"WiFi type\",\"\")),\n",
1177
+ " \"Primary use case\": str(dec_row.get(\"Primary use case\",\"\")),\n",
1178
+ " \"Serial port\": str(dec_row.get(\"Serial port (yes/no)\",\"\")),\n",
1179
+ " \"VPN\": str(dec_row.get(\"VPN capabilities\",\"\")),\n",
1180
+ " \"Throughput\": str(dec_row.get(\"Router throughput\",\"\")),\n",
1181
+ " \"Battery\": str(dec_row.get(\"Battery (internal/removable/none/optional)\",\"\")),\n",
1182
+ " \"Special notes\": str(dec_row.get(\"Special notes\",\"\")),\n",
1183
+ " \"Summary\": str(dec_row.get(\"summary and use case\",\"\")),\n",
1184
+ " }\n",
1185
+ " except Exception:\n",
1186
+ " dec_ctx = {}\n",
1187
+ "\n",
1188
+ " sys = (\n",
1189
+ " \"You are helping a Verizon rep. Based on the provided router context, output fit badges and a couple quick traits.\\n\"\n",
1190
+ " \"Return STRICT JSON only.\\n\"\n",
1191
+ " \"Badges must be chosen from this set only:\\n\"\n",
1192
+ " \"['Vehicle','Fixed site','Wi‑Fi','Rugged','Dual‑SIM','4x4 MIMO','High throughput','Serial'].\\n\"\n",
1193
+ " \"Rules:\\n\"\n",
1194
+ " \"- If is_5g is true, ALWAYS include '4x4 MIMO'.\\n\"\n",
1195
+ " \"- Ethernet ports: return a single integer as a string if you can infer total ethernet ports, otherwise 'Not listed'.\\n\"\n",
1196
+ " \"- Battery: return 'Yes' or 'No' if you can infer, otherwise 'Not listed'.\\n\"\n",
1197
+ " \"- If uncertain between Vehicle vs Fixed site, pick the most likely based on use case/ruggedization.\\n\"\n",
1198
+ " )\n",
1199
+ "\n",
1200
+ " payload = {\n",
1201
+ " \"model\": model,\n",
1202
+ " \"maker_family\": canon_make,\n",
1203
+ " \"is_5g\": bool(is_5g),\n",
1204
+ " \"dec_context\": dec_ctx,\n",
1205
+ " \"output_schema\": {\n",
1206
+ " \"badges\": [\"string\"],\n",
1207
+ " \"ethernet_ports\": \"string\",\n",
1208
+ " \"battery\": \"Yes|No|Not listed\"\n",
1209
+ " }\n",
1210
+ " }\n",
1211
+ "\n",
1212
+ " out = gpt_json(sys, payload, max_tokens=260) or {}\n",
1213
+ "\n",
1214
+ " badges = out.get(\"badges\", []) or []\n",
1215
+ " allowed = {\"Vehicle\",\"Fixed site\",\"Wi‑Fi\",\"Rugged\",\"Dual‑SIM\",\"4x4 MIMO\",\"High throughput\",\"Serial\"}\n",
1216
+ " clean = []\n",
1217
+ " for b in badges:\n",
1218
+ " bs = str(b).strip()\n",
1219
+ " if bs in allowed:\n",
1220
+ " clean.append(bs)\n",
1221
+ "\n",
1222
+ " if is_5g and \"4x4 MIMO\" not in clean:\n",
1223
+ " clean.append(\"4x4 MIMO\")\n",
1224
+ "\n",
1225
+ " eth = str(out.get(\"ethernet_ports\",\"\") or \"\").strip()\n",
1226
+ " if not eth or eth.lower() in {\"nan\",\"none\"}:\n",
1227
+ " eth = \"Not listed\"\n",
1228
+ " m = re.search(r\"\\d+\", eth)\n",
1229
+ " eth = m.group(0) if m else (\"Not listed\" if eth == \"Not listed\" else eth)\n",
1230
+ "\n",
1231
+ " bat = str(out.get(\"battery\",\"\") or \"\").strip()\n",
1232
+ " if not bat:\n",
1233
+ " bat = \"Not listed\"\n",
1234
+ " if bat.lower().startswith(\"y\"):\n",
1235
+ " bat = \"Yes\"\n",
1236
+ " elif bat.lower().startswith(\"n\"):\n",
1237
+ " bat = \"No\"\n",
1238
+ " elif bat not in {\"Yes\",\"No\",\"Not listed\"}:\n",
1239
+ " bat = \"Not listed\"\n",
1240
+ "\n",
1241
+ " dedup=[]\n",
1242
+ " seen=set()\n",
1243
+ " for b in clean:\n",
1244
+ " if b not in seen:\n",
1245
+ " seen.add(b); dedup.append(b)\n",
1246
+ " badges_csv = \", \".join(dedup) if dedup else \"Not listed\"\n",
1247
+ " return (badges_csv, eth, bat)\n",
1248
+ "\n",
1249
+ "\n",
1250
+ "def _fit_badges_for_model(model: str, canon_make: str, is_5g: bool) -> Tuple[str, str, str]:\n",
1251
+ " \"\"\"Return (badges_csv, ethernet_ports, battery_yesno). Uses dec2025routers.csv first, then GPT fill.\"\"\"\n",
1252
+ " model = str(model or \"\").strip()\n",
1253
+ " if not model or model in {\"Not listed\", \"Not applicable\"}:\n",
1254
+ " return (\"Not listed\", \"Not listed\", \"Not listed\")\n",
1255
+ "\n",
1256
+ " pool = df_dec[df_dec[\"_canon_make\"] == canon_make].copy()\n",
1257
+ " row = None\n",
1258
+ " if not pool.empty:\n",
1259
+ " hit = process.extractOne(norm_text(model), pool[\"_norm_model\"].tolist(), scorer=fuzz.WRatio)\n",
1260
+ " if hit and hit[1] >= MATCH_OK:\n",
1261
+ " row = pool.iloc[int(hit[2])]\n",
1262
+ "\n",
1263
+ " badges = []\n",
1264
+ " eth = \"Not listed\"\n",
1265
+ " bat_yes = \"Not listed\"\n",
1266
+ "\n",
1267
+ " if row is not None:\n",
1268
+ " use_case = str(row.get(\"Primary use case\",\"\") or \"\").lower()\n",
1269
+ " rugged = str(row.get(\"Ruggedization\",\"\") or \"\").lower()\n",
1270
+ "\n",
1271
+ " if any(k in use_case for k in [\"vehicle\",\"mobile\",\"fleet\",\"in-vehicle\"]) or \"vehicle\" in rugged:\n",
1272
+ " badges.append(\"Vehicle\")\n",
1273
+ " else:\n",
1274
+ " badges.append(\"Fixed site\")\n",
1275
+ "\n",
1276
+ " wifi = str(row.get(\"WiFi type\",\"\") or \"\").strip()\n",
1277
+ " if wifi and wifi.lower() not in {\"none\",\"no\",\"n/a\"}:\n",
1278
+ " badges.append(\"Wi‑Fi\")\n",
1279
+ "\n",
1280
+ " if any(k in rugged for k in [\"rugged\",\"industrial\",\"ip\",\"harsh\"]):\n",
1281
+ " badges.append(\"Rugged\")\n",
1282
+ "\n",
1283
+ " notes_blob = \" \".join([\n",
1284
+ " str(row.get(\"Special notes\",\"\") or \"\"),\n",
1285
+ " str(row.get(\"summary and use case\",\"\") or \"\"),\n",
1286
+ " ]).lower()\n",
1287
+ " if \"dual\" in notes_blob and \"sim\" in notes_blob:\n",
1288
+ " badges.append(\"Dual‑SIM\")\n",
1289
+ "\n",
1290
+ " if is_5g:\n",
1291
+ " badges.append(\"4x4 MIMO\")\n",
1292
+ "\n",
1293
+ " thr = str(row.get(\"Router throughput\",\"\") or \"\").lower()\n",
1294
+ " m = re.search(r\"(\\d+(\\.\\d+)?)\\s*gb\", thr)\n",
1295
+ " if m:\n",
1296
+ " try:\n",
1297
+ " if float(m.group(1)) >= 1.0:\n",
1298
+ " badges.append(\"High throughput\")\n",
1299
+ " except Exception:\n",
1300
+ " pass\n",
1301
+ "\n",
1302
+ " serial = str(row.get(\"Serial port (yes/no)\",\"\") or \"\").strip().lower()\n",
1303
+ " if serial in {\"yes\",\"y\",\"true\"}:\n",
1304
+ " badges.append(\"Serial\")\n",
1305
+ "\n",
1306
+ " wan = str(row.get(\"WAN ports and speed\",\"\") or \"\")\n",
1307
+ " lan = str(row.get(\"LAN ports and speed\",\"\") or \"\")\n",
1308
+ " m1 = re.search(r\"(\\d+)\\s*x\", wan.lower())\n",
1309
+ " m2 = re.search(r\"(\\d+)\\s*x\", lan.lower())\n",
1310
+ " if m1 or m2:\n",
1311
+ " total = (int(m1.group(1)) if m1 else 0) + (int(m2.group(1)) if m2 else 0)\n",
1312
+ " eth = str(total) if total > 0 else \"Not listed\"\n",
1313
+ "\n",
1314
+ " bat = str(row.get(\"Battery (internal/removable/none/optional)\",\"\") or \"\")\n",
1315
+ " bat_l = bat.lower().strip()\n",
1316
+ " if bat_l:\n",
1317
+ " if \"none\" in bat_l:\n",
1318
+ " bat_yes = \"No\"\n",
1319
+ " else:\n",
1320
+ " bat_yes = \"Yes\"\n",
1321
+ "\n",
1322
+ " # Use GPT when anything is missing (instead of best-effort inference)\n",
1323
+ " if (row is None) or (eth == \"Not listed\") or (bat_yes == \"Not listed\") or (not badges):\n",
1324
+ " g_badges, g_eth, g_bat = _gpt_fit_badges(model, canon_make, is_5g, row)\n",
1325
+ "\n",
1326
+ " if badges:\n",
1327
+ " if is_5g and \"4x4 MIMO\" not in badges:\n",
1328
+ " badges.append(\"4x4 MIMO\")\n",
1329
+ " dedup=[]\n",
1330
+ " seen=set()\n",
1331
+ " for b in badges:\n",
1332
+ " if b not in seen:\n",
1333
+ " seen.add(b); dedup.append(b)\n",
1334
+ " badges_csv = \", \".join(dedup)\n",
1335
+ " else:\n",
1336
+ " badges_csv = g_badges\n",
1337
+ "\n",
1338
+ " eth = eth if eth != \"Not listed\" else g_eth\n",
1339
+ " bat_yes = bat_yes if bat_yes != \"Not listed\" else g_bat\n",
1340
+ " return (badges_csv or \"Not listed\", eth or \"Not listed\", bat_yes or \"Not listed\")\n",
1341
+ "\n",
1342
+ " dedup=[]\n",
1343
+ " seen=set()\n",
1344
+ " for b in badges:\n",
1345
+ " if b not in seen:\n",
1346
+ " seen.add(b); dedup.append(b)\n",
1347
+ " badges_csv = \", \".join(dedup) if dedup else \"Not listed\"\n",
1348
+ " return (badges_csv, eth, bat_yes)\n",
1349
+ "\n",
1350
+ "def build_fit_table(repl_4g: str, repl_5g: str, canon_make: str) -> pd.DataFrame:\n",
1351
+ " rows = []\n",
1352
+ " # 4G alt row (is_5g False)\n",
1353
+ " b4, eth4, bat4 = _fit_badges_for_model(repl_4g, canon_make, is_5g=False)\n",
1354
+ " rows.append({\"Device\": \"4G alternative\", \"Fit badges\": b4, \"Ethernet ports\": eth4, \"Battery\": bat4})\n",
1355
+ " # 5G row (is_5g True)\n",
1356
+ " b5, eth5, bat5 = _fit_badges_for_model(repl_5g, canon_make, is_5g=True)\n",
1357
+ " rows.append({\"Device\": \"5G replacement\", \"Fit badges\": b5, \"Ethernet ports\": eth5, \"Battery\": bat5})\n",
1358
+ " return pd.DataFrame(rows, columns=FIT_COLS)\n",
1359
+ "\n",
1360
+ "# ============================\n",
1361
+ "# Output\n",
1362
+ "# ============================\n",
1363
+ "def assemble_output(life_row: pd.Series, status: str, eos: str, eol: str, repl: Dict[str,Any], ant: Dict[str,Any]) -> str:\n",
1364
+ " current_name = f\"{life_row.get('sku','')} — {life_row.get('description','')}\".strip(\" —\")\n",
1365
+ " st = ant.get(\"stationary_omni\", {})\n",
1366
+ " vh = ant.get(\"vehicle_omni\", {})\n",
1367
+ "\n",
1368
+ " lines = []\n",
1369
+ " lines.append(f\"1. Current device: **{current_name}**\")\n",
1370
+ " lines.append(f\"2. Status: **{status}**\")\n",
1371
+ " lines.append(f\"3. End of Sale date: **{eos}**\")\n",
1372
+ " lines.append(f\"4. End of Life date: **{eol}**\")\n",
1373
+ " lines.append(f\"5. 4G alternative (lifecycle): **{repl.get('repl_4g','Not applicable')}**\")\n",
1374
+ " lines.append(f\"6. 5G replacement (lifecycle): **{repl.get('repl_5g','Not listed')}**\")\n",
1375
+ " lines.append(\"7. Antenna options (Parsec-only):\")\n",
1376
+ " conn_s = f\" | Conn: {st.get('connectors','')}\" if st.get(\"connectors\") else \"\"\n",
1377
+ " conn_v = f\" | Conn: {vh.get('connectors','')}\" if vh.get(\"connectors\") else \"\"\n",
1378
+ " lines.append(f\" - Stationary (Omni): **{st.get('name','')}** (Part #: {st.get('part_number','')}) — {st.get('description','')} — MIMO: {st.get('mimo','')}{conn_s}\")\n",
1379
+ " lines.append(f\" - Vehicle (Omni): **{vh.get('name','')}** (Part #: {vh.get('part_number','')}) — {vh.get('description','')} — MIMO: {vh.get('mimo','')}{conn_v}\")\n",
1380
+ "\n",
1381
+ " lines.append(\"\\nSources (debug):\")\n",
1382
+ " for s in repl.get(\"sources\", []) if isinstance(repl.get(\"sources\"), list) else []:\n",
1383
+ " lines.append(f\"- {s}\")\n",
1384
+ " lines.append(\"- ParsecCatalog.pdf (local RAG)\")\n",
1385
+ " lines.append(\"- routers_eos_eol_by_sku.csv (replacements)\")\n",
1386
+ " return \"\\n\".join(lines)\n",
1387
+ "\n",
1388
+ "\n",
1389
+ "# ============================\n",
1390
+ "# Customer-ready email summary (single lookup only)\n",
1391
+ "# ============================\n",
1392
+ "\n",
1393
+ "def build_customer_email(life_row: pd.Series, status: str, eos: str, eol: str, repl: Dict[str,Any], ant: Dict[str,Any], link5: str) -> str:\n",
1394
+ " \"\"\"Email-style summary the rep can paste to a customer (lightly sales-y).\"\"\"\n",
1395
+ " current = f\"{life_row.get('sku','')} — {life_row.get('description','')}\".strip(\" —\")\n",
1396
+ " repl5 = str(repl.get(\"repl_5g\",\"\") or \"\").strip()\n",
1397
+ " repl4 = str(repl.get(\"repl_4g\",\"\") or \"\").strip()\n",
1398
+ "\n",
1399
+ " st = ant.get(\"stationary_omni\", {}) or {}\n",
1400
+ " vh = ant.get(\"vehicle_omni\", {}) or {}\n",
1401
+ "\n",
1402
+ " lines = []\n",
1403
+ " lines.append(\"Subject: Router replacement recommendation\")\n",
1404
+ " lines.append(\"\")\n",
1405
+ " lines.append(\"Hi there,\")\n",
1406
+ " lines.append(\"\")\n",
1407
+ " lines.append(f\"We reviewed your current router (**{current}**) and recommend the following path forward:\")\n",
1408
+ " lines.append(\"\")\n",
1409
+ " lines.append(f\"- **Status:** {status}\")\n",
1410
+ " lines.append(f\"- **End of Sale:** {eos}\")\n",
1411
+ " lines.append(f\"- **End of Life:** {eol}\")\n",
1412
+ " lines.append(\"\")\n",
1413
+ " lines.append(\"**Recommended replacement (5G):**\")\n",
1414
+ " lines.append(f\"- {repl5 if repl5 else 'Not listed'}\")\n",
1415
+ " if link5:\n",
1416
+ " lines.append(f\"- Manufacturer page (best effort): {link5}\")\n",
1417
+ " lines.append(\"\")\n",
1418
+ " lines.append(\"**Optional 4G alternative (if needed):**\")\n",
1419
+ " lines.append(f\"- {repl4 if repl4 and repl4.lower() != 'not applicable' else 'Not applicable'}\")\n",
1420
+ " lines.append(\"\")\n",
1421
+ " lines.append(\"**Antenna suggestions (Parsec):**\")\n",
1422
+ " lines.append(f\"- Stationary (Omni): {st.get('name','')} (PN {st.get('part_number','')})\")\n",
1423
+ " lines.append(f\"- Vehicle (Omni): {vh.get('name','')} (PN {vh.get('part_number','')})\")\n",
1424
+ " lines.append(\"\")\n",
1425
+ " lines.append(\"If you’d like, we can confirm the best-fit option for your install environment and provide pricing.\")\n",
1426
+ " lines.append(\"\")\n",
1427
+ " lines.append(\"Contact Peter Dunn @ 786.999.9127 or peter.dunn@masterstelecom.com for pricing.\")\n",
1428
+ " lines.append(\"\")\n",
1429
+ " lines.append(\"Thanks,\")\n",
1430
+ " lines.append(\"Peter Dunn\")\n",
1431
+ " return \"\\n\".join(lines)\n",
1432
+ "\n",
1433
+ "def generate_customer_email(st_json: str) -> str:\n",
1434
+ " st = state_load(st_json)\n",
1435
+ " if not st or \"row_idx\" not in st:\n",
1436
+ " return \"Run a lookup first.\"\n",
1437
+ " try:\n",
1438
+ " life_row = df_eos.iloc[int(st[\"row_idx\"])]\n",
1439
+ " except Exception:\n",
1440
+ " return \"Run a lookup first.\"\n",
1441
+ "\n",
1442
+ " eos, eol, status = row_to_dates_and_status(life_row)\n",
1443
+ " repl = st.get(\"repl\", {}) or {}\n",
1444
+ " ant = st.get(\"ant\", {}) or {}\n",
1445
+ "\n",
1446
+ " canon_make = str(life_row.get(\"_canon_make\",\"UNKNOWN\"))\n",
1447
+ " url5 = _best_effort_manufacturer_url(str(repl.get(\"repl_5g\",\"\") or \"\"), canon_make)\n",
1448
+ " return build_customer_email(life_row, status, eos, eol, repl, ant, url5)\n",
1449
+ "\n",
1450
+ "# ============================\n",
1451
+ "# Gradio callbacks\n",
1452
+ "# IMPORTANT: no dict state and ALL events have api_name=False (prevents api_info schema generation)\n",
1453
+ "# ============================\n",
1454
+ "def run_lookup(user_text: str, st_json: str):\n",
1455
+ " user_text = str(user_text or \"\").strip()\n",
1456
+ " if not user_text:\n",
1457
+ " return \"Enter a router SKU/model.\", \"\", None, None, \"\", gr.update(visible=False), gr.update(visible=False), \"{}\", \"\", \"\"\n",
1458
+ "\n",
1459
+ " res = resolve_device(user_text)\n",
1460
+ "\n",
1461
+ " if res.get(\"mode\") == \"pick\":\n",
1462
+ " opts = res.get(\"options\", [])\n",
1463
+ " choices = [o[\"label\"] for o in opts]\n",
1464
+ " st2 = {\"mode\":\"pick\",\"options\": opts, \"raw\": user_text}\n",
1465
+ " return \"Did you mean A or B? Pick one, then click Use selection.\", \"\", None, None, \"\", gr.update(choices=choices, value=None, visible=True), gr.update(visible=True), state_dump(st2), \"\", \"\"\n",
1466
+ "\n",
1467
+ " if res.get(\"mode\") != \"ok\":\n",
1468
+ " return \"Not found.\", \"\", None, None, \"\", gr.update(visible=False), gr.update(visible=False), \"{}\", \"\", \"\"\n",
1469
+ "\n",
1470
+ " life_row = df_eos.iloc[int(res[\"row_idx\"])]\n",
1471
+ " eos, eol, status = row_to_dates_and_status(life_row)\n",
1472
+ "\n",
1473
+ " repl = pick_replacements_lifecycle(life_row, status, use_gpt=True)\n",
1474
+ " canon_make = str(life_row.get(\"_canon_make\",\"UNKNOWN\"))\n",
1475
+ " mimo = infer_mimo_for_5g(repl.get(\"repl_5g\",\"\"))\n",
1476
+ " tech = \"5G\" if repl.get(\"repl_5g\") and repl.get(\"repl_5g\") != \"Not listed\" else (\"4G\" if device_is_4g(life_row) else \"Unknown\")\n",
1477
+ " ant = antenna_options_for(repl.get(\"repl_5g\") or str(life_row.get(\"sku\",\"\")), tech, mimo)\n",
1478
+ "\n",
1479
+ " output = assemble_output(life_row, status, eos, eol, repl, ant)\n",
1480
+ " st_out = {\"row_idx\": int(res[\"row_idx\"]), \"repl\": repl, \"ant\": ant, \"raw\": user_text}\n",
1481
+ " url5 = _best_effort_manufacturer_url(repl.get('repl_5g',''), canon_make)\n",
1482
+ " link = f\"**5G manufacturer page (best effort):** {url5}\" if url5 else \"\"\n",
1483
+ " feat_df = build_replacement_features_table(repl.get('repl_4g',''), repl.get('repl_5g',''), canon_make)\n",
1484
+ " fit = build_fit_table(repl.get('repl_4g',''), repl.get('repl_5g',''), canon_make)\n",
1485
+ " return output, link, feat_df, fit, \"\", gr.update(visible=False), gr.update(visible=False), state_dump(st_out), \"\", \"\"\n",
1486
+ "\n",
1487
+ "def use_selection(selected_label: str, st_json: str):\n",
1488
+ " st = state_load(st_json)\n",
1489
+ " if not st or st.get(\"mode\") != \"pick\":\n",
1490
+ " return \"Run a search first.\", \"\", None, None, \"\", gr.update(visible=False), gr.update(visible=False), \"{}\", \"\", \"\"\n",
1491
+ "\n",
1492
+ " if not selected_label:\n",
1493
+ " return \"Pick A or B first.\", \"\", None, None, \"\", gr.update(visible=True), gr.update(visible=True), st_json, \"\", \"\"\n",
1494
+ "\n",
1495
+ " chosen_row = None\n",
1496
+ " for o in st.get(\"options\", []):\n",
1497
+ " if o.get(\"label\") == selected_label:\n",
1498
+ " chosen_row = int(o[\"row_idx\"])\n",
1499
+ " break\n",
1500
+ " if chosen_row is None:\n",
1501
+ " return \"Pick a valid option.\", \"\", None, None, \"\", gr.update(visible=True), gr.update(visible=True), st_json, \"\", \"\"\n",
1502
+ "\n",
1503
+ " life_row = df_eos.iloc[int(chosen_row)]\n",
1504
+ " eos, eol, status = row_to_dates_and_status(life_row)\n",
1505
+ "\n",
1506
+ " repl = pick_replacements_lifecycle(life_row, status, use_gpt=True)\n",
1507
+ " canon_make = str(life_row.get(\"_canon_make\",\"UNKNOWN\"))\n",
1508
+ " mimo = infer_mimo_for_5g(repl.get(\"repl_5g\",\"\"))\n",
1509
+ " tech = \"5G\" if repl.get(\"repl_5g\") and repl.get(\"repl_5g\") != \"Not listed\" else (\"4G\" if device_is_4g(life_row) else \"Unknown\")\n",
1510
+ " ant = antenna_options_for(repl.get(\"repl_5g\") or str(life_row.get(\"sku\",\"\")), tech, mimo)\n",
1511
+ "\n",
1512
+ " output = assemble_output(life_row, status, eos, eol, repl, ant)\n",
1513
+ " st_out = {\"row_idx\": int(chosen_row), \"repl\": repl, \"ant\": ant, \"raw\": st.get(\"raw\",\"\")}\n",
1514
+ " url5 = _best_effort_manufacturer_url(repl.get('repl_5g',''), canon_make)\n",
1515
+ " link = f\"**5G manufacturer page (best effort):** {url5}\" if url5 else \"\"\n",
1516
+ " feat_df = build_replacement_features_table(repl.get('repl_4g',''), repl.get('repl_5g',''), canon_make)\n",
1517
+ " fit = build_fit_table(repl.get('repl_4g',''), repl.get('repl_5g',''), canon_make)\n",
1518
+ " return output, link, feat_df, fit, \"\", gr.update(visible=False), gr.update(visible=False), state_dump(st_out), \"\", \"\"\n",
1519
+ "\n",
1520
+ "def make_install_ready(st_json: str):\n",
1521
+ " st = state_load(st_json)\n",
1522
+ " if not st or \"row_idx\" not in st:\n",
1523
+ " return \"Run a lookup first.\"\n",
1524
+ " life_row = df_eos.iloc[int(st[\"row_idx\"])]\n",
1525
+ " current_sku = str(life_row.get(\"sku\",\"\") or \"\")\n",
1526
+ " return install_ready_checklist(current_sku, st.get(\"repl\", {}) or {}, st.get(\"ant\", {}) or {})\n",
1527
+ "\n",
1528
+ "\n",
1529
+ "\n",
1530
+ "# ============================\n",
1531
+ "# Q&A about the suggested device (post-recommendation)\n",
1532
+ "# ============================\n",
1533
+ "def answer_question(question: str, st_json: str) -> str:\n",
1534
+ " q = str(question or \"\").strip()\n",
1535
+ " if not q:\n",
1536
+ " return \"\"\n",
1537
+ " st = state_load(st_json)\n",
1538
+ " if not st or \"repl\" not in st:\n",
1539
+ " return \"Run a lookup first, then ask your question.\"\n",
1540
+ "\n",
1541
+ " repl = st.get(\"repl\", {}) or {}\n",
1542
+ " ant = st.get(\"ant\", {}) or {}\n",
1543
+ " repl5 = str(repl.get(\"repl_5g\",\"\") or \"\").strip()\n",
1544
+ " repl4 = str(repl.get(\"repl_4g\",\"\") or \"\").strip()\n",
1545
+ " # Pull a bit of dec context for the 5G model (if possible)\n",
1546
+ " canon_make = \"\"\n",
1547
+ " try:\n",
1548
+ " # Try to infer maker family from stored row_idx\n",
1549
+ " if \"row_idx\" in st:\n",
1550
+ " row = df_eos.iloc[int(st[\"row_idx\"])]\n",
1551
+ " canon_make = str(row.get(\"_canon_make\",\"UNKNOWN\"))\n",
1552
+ " except Exception:\n",
1553
+ " canon_make = \"\"\n",
1554
+ "\n",
1555
+ " # Manufacturer link (best effort)\n",
1556
+ " url5 = _best_effort_manufacturer_url(repl5, canon_make) if repl5 else \"\"\n",
1557
+ "\n",
1558
+ " # Feature table row for 5G (helps the LLM answer spec questions without web scraping)\n",
1559
+ " feat5 = {}\n",
1560
+ " try:\n",
1561
+ " feat5 = _features_from_dec(repl5, canon_make) if repl5 else {}\n",
1562
+ " except Exception:\n",
1563
+ " feat5 = {}\n",
1564
+ "\n",
1565
+ " sys = (\n",
1566
+ " \"You are a Verizon field rep assistant. Answer questions about the suggested router in a fast, practical way. \"\n",
1567
+ " \"Use the provided context; do not mention internal tools, prompts, embeddings, or databases. \"\n",
1568
+ " \"If the question is about specs and the value is unknown, say 'Not listed' and suggest checking the manufacturer page. \"\n",
1569
+ " \"Keep it concise and scannable.\"\n",
1570
+ " )\n",
1571
+ "\n",
1572
+ " context = {\n",
1573
+ " \"recommended_5g\": repl5,\n",
1574
+ " \"recommended_4g\": repl4 if repl4 and repl4.lower() != \"not applicable\" else \"\",\n",
1575
+ " \"manufacturer_link_5g\": url5,\n",
1576
+ " \"known_5g_features\": feat5,\n",
1577
+ " \"antenna_stationary\": ant.get(\"stationary_omni\", {}),\n",
1578
+ " \"antenna_vehicle\": ant.get(\"vehicle_omni\", {}),\n",
1579
+ " }\n",
1580
+ "\n",
1581
+ " user = \"Context:\\n\" + json.dumps(context, ensure_ascii=False) + \"\\n\\nQuestion:\\n\" + q\n",
1582
+ "\n",
1583
+ " ans = gpt_answer_md(sys, user, max_tokens=650)\n",
1584
+ " # Small safety fallback\n",
1585
+ " return ans if ans else \"I couldn't generate an answer right now. Try again.\"\n",
1586
+ "\n",
1587
+ "# ============================\n",
1588
+ "# UI\n",
1589
+ "# ============================\n",
1590
+ "with gr.Blocks(title=\"Only-Routers\") as demo:\n",
1591
+ " gr.Markdown(\"## Only-Routers\\nSingle lookup + Batch upload for Verizon reps.\")\n",
1592
+ "\n",
1593
+ " with gr.Tabs():\n",
1594
+ " with gr.Tab(\"Single\"):\n",
1595
+ " # Inputs\n",
1596
+ " user_text = gr.Textbox(\n",
1597
+ " label=\"Router SKU or model\",\n",
1598
+ " placeholder=\"Examples: IBR650B, AER1600, ES450, WR21, RUT240\",\n",
1599
+ " lines=1,\n",
1600
+ " )\n",
1601
+ " st = gr.State(\"{}\") # JSON string state\n",
1602
+ "\n",
1603
+ " # Actions\n",
1604
+ " check_btn = gr.Button(\"Check\", variant=\"primary\")\n",
1605
+ " pick_dd = gr.Dropdown(label=\"Pick A or B\", choices=[], visible=False)\n",
1606
+ " use_btn = gr.Button(\"Use selection\", visible=False)\n",
1607
+ "\n",
1608
+ " # Main outputs\n",
1609
+ " output_md = gr.Markdown()\n",
1610
+ " link_md = gr.Markdown()\n",
1611
+ " features_df = gr.Dataframe(headers=FEATURE_COLS, interactive=False, wrap=True)\n",
1612
+ " fit_df = gr.Dataframe(headers=FIT_COLS, interactive=False, wrap=True)\n",
1613
+ " qa_md = gr.Markdown()\n",
1614
+ "\n",
1615
+ " # Post-recommendation Q&A\n",
1616
+ " gr.Markdown(\"### Questions about the suggested device?\")\n",
1617
+ " question_box = gr.Textbox(\n",
1618
+ " label=\"Ask a question (optional)\",\n",
1619
+ " placeholder=\"Example: Does the 5G device support dual-SIM? How many ethernet ports? Does it support Wi‑Fi?\",\n",
1620
+ " lines=2,\n",
1621
+ " )\n",
1622
+ " ask_btn = gr.Button(\"Ask\", variant=\"secondary\")\n",
1623
+ "\n",
1624
+ " # Install-ready checklist\n",
1625
+ " install_btn = gr.Button(\"Make install-ready checklist\")\n",
1626
+ " install_md = gr.Markdown()\n",
1627
+ "\n",
1628
+ " # Customer-ready email summary\n",
1629
+ " gr.Markdown(\"### Customer-ready email\")\n",
1630
+ " email_btn = gr.Button(\"Generate customer email\")\n",
1631
+ " customer_email_box = gr.Textbox(label=\"Email draft\", lines=10)\n",
1632
+ "\n",
1633
+ " # Wiring (api_name=False avoids HF/Gradio API schema issues)\n",
1634
+ " check_btn.click(\n",
1635
+ " fn=run_lookup,\n",
1636
+ " inputs=[user_text, st],\n",
1637
+ " outputs=[output_md, link_md, features_df, fit_df, qa_md, pick_dd, use_btn, st, install_md, customer_email_box],\n",
1638
+ " api_name=False,\n",
1639
+ " )\n",
1640
+ " use_btn.click(\n",
1641
+ " fn=use_selection,\n",
1642
+ " inputs=[pick_dd, st],\n",
1643
+ " outputs=[output_md, link_md, features_df, fit_df, qa_md, pick_dd, use_btn, st, install_md, customer_email_box],\n",
1644
+ " api_name=False,\n",
1645
+ " )\n",
1646
+ " ask_btn.click(\n",
1647
+ " fn=answer_question,\n",
1648
+ " inputs=[question_box, st],\n",
1649
+ " outputs=[qa_md],\n",
1650
+ " api_name=False,\n",
1651
+ " )\n",
1652
+ " install_btn.click(\n",
1653
+ " fn=make_install_ready,\n",
1654
+ " inputs=[st],\n",
1655
+ " outputs=[install_md],\n",
1656
+ " api_name=False,\n",
1657
+ " )\n",
1658
+ " email_btn.click(\n",
1659
+ " fn=generate_customer_email,\n",
1660
+ " inputs=[st],\n",
1661
+ " outputs=[customer_email_box],\n",
1662
+ " api_name=False,\n",
1663
+ " )\n",
1664
+ "\n",
1665
+ " with gr.Tab(\"Batch\"):\n",
1666
+ " gr.Markdown(\"Paste one per line or upload a CSV (first column). Batch runs fast (no GPT).\")\n",
1667
+ " batch_text = gr.Textbox(label=\"Paste devices (one per line)\", lines=8, placeholder=\"WR21\\nRUT240\\nIBR650B\")\n",
1668
+ " batch_file = gr.File(label=\"Upload CSV\", file_types=[\".csv\"])\n",
1669
+ " include_ant = gr.Checkbox(label=\"Include antenna picks (slower)\", value=False)\n",
1670
+ " run_btn = gr.Button(\"Run batch\", variant=\"primary\")\n",
1671
+ "\n",
1672
+ " summary_md = gr.Markdown()\n",
1673
+ " rollup_md = gr.Markdown()\n",
1674
+ " table = gr.Dataframe(interactive=False, wrap=True)\n",
1675
+ " dl = gr.File(label=\"Download results CSV\")\n",
1676
+ "\n",
1677
+ " run_btn.click(\n",
1678
+ " fn=run_batch,\n",
1679
+ " inputs=[batch_text, batch_file, include_ant],\n",
1680
+ " outputs=[summary_md, table, dl, rollup_md],\n",
1681
+ " api_name=False,\n",
1682
+ " )\n",
1683
+ "\n",
1684
+ "demo.launch(show_api=False)\n"
1685
+ ]
1686
+ }
1687
+ ],
1688
+ "metadata": {
1689
+ "kernelspec": {
1690
+ "display_name": "Python 3",
1691
+ "name": "python3"
1692
+ },
1693
+ "language_info": {
1694
+ "name": "python"
1695
+ }
1696
+ },
1697
+ "nbformat": 4,
1698
+ "nbformat_minor": 5
1699
+ }