crazycrazypete commited on
Commit
dc11227
·
verified ·
1 Parent(s): add529d

Upload folder using huggingface_hub

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