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

Upload folder using huggingface_hub

Browse files
Updates/only-routers_ai_poc_hf_fixed_v10_2.ipynb ADDED
@@ -0,0 +1,1653 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "24915479",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Only-Routers (v10.2)\n",
9
+ "\n",
10
+ "Fixes UI indentation for Spaces."
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": null,
16
+ "id": "3f33f2b3",
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 _features_from_dec(model: str, canon_make: str) -> Dict[str, str]:\n",
990
+ " \"\"\"Lookup a router model in dec2025routers.csv and return the key feature fields.\"\"\"\n",
991
+ " if not model or model in {\"Not listed\", \"Not applicable\"}:\n",
992
+ " return {k: \"Not listed\" for k in FEATURE_COLS[1:]}\n",
993
+ "\n",
994
+ " pool = df_dec[df_dec[\"_canon_make\"] == canon_make].copy()\n",
995
+ " if pool.empty:\n",
996
+ " return {k: \"Not listed\" for k in FEATURE_COLS[1:]}\n",
997
+ "\n",
998
+ " hit = process.extractOne(norm_text(model), pool[\"_norm_model\"].tolist(), scorer=fuzz.WRatio)\n",
999
+ " if not hit or hit[1] < MATCH_OK:\n",
1000
+ " return {k: \"Not listed\" for k in FEATURE_COLS[1:]}\n",
1001
+ "\n",
1002
+ " r = pool.iloc[int(hit[2])]\n",
1003
+ " ports = f\"WAN: {r.get('WAN ports and speed','')} | LAN: {r.get('LAN ports and speed','')}\"\n",
1004
+ " return {\n",
1005
+ " \"Modem technology\": str(r.get(\"Modem Type\",\"\")) or \"Not listed\",\n",
1006
+ " \"WiFi\": str(r.get(\"WiFi type\",\"\")) or \"Not listed\",\n",
1007
+ " \"Ports\": ports.strip() if ports.strip() else \"Not listed\",\n",
1008
+ " \"Antennas\": str(r.get(\"Antennas (internal/external/both)\",\"\")) or \"Not listed\",\n",
1009
+ " \"Ruggedness\": str(r.get(\"Ruggedization\",\"\")) or \"Not listed\",\n",
1010
+ " \"Use case\": str(r.get(\"Primary use case\",\"\")) or \"Not listed\",\n",
1011
+ " }\n",
1012
+ "\n",
1013
+ "def _gpt_fill_feature_row(device_label: str, model: str, canon_make: str, row: Dict[str, str]) -> Dict[str, str]:\n",
1014
+ " \"\"\"If dec can't supply values, ask GPT to fill missing ones (best guess).\"\"\"\n",
1015
+ " if client is None:\n",
1016
+ " return row\n",
1017
+ "\n",
1018
+ " missing = [k for k,v in row.items() if (not v) or str(v).strip().lower() in {\"not listed\",\"nan\",\"\"}]\n",
1019
+ " if not missing:\n",
1020
+ " return row\n",
1021
+ "\n",
1022
+ " sys = \"Fill missing router feature fields for a Verizon rep. Return strict JSON only.\"\n",
1023
+ " payload = {\n",
1024
+ " \"device_label\": device_label,\n",
1025
+ " \"model\": model,\n",
1026
+ " \"maker_family\": canon_make,\n",
1027
+ " \"known\": row,\n",
1028
+ " \"fill_only\": missing,\n",
1029
+ " \"rules\": [\n",
1030
+ " \"Fill only the requested fields.\",\n",
1031
+ " \"Best guess if needed. Short phrases only.\",\n",
1032
+ " \"Return JSON only.\"\n",
1033
+ " ],\n",
1034
+ " \"output_schema\": {k: \"string\" for k in missing}\n",
1035
+ " }\n",
1036
+ " out = gpt_json(sys, payload, max_tokens=260) or {}\n",
1037
+ " for k in missing:\n",
1038
+ " val = str(out.get(k, \"\") or \"\").strip()\n",
1039
+ " if val:\n",
1040
+ " row[k] = val\n",
1041
+ " return row\n",
1042
+ "\n",
1043
+ "def build_replacement_features_table(repl_4g: str, repl_5g: str, canon_make: str) -> pd.DataFrame:\n",
1044
+ " rows = []\n",
1045
+ "\n",
1046
+ " # 4G\n",
1047
+ " row4 = _features_from_dec(repl_4g, canon_make)\n",
1048
+ " row4 = _gpt_fill_feature_row(\"4G alternative\", repl_4g, canon_make, row4)\n",
1049
+ " rows.append({\"Device\": \"4G alternative\", **row4})\n",
1050
+ "\n",
1051
+ " # 5G\n",
1052
+ " row5 = _features_from_dec(repl_5g, canon_make)\n",
1053
+ " row5 = _gpt_fill_feature_row(\"5G replacement\", repl_5g, canon_make, row5)\n",
1054
+ " rows.append({\"Device\": \"5G replacement\", **row5})\n",
1055
+ "\n",
1056
+ " df = pd.DataFrame(rows, columns=FEATURE_COLS)\n",
1057
+ " return df\n",
1058
+ "\n",
1059
+ "\n",
1060
+ "# ============================\n",
1061
+ "# Verizon fit badges (small table) for recommended devices\n",
1062
+ "# ============================\n",
1063
+ "\n",
1064
+ "FIT_COLS = [\"Device\", \"Fit badges\", \"Ethernet ports\", \"Battery\"]\n",
1065
+ "\n",
1066
+ "def _parse_ethernet_ports(wan_field: str, lan_field: str) -> str:\n",
1067
+ " \"\"\"Best-effort total ethernet ports based on WAN/LAN text.\"\"\"\n",
1068
+ " def _count(field: str) -> int:\n",
1069
+ " s = str(field or \"\")\n",
1070
+ " # Common forms: \"1x GbE\", \"2 x 10/100\", \"WAN: 1\", etc.\n",
1071
+ " nums = [int(x) for x in re.findall(r\"(\\\\d+)\\\\s*x\", s.lower())]\n",
1072
+ " if nums:\n",
1073
+ " return sum(nums)\n",
1074
+ " # Fallback: if it contains 'port' with a number\n",
1075
+ " m = re.search(r\"(\\\\d+)\\\\s*port\", s.lower())\n",
1076
+ " if m:\n",
1077
+ " return int(m.group(1))\n",
1078
+ " # If it contains '1' and 'wan' in short text, guess 1\n",
1079
+ " if \"wan\" in s.lower() and re.search(r\"\\\\b1\\\\b\", s):\n",
1080
+ " return 1\n",
1081
+ " return 0\n",
1082
+ "\n",
1083
+ " total = _count(wan_field) + _count(lan_field)\n",
1084
+ " return str(total) if total > 0 else \"Not listed\"\n",
1085
+ "\n",
1086
+ "def _battery_badge(battery_field: str) -> str:\n",
1087
+ " s = str(battery_field or \"\").strip().lower()\n",
1088
+ " if not s or s in {\"none\", \"no\", \"n/a\", \"not listed\"}:\n",
1089
+ " return \"No\"\n",
1090
+ " return \"Yes\"\n",
1091
+ "\n",
1092
+ "def _bool_badge(flag: bool) -> str:\n",
1093
+ " return \"Yes\" if flag else \"No\"\n",
1094
+ "\n",
1095
+ "def _dual_sim_from_row_text(*fields: str) -> bool:\n",
1096
+ " txt = \" \".join([str(x or \"\") for x in fields]).lower()\n",
1097
+ " return (\"dual sim\" in txt) or (\"2 sim\" in txt) or (\"two sim\" in txt) or (\"dual-sim\" in txt)\n",
1098
+ "\n",
1099
+ "def _throughput_high(throughput_field: str) -> bool:\n",
1100
+ " t = str(throughput_field or \"\").lower()\n",
1101
+ " # Heuristic: anything mentioning gbps or >=1000 mbps\n",
1102
+ " if \"gbps\" in t:\n",
1103
+ " return True\n",
1104
+ " m = re.search(r\"(\\\\d+(?:\\\\.\\\\d+)?)\\\\s*mbps\", t)\n",
1105
+ " if m:\n",
1106
+ " try:\n",
1107
+ " return float(m.group(1)) >= 1000.0\n",
1108
+ " except Exception:\n",
1109
+ " pass\n",
1110
+ " return False\n",
1111
+ "\n",
1112
+ "def _gpt_fit_badges(model: str, canon_make: str, is_5g: bool, dec_row: Optional[pd.Series]) -> Tuple[str, str, str]:\n",
1113
+ " \"\"\"\n",
1114
+ " GPT-based fill for Fit badges / Ethernet ports / Battery, used when dec is missing or incomplete.\n",
1115
+ " Returns (badges_csv, ethernet_ports, battery_yesno).\n",
1116
+ " \"\"\"\n",
1117
+ " if client is None:\n",
1118
+ " return (\"Not listed\", \"Not listed\", \"Not listed\")\n",
1119
+ "\n",
1120
+ " dec_ctx = {}\n",
1121
+ " if dec_row is not None:\n",
1122
+ " try:\n",
1123
+ " dec_ctx = {\n",
1124
+ " \"Model\": str(dec_row.get(\"Model\",\"\")),\n",
1125
+ " \"Modem Type\": str(dec_row.get(\"Modem Type\",\"\")),\n",
1126
+ " \"Ruggedization\": str(dec_row.get(\"Ruggedization\",\"\")),\n",
1127
+ " \"WAN ports and speed\": str(dec_row.get(\"WAN ports and speed\",\"\")),\n",
1128
+ " \"LAN ports and speed\": str(dec_row.get(\"LAN ports and speed\",\"\")),\n",
1129
+ " \"Antennas\": str(dec_row.get(\"Antennas (internal/external/both)\",\"\")),\n",
1130
+ " \"WiFi type\": str(dec_row.get(\"WiFi type\",\"\")),\n",
1131
+ " \"Primary use case\": str(dec_row.get(\"Primary use case\",\"\")),\n",
1132
+ " \"Serial port\": str(dec_row.get(\"Serial port (yes/no)\",\"\")),\n",
1133
+ " \"VPN\": str(dec_row.get(\"VPN capabilities\",\"\")),\n",
1134
+ " \"Throughput\": str(dec_row.get(\"Router throughput\",\"\")),\n",
1135
+ " \"Battery\": str(dec_row.get(\"Battery (internal/removable/none/optional)\",\"\")),\n",
1136
+ " \"Special notes\": str(dec_row.get(\"Special notes\",\"\")),\n",
1137
+ " \"Summary\": str(dec_row.get(\"summary and use case\",\"\")),\n",
1138
+ " }\n",
1139
+ " except Exception:\n",
1140
+ " dec_ctx = {}\n",
1141
+ "\n",
1142
+ " sys = (\n",
1143
+ " \"You are helping a Verizon rep. Based on the provided router context, output fit badges and a couple quick traits.\\n\"\n",
1144
+ " \"Return STRICT JSON only.\\n\"\n",
1145
+ " \"Badges must be chosen from this set only:\\n\"\n",
1146
+ " \"['Vehicle','Fixed site','Wi‑Fi','Rugged','Dual‑SIM','4x4 MIMO','High throughput','Serial'].\\n\"\n",
1147
+ " \"Rules:\\n\"\n",
1148
+ " \"- If is_5g is true, ALWAYS include '4x4 MIMO'.\\n\"\n",
1149
+ " \"- Ethernet ports: return a single integer as a string if you can infer total ethernet ports, otherwise 'Not listed'.\\n\"\n",
1150
+ " \"- Battery: return 'Yes' or 'No' if you can infer, otherwise 'Not listed'.\\n\"\n",
1151
+ " \"- If uncertain between Vehicle vs Fixed site, pick the most likely based on use case/ruggedization.\\n\"\n",
1152
+ " )\n",
1153
+ "\n",
1154
+ " payload = {\n",
1155
+ " \"model\": model,\n",
1156
+ " \"maker_family\": canon_make,\n",
1157
+ " \"is_5g\": bool(is_5g),\n",
1158
+ " \"dec_context\": dec_ctx,\n",
1159
+ " \"output_schema\": {\n",
1160
+ " \"badges\": [\"string\"],\n",
1161
+ " \"ethernet_ports\": \"string\",\n",
1162
+ " \"battery\": \"Yes|No|Not listed\"\n",
1163
+ " }\n",
1164
+ " }\n",
1165
+ "\n",
1166
+ " out = gpt_json(sys, payload, max_tokens=260) or {}\n",
1167
+ "\n",
1168
+ " badges = out.get(\"badges\", []) or []\n",
1169
+ " allowed = {\"Vehicle\",\"Fixed site\",\"Wi‑Fi\",\"Rugged\",\"Dual‑SIM\",\"4x4 MIMO\",\"High throughput\",\"Serial\"}\n",
1170
+ " clean = []\n",
1171
+ " for b in badges:\n",
1172
+ " bs = str(b).strip()\n",
1173
+ " if bs in allowed:\n",
1174
+ " clean.append(bs)\n",
1175
+ "\n",
1176
+ " if is_5g and \"4x4 MIMO\" not in clean:\n",
1177
+ " clean.append(\"4x4 MIMO\")\n",
1178
+ "\n",
1179
+ " eth = str(out.get(\"ethernet_ports\",\"\") or \"\").strip()\n",
1180
+ " if not eth or eth.lower() in {\"nan\",\"none\"}:\n",
1181
+ " eth = \"Not listed\"\n",
1182
+ " m = re.search(r\"\\d+\", eth)\n",
1183
+ " eth = m.group(0) if m else (\"Not listed\" if eth == \"Not listed\" else eth)\n",
1184
+ "\n",
1185
+ " bat = str(out.get(\"battery\",\"\") or \"\").strip()\n",
1186
+ " if not bat:\n",
1187
+ " bat = \"Not listed\"\n",
1188
+ " if bat.lower().startswith(\"y\"):\n",
1189
+ " bat = \"Yes\"\n",
1190
+ " elif bat.lower().startswith(\"n\"):\n",
1191
+ " bat = \"No\"\n",
1192
+ " elif bat not in {\"Yes\",\"No\",\"Not listed\"}:\n",
1193
+ " bat = \"Not listed\"\n",
1194
+ "\n",
1195
+ " dedup=[]\n",
1196
+ " seen=set()\n",
1197
+ " for b in clean:\n",
1198
+ " if b not in seen:\n",
1199
+ " seen.add(b); dedup.append(b)\n",
1200
+ " badges_csv = \", \".join(dedup) if dedup else \"Not listed\"\n",
1201
+ " return (badges_csv, eth, bat)\n",
1202
+ "\n",
1203
+ "\n",
1204
+ "def _fit_badges_for_model(model: str, canon_make: str, is_5g: bool) -> Tuple[str, str, str]:\n",
1205
+ " \"\"\"Return (badges_csv, ethernet_ports, battery_yesno). Uses dec2025routers.csv first, then GPT fill.\"\"\"\n",
1206
+ " model = str(model or \"\").strip()\n",
1207
+ " if not model or model in {\"Not listed\", \"Not applicable\"}:\n",
1208
+ " return (\"Not listed\", \"Not listed\", \"Not listed\")\n",
1209
+ "\n",
1210
+ " pool = df_dec[df_dec[\"_canon_make\"] == canon_make].copy()\n",
1211
+ " row = None\n",
1212
+ " if not pool.empty:\n",
1213
+ " hit = process.extractOne(norm_text(model), pool[\"_norm_model\"].tolist(), scorer=fuzz.WRatio)\n",
1214
+ " if hit and hit[1] >= MATCH_OK:\n",
1215
+ " row = pool.iloc[int(hit[2])]\n",
1216
+ "\n",
1217
+ " badges = []\n",
1218
+ " eth = \"Not listed\"\n",
1219
+ " bat_yes = \"Not listed\"\n",
1220
+ "\n",
1221
+ " if row is not None:\n",
1222
+ " use_case = str(row.get(\"Primary use case\",\"\") or \"\").lower()\n",
1223
+ " rugged = str(row.get(\"Ruggedization\",\"\") or \"\").lower()\n",
1224
+ "\n",
1225
+ " if any(k in use_case for k in [\"vehicle\",\"mobile\",\"fleet\",\"in-vehicle\"]) or \"vehicle\" in rugged:\n",
1226
+ " badges.append(\"Vehicle\")\n",
1227
+ " else:\n",
1228
+ " badges.append(\"Fixed site\")\n",
1229
+ "\n",
1230
+ " wifi = str(row.get(\"WiFi type\",\"\") or \"\").strip()\n",
1231
+ " if wifi and wifi.lower() not in {\"none\",\"no\",\"n/a\"}:\n",
1232
+ " badges.append(\"Wi‑Fi\")\n",
1233
+ "\n",
1234
+ " if any(k in rugged for k in [\"rugged\",\"industrial\",\"ip\",\"harsh\"]):\n",
1235
+ " badges.append(\"Rugged\")\n",
1236
+ "\n",
1237
+ " notes_blob = \" \".join([\n",
1238
+ " str(row.get(\"Special notes\",\"\") or \"\"),\n",
1239
+ " str(row.get(\"summary and use case\",\"\") or \"\"),\n",
1240
+ " ]).lower()\n",
1241
+ " if \"dual\" in notes_blob and \"sim\" in notes_blob:\n",
1242
+ " badges.append(\"Dual‑SIM\")\n",
1243
+ "\n",
1244
+ " if is_5g:\n",
1245
+ " badges.append(\"4x4 MIMO\")\n",
1246
+ "\n",
1247
+ " thr = str(row.get(\"Router throughput\",\"\") or \"\").lower()\n",
1248
+ " m = re.search(r\"(\\d+(\\.\\d+)?)\\s*gb\", thr)\n",
1249
+ " if m:\n",
1250
+ " try:\n",
1251
+ " if float(m.group(1)) >= 1.0:\n",
1252
+ " badges.append(\"High throughput\")\n",
1253
+ " except Exception:\n",
1254
+ " pass\n",
1255
+ "\n",
1256
+ " serial = str(row.get(\"Serial port (yes/no)\",\"\") or \"\").strip().lower()\n",
1257
+ " if serial in {\"yes\",\"y\",\"true\"}:\n",
1258
+ " badges.append(\"Serial\")\n",
1259
+ "\n",
1260
+ " wan = str(row.get(\"WAN ports and speed\",\"\") or \"\")\n",
1261
+ " lan = str(row.get(\"LAN ports and speed\",\"\") or \"\")\n",
1262
+ " m1 = re.search(r\"(\\d+)\\s*x\", wan.lower())\n",
1263
+ " m2 = re.search(r\"(\\d+)\\s*x\", lan.lower())\n",
1264
+ " if m1 or m2:\n",
1265
+ " total = (int(m1.group(1)) if m1 else 0) + (int(m2.group(1)) if m2 else 0)\n",
1266
+ " eth = str(total) if total > 0 else \"Not listed\"\n",
1267
+ "\n",
1268
+ " bat = str(row.get(\"Battery (internal/removable/none/optional)\",\"\") or \"\")\n",
1269
+ " bat_l = bat.lower().strip()\n",
1270
+ " if bat_l:\n",
1271
+ " if \"none\" in bat_l:\n",
1272
+ " bat_yes = \"No\"\n",
1273
+ " else:\n",
1274
+ " bat_yes = \"Yes\"\n",
1275
+ "\n",
1276
+ " # Use GPT when anything is missing (instead of best-effort inference)\n",
1277
+ " if (row is None) or (eth == \"Not listed\") or (bat_yes == \"Not listed\") or (not badges):\n",
1278
+ " g_badges, g_eth, g_bat = _gpt_fit_badges(model, canon_make, is_5g, row)\n",
1279
+ "\n",
1280
+ " if badges:\n",
1281
+ " if is_5g and \"4x4 MIMO\" not in badges:\n",
1282
+ " badges.append(\"4x4 MIMO\")\n",
1283
+ " dedup=[]\n",
1284
+ " seen=set()\n",
1285
+ " for b in badges:\n",
1286
+ " if b not in seen:\n",
1287
+ " seen.add(b); dedup.append(b)\n",
1288
+ " badges_csv = \", \".join(dedup)\n",
1289
+ " else:\n",
1290
+ " badges_csv = g_badges\n",
1291
+ "\n",
1292
+ " eth = eth if eth != \"Not listed\" else g_eth\n",
1293
+ " bat_yes = bat_yes if bat_yes != \"Not listed\" else g_bat\n",
1294
+ " return (badges_csv or \"Not listed\", eth or \"Not listed\", bat_yes or \"Not listed\")\n",
1295
+ "\n",
1296
+ " dedup=[]\n",
1297
+ " seen=set()\n",
1298
+ " for b in badges:\n",
1299
+ " if b not in seen:\n",
1300
+ " seen.add(b); dedup.append(b)\n",
1301
+ " badges_csv = \", \".join(dedup) if dedup else \"Not listed\"\n",
1302
+ " return (badges_csv, eth, bat_yes)\n",
1303
+ "\n",
1304
+ "def build_fit_table(repl_4g: str, repl_5g: str, canon_make: str) -> pd.DataFrame:\n",
1305
+ " rows = []\n",
1306
+ " # 4G alt row (is_5g False)\n",
1307
+ " b4, eth4, bat4 = _fit_badges_for_model(repl_4g, canon_make, is_5g=False)\n",
1308
+ " rows.append({\"Device\": \"4G alternative\", \"Fit badges\": b4, \"Ethernet ports\": eth4, \"Battery\": bat4})\n",
1309
+ " # 5G row (is_5g True)\n",
1310
+ " b5, eth5, bat5 = _fit_badges_for_model(repl_5g, canon_make, is_5g=True)\n",
1311
+ " rows.append({\"Device\": \"5G replacement\", \"Fit badges\": b5, \"Ethernet ports\": eth5, \"Battery\": bat5})\n",
1312
+ " return pd.DataFrame(rows, columns=FIT_COLS)\n",
1313
+ "\n",
1314
+ "# ============================\n",
1315
+ "# Output\n",
1316
+ "# ============================\n",
1317
+ "def assemble_output(life_row: pd.Series, status: str, eos: str, eol: str, repl: Dict[str,Any], ant: Dict[str,Any]) -> str:\n",
1318
+ " current_name = f\"{life_row.get('sku','')} — {life_row.get('description','')}\".strip(\" —\")\n",
1319
+ " st = ant.get(\"stationary_omni\", {})\n",
1320
+ " vh = ant.get(\"vehicle_omni\", {})\n",
1321
+ "\n",
1322
+ " lines = []\n",
1323
+ " lines.append(f\"1. Current device: **{current_name}**\")\n",
1324
+ " lines.append(f\"2. Status: **{status}**\")\n",
1325
+ " lines.append(f\"3. End of Sale date: **{eos}**\")\n",
1326
+ " lines.append(f\"4. End of Life date: **{eol}**\")\n",
1327
+ " lines.append(f\"5. 4G alternative (lifecycle): **{repl.get('repl_4g','Not applicable')}**\")\n",
1328
+ " lines.append(f\"6. 5G replacement (lifecycle): **{repl.get('repl_5g','Not listed')}**\")\n",
1329
+ " lines.append(\"7. Antenna options (Parsec-only):\")\n",
1330
+ " conn_s = f\" | Conn: {st.get('connectors','')}\" if st.get(\"connectors\") else \"\"\n",
1331
+ " conn_v = f\" | Conn: {vh.get('connectors','')}\" if vh.get(\"connectors\") else \"\"\n",
1332
+ " lines.append(f\" - Stationary (Omni): **{st.get('name','')}** (Part #: {st.get('part_number','')}) — {st.get('description','')} — MIMO: {st.get('mimo','')}{conn_s}\")\n",
1333
+ " lines.append(f\" - Vehicle (Omni): **{vh.get('name','')}** (Part #: {vh.get('part_number','')}) — {vh.get('description','')} — MIMO: {vh.get('mimo','')}{conn_v}\")\n",
1334
+ "\n",
1335
+ " lines.append(\"\\nSources (debug):\")\n",
1336
+ " for s in repl.get(\"sources\", []) if isinstance(repl.get(\"sources\"), list) else []:\n",
1337
+ " lines.append(f\"- {s}\")\n",
1338
+ " lines.append(\"- ParsecCatalog.pdf (local RAG)\")\n",
1339
+ " lines.append(\"- routers_eos_eol_by_sku.csv (replacements)\")\n",
1340
+ " return \"\\n\".join(lines)\n",
1341
+ "\n",
1342
+ "\n",
1343
+ "# ============================\n",
1344
+ "# Customer-ready email summary (single lookup only)\n",
1345
+ "# ============================\n",
1346
+ "\n",
1347
+ "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",
1348
+ " \"\"\"Email-style summary the rep can paste to a customer (lightly sales-y).\"\"\"\n",
1349
+ " current = f\"{life_row.get('sku','')} — {life_row.get('description','')}\".strip(\" —\")\n",
1350
+ " repl5 = str(repl.get(\"repl_5g\",\"\") or \"\").strip()\n",
1351
+ " repl4 = str(repl.get(\"repl_4g\",\"\") or \"\").strip()\n",
1352
+ "\n",
1353
+ " st = ant.get(\"stationary_omni\", {}) or {}\n",
1354
+ " vh = ant.get(\"vehicle_omni\", {}) or {}\n",
1355
+ "\n",
1356
+ " lines = []\n",
1357
+ " lines.append(\"Subject: Router replacement recommendation\")\n",
1358
+ " lines.append(\"\")\n",
1359
+ " lines.append(\"Hi there,\")\n",
1360
+ " lines.append(\"\")\n",
1361
+ " lines.append(f\"We reviewed your current router (**{current}**) and recommend the following path forward:\")\n",
1362
+ " lines.append(\"\")\n",
1363
+ " lines.append(f\"- **Status:** {status}\")\n",
1364
+ " lines.append(f\"- **End of Sale:** {eos}\")\n",
1365
+ " lines.append(f\"- **End of Life:** {eol}\")\n",
1366
+ " lines.append(\"\")\n",
1367
+ " lines.append(\"**Recommended replacement (5G):**\")\n",
1368
+ " lines.append(f\"- {repl5 if repl5 else 'Not listed'}\")\n",
1369
+ " if link5:\n",
1370
+ " lines.append(f\"- Manufacturer page (best effort): {link5}\")\n",
1371
+ " lines.append(\"\")\n",
1372
+ " lines.append(\"**Optional 4G alternative (if needed):**\")\n",
1373
+ " lines.append(f\"- {repl4 if repl4 and repl4.lower() != 'not applicable' else 'Not applicable'}\")\n",
1374
+ " lines.append(\"\")\n",
1375
+ " lines.append(\"**Antenna suggestions (Parsec):**\")\n",
1376
+ " lines.append(f\"- Stationary (Omni): {st.get('name','')} (PN {st.get('part_number','')})\")\n",
1377
+ " lines.append(f\"- Vehicle (Omni): {vh.get('name','')} (PN {vh.get('part_number','')})\")\n",
1378
+ " lines.append(\"\")\n",
1379
+ " lines.append(\"If you’d like, we can confirm the best-fit option for your install environment and provide pricing.\")\n",
1380
+ " lines.append(\"\")\n",
1381
+ " lines.append(\"Contact Peter Dunn @ 786.999.9127 or peter.dunn@masterstelecom.com for pricing.\")\n",
1382
+ " lines.append(\"\")\n",
1383
+ " lines.append(\"Thanks,\")\n",
1384
+ " lines.append(\"Peter Dunn\")\n",
1385
+ " return \"\\n\".join(lines)\n",
1386
+ "\n",
1387
+ "def generate_customer_email(st_json: str) -> str:\n",
1388
+ " st = state_load(st_json)\n",
1389
+ " if not st or \"row_idx\" not in st:\n",
1390
+ " return \"Run a lookup first.\"\n",
1391
+ " try:\n",
1392
+ " life_row = df_eos.iloc[int(st[\"row_idx\"])]\n",
1393
+ " except Exception:\n",
1394
+ " return \"Run a lookup first.\"\n",
1395
+ "\n",
1396
+ " eos, eol, status = row_to_dates_and_status(life_row)\n",
1397
+ " repl = st.get(\"repl\", {}) or {}\n",
1398
+ " ant = st.get(\"ant\", {}) or {}\n",
1399
+ "\n",
1400
+ " canon_make = str(life_row.get(\"_canon_make\",\"UNKNOWN\"))\n",
1401
+ " url5 = _best_effort_manufacturer_url(str(repl.get(\"repl_5g\",\"\") or \"\"), canon_make)\n",
1402
+ " return build_customer_email(life_row, status, eos, eol, repl, ant, url5)\n",
1403
+ "\n",
1404
+ "# ============================\n",
1405
+ "# Gradio callbacks\n",
1406
+ "# IMPORTANT: no dict state and ALL events have api_name=False (prevents api_info schema generation)\n",
1407
+ "# ============================\n",
1408
+ "def run_lookup(user_text: str, st_json: str):\n",
1409
+ " user_text = str(user_text or \"\").strip()\n",
1410
+ " if not user_text:\n",
1411
+ " return \"Enter a router SKU/model.\", \"\", None, None, \"\", gr.update(visible=False), gr.update(visible=False), \"{}\", \"\", \"\"\n",
1412
+ "\n",
1413
+ " res = resolve_device(user_text)\n",
1414
+ "\n",
1415
+ " if res.get(\"mode\") == \"pick\":\n",
1416
+ " opts = res.get(\"options\", [])\n",
1417
+ " choices = [o[\"label\"] for o in opts]\n",
1418
+ " st2 = {\"mode\":\"pick\",\"options\": opts, \"raw\": user_text}\n",
1419
+ " 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",
1420
+ "\n",
1421
+ " if res.get(\"mode\") != \"ok\":\n",
1422
+ " return \"Not found.\", \"\", None, None, \"\", gr.update(visible=False), gr.update(visible=False), \"{}\", \"\", \"\"\n",
1423
+ "\n",
1424
+ " life_row = df_eos.iloc[int(res[\"row_idx\"])]\n",
1425
+ " eos, eol, status = row_to_dates_and_status(life_row)\n",
1426
+ "\n",
1427
+ " repl = pick_replacements_lifecycle(life_row, status, use_gpt=True)\n",
1428
+ " canon_make = str(life_row.get(\"_canon_make\",\"UNKNOWN\"))\n",
1429
+ " mimo = infer_mimo_for_5g(repl.get(\"repl_5g\",\"\"))\n",
1430
+ " 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",
1431
+ " ant = antenna_options_for(repl.get(\"repl_5g\") or str(life_row.get(\"sku\",\"\")), tech, mimo)\n",
1432
+ "\n",
1433
+ " output = assemble_output(life_row, status, eos, eol, repl, ant)\n",
1434
+ " st_out = {\"row_idx\": int(res[\"row_idx\"]), \"repl\": repl, \"ant\": ant, \"raw\": user_text}\n",
1435
+ " url5 = _best_effort_manufacturer_url(repl.get('repl_5g',''), canon_make)\n",
1436
+ " link = f\"**5G manufacturer page (best effort):** {url5}\" if url5 else \"\"\n",
1437
+ " feat_df = build_replacement_features_table(repl.get('repl_4g',''), repl.get('repl_5g',''), canon_make)\n",
1438
+ " fit = build_fit_table(repl.get('repl_4g',''), repl.get('repl_5g',''), canon_make)\n",
1439
+ " return output, link, feat_df, fit, \"\", gr.update(visible=False), gr.update(visible=False), state_dump(st_out), \"\", \"\"\n",
1440
+ "\n",
1441
+ "def use_selection(selected_label: str, st_json: str):\n",
1442
+ " st = state_load(st_json)\n",
1443
+ " if not st or st.get(\"mode\") != \"pick\":\n",
1444
+ " return \"Run a search first.\", \"\", None, None, \"\", gr.update(visible=False), gr.update(visible=False), \"{}\", \"\", \"\"\n",
1445
+ "\n",
1446
+ " if not selected_label:\n",
1447
+ " return \"Pick A or B first.\", \"\", None, None, \"\", gr.update(visible=True), gr.update(visible=True), st_json, \"\", \"\"\n",
1448
+ "\n",
1449
+ " chosen_row = None\n",
1450
+ " for o in st.get(\"options\", []):\n",
1451
+ " if o.get(\"label\") == selected_label:\n",
1452
+ " chosen_row = int(o[\"row_idx\"])\n",
1453
+ " break\n",
1454
+ " if chosen_row is None:\n",
1455
+ " return \"Pick a valid option.\", \"\", None, None, \"\", gr.update(visible=True), gr.update(visible=True), st_json, \"\", \"\"\n",
1456
+ "\n",
1457
+ " life_row = df_eos.iloc[int(chosen_row)]\n",
1458
+ " eos, eol, status = row_to_dates_and_status(life_row)\n",
1459
+ "\n",
1460
+ " repl = pick_replacements_lifecycle(life_row, status, use_gpt=True)\n",
1461
+ " canon_make = str(life_row.get(\"_canon_make\",\"UNKNOWN\"))\n",
1462
+ " mimo = infer_mimo_for_5g(repl.get(\"repl_5g\",\"\"))\n",
1463
+ " 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",
1464
+ " ant = antenna_options_for(repl.get(\"repl_5g\") or str(life_row.get(\"sku\",\"\")), tech, mimo)\n",
1465
+ "\n",
1466
+ " output = assemble_output(life_row, status, eos, eol, repl, ant)\n",
1467
+ " st_out = {\"row_idx\": int(chosen_row), \"repl\": repl, \"ant\": ant, \"raw\": st.get(\"raw\",\"\")}\n",
1468
+ " url5 = _best_effort_manufacturer_url(repl.get('repl_5g',''), canon_make)\n",
1469
+ " link = f\"**5G manufacturer page (best effort):** {url5}\" if url5 else \"\"\n",
1470
+ " feat_df = build_replacement_features_table(repl.get('repl_4g',''), repl.get('repl_5g',''), canon_make)\n",
1471
+ " fit = build_fit_table(repl.get('repl_4g',''), repl.get('repl_5g',''), canon_make)\n",
1472
+ " return output, link, feat_df, fit, \"\", gr.update(visible=False), gr.update(visible=False), state_dump(st_out), \"\", \"\"\n",
1473
+ "\n",
1474
+ "def make_install_ready(st_json: str):\n",
1475
+ " st = state_load(st_json)\n",
1476
+ " if not st or \"row_idx\" not in st:\n",
1477
+ " return \"Run a lookup first.\"\n",
1478
+ " life_row = df_eos.iloc[int(st[\"row_idx\"])]\n",
1479
+ " current_sku = str(life_row.get(\"sku\",\"\") or \"\")\n",
1480
+ " return install_ready_checklist(current_sku, st.get(\"repl\", {}) or {}, st.get(\"ant\", {}) or {})\n",
1481
+ "\n",
1482
+ "\n",
1483
+ "\n",
1484
+ "# ============================\n",
1485
+ "# Q&A about the suggested device (post-recommendation)\n",
1486
+ "# ============================\n",
1487
+ "def answer_question(question: str, st_json: str) -> str:\n",
1488
+ " q = str(question or \"\").strip()\n",
1489
+ " if not q:\n",
1490
+ " return \"\"\n",
1491
+ " st = state_load(st_json)\n",
1492
+ " if not st or \"repl\" not in st:\n",
1493
+ " return \"Run a lookup first, then ask your question.\"\n",
1494
+ "\n",
1495
+ " repl = st.get(\"repl\", {}) or {}\n",
1496
+ " ant = st.get(\"ant\", {}) or {}\n",
1497
+ " repl5 = str(repl.get(\"repl_5g\",\"\") or \"\").strip()\n",
1498
+ " repl4 = str(repl.get(\"repl_4g\",\"\") or \"\").strip()\n",
1499
+ " # Pull a bit of dec context for the 5G model (if possible)\n",
1500
+ " canon_make = \"\"\n",
1501
+ " try:\n",
1502
+ " # Try to infer maker family from stored row_idx\n",
1503
+ " if \"row_idx\" in st:\n",
1504
+ " row = df_eos.iloc[int(st[\"row_idx\"])]\n",
1505
+ " canon_make = str(row.get(\"_canon_make\",\"UNKNOWN\"))\n",
1506
+ " except Exception:\n",
1507
+ " canon_make = \"\"\n",
1508
+ "\n",
1509
+ " # Manufacturer link (best effort)\n",
1510
+ " url5 = _best_effort_manufacturer_url(repl5, canon_make) if repl5 else \"\"\n",
1511
+ "\n",
1512
+ " # Feature table row for 5G (helps the LLM answer spec questions without web scraping)\n",
1513
+ " feat5 = {}\n",
1514
+ " try:\n",
1515
+ " feat5 = _features_from_dec(repl5, canon_make) if repl5 else {}\n",
1516
+ " except Exception:\n",
1517
+ " feat5 = {}\n",
1518
+ "\n",
1519
+ " sys = (\n",
1520
+ " \"You are a Verizon field rep assistant. Answer questions about the suggested router in a fast, practical way. \"\n",
1521
+ " \"Use the provided context; do not mention internal tools, prompts, embeddings, or databases. \"\n",
1522
+ " \"If the question is about specs and the value is unknown, say 'Not listed' and suggest checking the manufacturer page. \"\n",
1523
+ " \"Keep it concise and scannable.\"\n",
1524
+ " )\n",
1525
+ "\n",
1526
+ " context = {\n",
1527
+ " \"recommended_5g\": repl5,\n",
1528
+ " \"recommended_4g\": repl4 if repl4 and repl4.lower() != \"not applicable\" else \"\",\n",
1529
+ " \"manufacturer_link_5g\": url5,\n",
1530
+ " \"known_5g_features\": feat5,\n",
1531
+ " \"antenna_stationary\": ant.get(\"stationary_omni\", {}),\n",
1532
+ " \"antenna_vehicle\": ant.get(\"vehicle_omni\", {}),\n",
1533
+ " }\n",
1534
+ "\n",
1535
+ " user = \"Context:\\n\" + json.dumps(context, ensure_ascii=False) + \"\\n\\nQuestion:\\n\" + q\n",
1536
+ "\n",
1537
+ " ans = gpt_answer_md(sys, user, max_tokens=650)\n",
1538
+ " # Small safety fallback\n",
1539
+ " return ans if ans else \"I couldn't generate an answer right now. Try again.\"\n",
1540
+ "\n",
1541
+ "# ============================\n",
1542
+ "# UI\n",
1543
+ "# ============================\n",
1544
+ "with gr.Blocks(title=\"Only-Routers\") as demo:\n",
1545
+ " gr.Markdown(\"## Only-Routers\\nSingle lookup + Batch upload for Verizon reps.\")\n",
1546
+ "\n",
1547
+ " with gr.Tabs():\n",
1548
+ " with gr.Tab(\"Single\"):\n",
1549
+ " # Inputs\n",
1550
+ " user_text = gr.Textbox(\n",
1551
+ " label=\"Router SKU or model\",\n",
1552
+ " placeholder=\"Examples: IBR650B, AER1600, ES450, WR21, RUT240\",\n",
1553
+ " lines=1,\n",
1554
+ " )\n",
1555
+ " st = gr.State(\"{}\") # JSON string state\n",
1556
+ "\n",
1557
+ " # Actions\n",
1558
+ " check_btn = gr.Button(\"Check\", variant=\"primary\")\n",
1559
+ " pick_dd = gr.Dropdown(label=\"Pick A or B\", choices=[], visible=False)\n",
1560
+ " use_btn = gr.Button(\"Use selection\", visible=False)\n",
1561
+ "\n",
1562
+ " # Main outputs\n",
1563
+ " output_md = gr.Markdown()\n",
1564
+ " link_md = gr.Markdown()\n",
1565
+ " features_df = gr.Dataframe(headers=FEATURE_COLS, interactive=False, wrap=True)\n",
1566
+ " fit_df = gr.Dataframe(headers=FIT_COLS, interactive=False, wrap=True)\n",
1567
+ " qa_md = gr.Markdown()\n",
1568
+ "\n",
1569
+ " # Post-recommendation Q&A\n",
1570
+ " gr.Markdown(\"### Questions about the suggested device?\")\n",
1571
+ " question_box = gr.Textbox(\n",
1572
+ " label=\"Ask a question (optional)\",\n",
1573
+ " placeholder=\"Example: Does the 5G device support dual-SIM? How many ethernet ports? Does it support Wi‑Fi?\",\n",
1574
+ " lines=2,\n",
1575
+ " )\n",
1576
+ " ask_btn = gr.Button(\"Ask\", variant=\"secondary\")\n",
1577
+ "\n",
1578
+ " # Install-ready checklist\n",
1579
+ " install_btn = gr.Button(\"Make install-ready checklist\")\n",
1580
+ " install_md = gr.Markdown()\n",
1581
+ "\n",
1582
+ " # Customer-ready email summary\n",
1583
+ " gr.Markdown(\"### Customer-ready email\")\n",
1584
+ " email_btn = gr.Button(\"Generate customer email\")\n",
1585
+ " customer_email_box = gr.Textbox(label=\"Email draft\", lines=10)\n",
1586
+ "\n",
1587
+ " # Wiring (api_name=False avoids HF/Gradio API schema issues)\n",
1588
+ " check_btn.click(\n",
1589
+ " fn=run_lookup,\n",
1590
+ " inputs=[user_text, st],\n",
1591
+ " outputs=[output_md, link_md, features_df, fit_df, qa_md, pick_dd, use_btn, st, install_md, customer_email_box],\n",
1592
+ " api_name=False,\n",
1593
+ " )\n",
1594
+ " use_btn.click(\n",
1595
+ " fn=use_selection,\n",
1596
+ " inputs=[pick_dd, st],\n",
1597
+ " outputs=[output_md, link_md, features_df, fit_df, qa_md, pick_dd, use_btn, st, install_md, customer_email_box],\n",
1598
+ " api_name=False,\n",
1599
+ " )\n",
1600
+ " ask_btn.click(\n",
1601
+ " fn=answer_question,\n",
1602
+ " inputs=[question_box, st],\n",
1603
+ " outputs=[qa_md],\n",
1604
+ " api_name=False,\n",
1605
+ " )\n",
1606
+ " install_btn.click(\n",
1607
+ " fn=make_install_ready,\n",
1608
+ " inputs=[st],\n",
1609
+ " outputs=[install_md],\n",
1610
+ " api_name=False,\n",
1611
+ " )\n",
1612
+ " email_btn.click(\n",
1613
+ " fn=generate_customer_email,\n",
1614
+ " inputs=[st],\n",
1615
+ " outputs=[customer_email_box],\n",
1616
+ " api_name=False,\n",
1617
+ " )\n",
1618
+ "\n",
1619
+ " with gr.Tab(\"Batch\"):\n",
1620
+ " gr.Markdown(\"Paste one per line or upload a CSV (first column). Batch runs fast (no GPT).\")\n",
1621
+ " batch_text = gr.Textbox(label=\"Paste devices (one per line)\", lines=8, placeholder=\"WR21\\nRUT240\\nIBR650B\")\n",
1622
+ " batch_file = gr.File(label=\"Upload CSV\", file_types=[\".csv\"])\n",
1623
+ " include_ant = gr.Checkbox(label=\"Include antenna picks (slower)\", value=False)\n",
1624
+ " run_btn = gr.Button(\"Run batch\", variant=\"primary\")\n",
1625
+ "\n",
1626
+ " summary_md = gr.Markdown()\n",
1627
+ " rollup_md = gr.Markdown()\n",
1628
+ " table = gr.Dataframe(interactive=False, wrap=True)\n",
1629
+ " dl = gr.File(label=\"Download results CSV\")\n",
1630
+ "\n",
1631
+ " run_btn.click(\n",
1632
+ " fn=run_batch,\n",
1633
+ " inputs=[batch_text, batch_file, include_ant],\n",
1634
+ " outputs=[summary_md, table, dl, rollup_md],\n",
1635
+ " api_name=False,\n",
1636
+ " )\n",
1637
+ "\n",
1638
+ "demo.launch(show_api=False)\n"
1639
+ ]
1640
+ }
1641
+ ],
1642
+ "metadata": {
1643
+ "kernelspec": {
1644
+ "display_name": "Python 3",
1645
+ "name": "python3"
1646
+ },
1647
+ "language_info": {
1648
+ "name": "python"
1649
+ }
1650
+ },
1651
+ "nbformat": 4,
1652
+ "nbformat_minor": 5
1653
+ }
app.py CHANGED
@@ -1527,40 +1527,75 @@ with gr.Blocks(title="Only-Routers") as demo:
1527
 
1528
  with gr.Tabs():
1529
  with gr.Tab("Single"):
1530
- user_text = gr.Textbox(label="Router SKU or model", placeholder="Examples: IBR650B, AER1600, ES450, WR21, RUT240", lines=1)
1531
- st = gr.State("{}") # JSON string
1532
-
 
 
 
 
 
 
1533
  check_btn = gr.Button("Check", variant="primary")
1534
  pick_dd = gr.Dropdown(label="Pick A or B", choices=[], visible=False)
1535
  use_btn = gr.Button("Use selection", visible=False)
1536
 
 
1537
  output_md = gr.Markdown()
1538
-
1539
  link_md = gr.Markdown()
1540
  features_df = gr.Dataframe(headers=FEATURE_COLS, interactive=False, wrap=True)
1541
  fit_df = gr.Dataframe(headers=FIT_COLS, interactive=False, wrap=True)
1542
-
1543
-
1544
-
1545
- gr.Markdown("### Questions about the suggested device?")
1546
- question_box = gr.Textbox(label="Ask a question (optional)", placeholder="Example: Does the 5G device support dual-SIM? What antenna ports does it have?", lines=2)
1547
- ask_btn = gr.Button("Ask", variant="secondary")
1548
- qa_md = gr.Markdown()
1549
-
1550
-
 
 
 
1551
  install_btn = gr.Button("Make install-ready checklist")
1552
  install_md = gr.Markdown()
1553
 
1554
- gr.Markdown("### Customer-ready email (copy/paste)")
 
1555
  email_btn = gr.Button("Generate customer email")
1556
- customer_email_box = gr.Textbox(label="Email summary", lines=14)
1557
-
1558
-
1559
- check_btn.click(fn=run_lookup, inputs=[user_text, st], outputs=[output_md, link_md, features_df, fit_df, qa_md, pick_dd, use_btn, st, install_md, customer_email_box], api_name=False)
1560
- use_btn.click(fn=use_selection, inputs=[pick_dd, st], outputs=[output_md, link_md, features_df, fit_df, qa_md, pick_dd, use_btn, st, install_md, customer_email_box], api_name=False)
1561
- install_btn.click(fn=make_install_ready, inputs=[st], outputs=[install_md], api_name=False)
1562
- email_btn.click(fn=generate_customer_email, inputs=[st], outputs=[customer_email_box], api_name=False)
1563
- ask_btn.click(fn=answer_question, inputs=[question_box, st], outputs=[qa_md], api_name=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1564
 
1565
  with gr.Tab("Batch"):
1566
  gr.Markdown("Paste one per line or upload a CSV (first column). Batch runs fast (no GPT).")
@@ -1574,7 +1609,11 @@ qa_md = gr.Markdown()
1574
  table = gr.Dataframe(interactive=False, wrap=True)
1575
  dl = gr.File(label="Download results CSV")
1576
 
1577
- run_btn.click(fn=run_batch, inputs=[batch_text, batch_file, include_ant], outputs=[summary_md, table, dl, rollup_md], api_name=False)
 
 
 
 
 
1578
 
1579
- # IMPORTANT: On Spaces, demo.launch() is correct; do NOT use share=True.
1580
  demo.launch(show_api=False)
 
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).")
 
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)