Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378############################################################# app.py - Hardened AI Analyst Bot for Sites_Master.xlsx# - GPT-4.1 via HTTP (requests)# - Column list in prompt# - Column validation + auto-rewrite on KeyError risk############################################################import osimport reimport tracebackimport numpy as npimport pandas as pdimport requestsimport streamlit as st############################################################# PAGE CONFIG AND THEME############################################################st.set_page_config(page_title="Sites Analyst Bot", layout="wide")ACCENT_BLUE = "#009FE3"st.markdown(f"""<style>html, body, .stApp {{background-color: white !important;}}.main-title {{color: #222222;font-size: 32px;font-weight: 700;}}.subtitle {{color: #444444;font-size: 14px;}}.accent-box {{border-left: 4px solid {ACCENT_BLUE};padding: 0.75rem 1rem;margin-bottom: 1rem;background-color: #f6fbff;border-radius: 6px;font-size: 13px;color: #333333;}}.chat-label {{font-weight: 600;margin-top: 0.5rem;margin-bottom: 0.25rem;}}</style>""",unsafe_allow_html=True,)############################################################# LOAD EXCEL FILE############################################################FILE_PATH = "Sites_Master.xlsx"@st.cache_data(show_spinner=True)def load_data() -> pd.DataFrame:df = pd.read_excel(FILE_PATH)return dfdf = load_data()############################################################# OPENAI CONFIG (env only)############################################################def normalize_openai_base(raw: str | None) -> str:base = (raw or "").strip()if not base:base = "https://api.openai.com"if base.startswith("ttps://"):base = "h" + baseif not base.startswith(("http://", "https://")):base = "https://" + base.lstrip("/")base = base.rstrip("/")if not base.endswith("/v1"):base = base + "/v1"return baseAPI_KEY = os.getenv("OPENAI_API_KEY", "")if not API_KEY:st.error("OPENAI_API_KEY is not configured.\n\n""Set it in your Space under Settings → Repository secrets → OPENAI_API_KEY.")st.stop()OPENAI_BASE = normalize_openai_base(os.getenv("OPENAI_BASE", ""))MODEL = os.getenv("OPENAI_MODEL", "gpt-4.1")CHAT_URL = OPENAI_BASE + "/chat/completions"############################################################# OPENAI CHAT HELPER############################################################def openai_chat(messages, temperature: float = 0.0) -> str:payload = {"model": MODEL, "messages": messages, "temperature": temperature}headers = {"Authorization": f"Bearer {API_KEY}"}resp = requests.post(CHAT_URL, json=payload, headers=headers, timeout=90)resp.raise_for_status()data = resp.json()return data["choices"][0]["message"]["content"]############################################################# PROMPT BUILDERS############################################################def build_code_prompt(df_head: pd.DataFrame, question: str) -> str:preview = df_head.to_string(max_rows=5)cols_list = "\n".join(f"- {c}" for c in df_head.columns)return ("You are an elite telecom data analyst.\n\n""You are analyzing a pandas DataFrame called df which contains thousands ""of Mobily/Ericsson telecom sites.\n\n"f"User question:\n\"\"\"{question}\"\"\"\n\n""VALID COLUMN NAMES (you MUST use these exact names only; ""do not merge, split, rename, abbreviate, or invent any column):\n"f"{cols_list}\n\n""If you need to combine information from multiple columns, use them ""separately in a boolean condition, for example:\n""result = df[(df['Key'] == ...) & (df['Swp/Dis Date'] == ...)].\n\n""Your job:\n""1. Understand the question.\n""2. Write ONLY Python pandas code.\n""3. Code MUST assign a variable named result.\n""4. Do NOT modify df.\n""5. Do NOT import anything.\n""6. Do NOT write explanations or comments.\n\n""The format MUST be exactly:\n\n""```python\n""result = <pandas_expression>\n""```\n\n""Here is a small preview of df (only to understand how values look; ""do not hard-code the preview values):\n"f"{preview}\n")def build_explanation_prompt(question: str, code_used: str, result) -> str:if isinstance(result, pd.DataFrame):preview = result.head(20).to_markdown(index=False)total_rows = len(result)result_text = (f"Result is a DataFrame with {total_rows} rows. ""Here is a preview (up to first 20 rows):\n\n" + preview)elif isinstance(result, pd.Series):preview = result.head(20).to_markdown()total = len(result)result_text = (f"Result is a Series with {total} items. ""Here is a preview (up to first 20 values):\n\n" + preview)else:result_text = f"Result is a scalar value: {repr(result)}"return ("You are a senior telecom data analyst. ""Explain the answer in clear, natural language, as if you are talking to a manager. ""Do not show Python code unless necessary. Be concise (2–4 sentences).\n\n"f"User question:\n{question}\n\n"f"Python pandas code that was executed:\n```python\n{code_used}\n```\n\n"f"Structured result summary:\n{result_text}\n\n""Now give a clear explanation of the result.")############################################################# CODE PARSING & VALIDATION############################################################def extract_python_snippet(markdown_text: str) -> str:"""Get the python code inside ```python ...``` or return raw text."""m = re.search(r"```python(.*?)```", markdown_text, re.DOTALL)if m:return m.group(1).strip()return markdown_text.strip()def extract_columns_from_code(code: str) -> set[str]:"""Find all df['col'] or df["col"] references.This is simple regex, not full AST, but works well for pandas expressions."""pattern = r"df\[\s*['\"]([^'\"]+)['\"]\s*\]"return set(re.findall(pattern, code))def validate_and_maybe_rewrite_code(question: str,initial_markdown: str,df: pd.DataFrame,max_retries: int = 1,) -> tuple[str | None, str | None, str | None]:"""Returns (code_to_run, final_markdown, error_message).- code_to_run: python snippet with result = ...- final_markdown: full markdown returned by model (for display)- error_message: if not None, something went wrong"""valid_cols = set(df.columns)markdown = initial_markdownfor attempt in range(max_retries + 1):code_snippet = extract_python_snippet(markdown)used_cols = extract_columns_from_code(code_snippet)invalid = used_cols - valid_colsif not invalid:return code_snippet, markdown, None# invalid columns found; ask model to fix codeif attempt == max_retries:# Give up after retrieserr = ("Model used invalid column names and could not be corrected.\n"f"Invalid columns: {sorted(invalid)}\n"f"Valid columns are: {list(valid_cols)}")return None, markdown, err# Build correction promptcols_list = "\n".join(f"- {c}" for c in valid_cols)correction_prompt = ("You previously generated pandas code for the following question:\n"f"Question: {question}\n\n""Your previous code was:\n"f"```python\n{code_snippet}\n```\n\n""However, the following column names are INVALID (they do not exist in df):\n"f"{sorted(invalid)}\n\n""Here is the list of VALID column names. You MUST only use these exact names:\n"f"{cols_list}\n\n""Rewrite the pandas code so that it answers the same question but uses only valid ""column names. Do not change the intent of the query.\n\n""Return ONLY code in the format:\n""```python\n""result = <pandas_expression>\n""```")markdown = openai_chat(messages=[{"role": "user", "content": correction_prompt}],temperature=0.0,)# Should not reach herereturn None, markdown, "Unexpected validation loop error."############################################################# EXECUTE GENERATED CODE SAFELY############################################################def execute_user_code(code: str, df: pd.DataFrame):safe_globals = {"df": df, "np": np, "pd": pd}local_env: dict = {}try:exec(code, safe_globals, local_env)if "result" not in local_env:return None, "Error: Code did not create a 'result' variable."return local_env["result"], Noneexcept Exception as e:return None, f"Execution error: {e}\n\n{traceback.format_exc()}"############################################################# MAIN UI############################################################st.markdown('<div class="main-title">AI Analyst Bot - Sites Master (Claude Style)</div>',unsafe_allow_html=True,)st.markdown('<div class="subtitle">Ask any telecom question in plain English. ''GPT-4.1 will generate pandas code against <code>Sites_Master.xlsx</code> and execute it.</div>',unsafe_allow_html=True,)st.markdown('<div class="accent-box">'"Examples: <b>“How many Active ODC sites in Makkah?”</b>, ""<b>“Show Access details of site 2603”</b>, ""<b>“Count VIP sites per Area.”</b>""</div>",unsafe_allow_html=True,)question = st.text_area("Write your question:",height=120,placeholder="How many Active sites in Makkah?",)run_button = st.button("Analyze")############################################################# HANDLE PROCESSING############################################################if run_button and question.strip():st.markdown('<div class="chat-label">You:</div>', unsafe_allow_html=True)st.write(question)st.markdown('<div class="chat-label">Bot:</div>', unsafe_allow_html=True)st.write("GPT-4.1 is analyzing your data...")df_preview = df.head(5)code_prompt = build_code_prompt(df_preview, question)# 1) Ask GPT-4.1 for pandas codetry:initial_markdown = openai_chat(messages=[{"role": "user", "content": code_prompt}],temperature=0.0,)except Exception as e:st.error(f"GPT-4.1 request error while generating code: {e}")st.stop()# 2) Validate columns and auto-rewrite if neededcode_to_run, final_markdown, validation_err = validate_and_maybe_rewrite_code(question, initial_markdown, df, max_retries=1)with st.expander("Show generated pandas code"):st.code(final_markdown, language="python")if validation_err:st.error(validation_err)st.stop()# 3) Execute the pandas coderesult, exec_err = execute_user_code(code_to_run, df)if exec_err:st.error(exec_err)else:st.success("Execution successful!")# Show raw structured resultif isinstance(result, (pd.DataFrame, pd.Series)):st.dataframe(result, use_container_width=True)else:st.write(result)# 4) Ask GPT-4.1 to explain the result in natural languagetry:explanation_prompt = build_explanation_prompt(question, code_to_run, result)explanation = openai_chat(messages=[{"role": "user", "content": explanation_prompt}],temperature=0.1,)st.markdown("#### Explanation")st.write(explanation)except Exception as e:st.warning(f"Could not generate explanation: {e}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389# app.py — Sites Dashboard (NL Q&A, no backend)# Data source: local Sites_Master.xlsx (repo root). Falls back to Sites_Master.csv if present.# Uses headers.json for alias/normalization. No external API calls.from __future__ import annotationsimport osimport ioimport reimport jsonfrom typing import Dict, List, Optional, Tupleimport pandas as pdimport numpy as npfrom tabulate import tabulateimport streamlit as st# =========================# Page config# =========================st.set_page_config(page_title="Sites Dashboard — NL Q&A", layout="wide")# Minimal theme helpers (no JS)st.markdown("""<style>.app-title { font-size: 1.6rem; font-weight: 700; margin: 0.2rem 0 0.6rem 0; }.help-hint { opacity: 0.8; font-size: 0.9rem; }.metric-pill { padding: 6px 10px; border-radius: 999px; background: #eef3f6; display: inline-block; margin-right: 6px; }.table-note { font-size: 0.85rem; opacity: 0.85; }/* Keep inputs readable on both light/dark */.stTextInput>div>div>input { font-size: 1rem; }</style>""",unsafe_allow_html=True,)# =========================# Paths# =========================DATA_XLSX = os.environ.get("SITES_FILE", "Sites_Master.xlsx")DATA_CSV = os.environ.get("SITES_FILE_FALLBACK", "Sites_Master.csv")HEADERS_JSON = os.environ.get("HEADERS_FILE", "headers.json")# =========================# Load headers.json# =========================@st.cache_data(show_spinner=False)def load_headers(path: str) -> Dict[str, str]:"""Return alias->canonical mapping from headers.json.Expected schema: list of {"name": <canonical>, "aliases": [..]} objects,but we also accept {"fields": [...]}. All names are normalized to lower."""alias_to_name: Dict[str, str] = {}if not os.path.exists(path):return alias_to_nametry:with open(path, "r", encoding="utf-8") as f:raw = json.load(f)fields: List[dict] = []if isinstance(raw, list):fields = rawelif isinstance(raw, dict) and "fields" in raw and isinstance(raw["fields"], list):fields = raw["fields"]for item in fields:name = str(item.get("name", "")).strip()if not name:continuecanon = namealias_to_name[name.lower()] = canonfor a in item.get("aliases", []) or []:if not a:continuealias_to_name[str(a).lower()] = canonreturn alias_to_nameexcept Exception:return {}# =========================# Load data# =========================@st.cache_data(ttl=10800, show_spinner=True) # 3hdef load_data(xlsx_path: str, csv_path: str) -> pd.DataFrame:if os.path.exists(xlsx_path):try:df = pd.read_excel(xlsx_path)return dfexcept Exception as e:st.warning(f"Failed to read {xlsx_path}: {e}. Trying CSV…")if os.path.exists(csv_path):try:df = pd.read_csv(csv_path)return dfexcept Exception as e:st.error(f"Failed to read CSV fallback {csv_path}: {e}")return pd.DataFrame()st.error("No data file found. Place 'Sites_Master.xlsx' or 'Sites_Master.csv' in repo root.")return pd.DataFrame()# =========================# Column normalization# =========================def normalize(s: str) -> str:return re.sub(r"\s+", " ", str(s).strip())def canon_columns(df: pd.DataFrame, alias_map: Dict[str, str]) -> Tuple[pd.DataFrame, Dict[str, str]]:"""Return df with canonical columns and a map of original->canonical.If a column matches an alias, we rename it to its canonical name.Else we keep as-is."""rename_map: Dict[str, str] = {}lower_map = {c.lower(): c for c in df.columns}for lower, original in lower_map.items():# Exact alias hitif lower in alias_map:rename_map[original] = alias_map[lower]else:# Attempt loose normalization (remove punctuation / collapse spaces)key = re.sub(r"[^a-z0-9]+", " ", lower).strip()if key in alias_map:rename_map[original] = alias_map[key]# Apply renameif rename_map:df = df.rename(columns=rename_map)return df, rename_map# =========================# Query parsing# =========================REGION_HINTS = ["region", "area", "city", "cluster", "governorate", "makkah", "madinah", "jeddah", "taif"]STATUS_HINTS = ["status", "site status", "state"]SITE_ID_HINTS = ["site id", "siteid", "site code", "site number", "id"]VIP_HINTS = ["vip", "priority", "site priority", "vip category"]SHELTER_HINTS = ["shelter", "odc", "cabinet", "enclosure"]TRM_HINTS = ["trm", "transmission", "mw", "microwave"]TOWER_HINTS = ["tower type", "tower"]NAME_LIKE_HINTS = ["site name", "name"]INTENT_LIST = re.compile(r"\b(list|show|share|display)\b", re.I)INTENT_COUNT = re.compile(r"\b(how many|count|total|number of)\b", re.I)INTENT_GROUP = re.compile(r"\b(group by|breakdown|per\s+region|by\s+region|by\s+area|distribution)\b", re.I)def find_cols(df: pd.DataFrame, hints: List[str]) -> List[str]:cols: List[str] = []for c in df.columns:cl = c.lower()if any(h in cl for h in hints):cols.append(c)return colsdef best_region_cols(df: pd.DataFrame) -> List[str]:cols = find_cols(df, REGION_HINTS)return cols or find_cols(df, ["region"]) or []def text_filter(df: pd.DataFrame, cols: List[str], needle: str) -> pd.Series:if not cols:return pd.Series([True] * len(df))n = needle.lower()m = pd.Series([False] * len(df))for c in cols:try:m = m | df[c].astype(str).str.lower().str.contains(n, na=False)except Exception:continuereturn mdef keyword_filter(df: pd.DataFrame, q: str) -> pd.Series:ql = q.lower()m = pd.Series([True] * len(df))# ODC / Shelter keywordsif any(k in ql for k in ["odc", "cabinet", "enclosure", "shelter"]):cols = find_cols(df, SHELTER_HINTS)if cols:m = m & text_filter(df, cols, "odc")# VIPif "vip" in ql:cols = find_cols(df, VIP_HINTS)if cols:m = m & text_filter(df, cols, "vip")# Status wordsfor word in ["active", "repeater", "core"]:if word in ql:cols = find_cols(df, STATUS_HINTS)if cols:m = m & text_filter(df, cols, word)# TRMif "trm" in ql:cols = find_cols(df, TRM_HINTS)if cols:m = m & text_filter(df, cols, "trm")# Tower typeif "tower" in ql":cols = find_cols(df, TOWER_HINTS)if cols:# try to capture an optional value like 'monopole', 'RTT' etc.m = m & pd.Series([True] * len(df))return mdef parse_query(df: pd.DataFrame, q: str) -> Dict[str, object]:"""Return a plan dict: {intent: 'count'|'list'|'group', filters: mask, group_by: Optional[str]}"""plan: Dict[str, object] = {"intent": "count", "filters": pd.Series([True] * len(df)), "group_by": None}# Decide intentif INTENT_LIST.search(q):plan["intent"] = "list"elif INTENT_GROUP.search(q):plan["intent"] = "group"elif INTENT_COUNT.search(q):plan["intent"] = "count"else:# default: if user says "sites" or "site list" we assume list, else countif re.search(r"\bsite(s)?\b", q, re.I):plan["intent"] = "list"# Region / Area extraction (simple heuristic: look for token after 'in' or 'at')region_cols = best_region_cols(df)region_mask = pd.Series([True] * len(df))m = re.search(r"\b(?:in|at|within|for)\s+([A-Za-z\-\s]+)$", q.strip(), re.I)region_term = Noneif m:region_term = m.group(1).strip()# strip trailing words like 'region' if user wrote 'in Makkah region'region_term = re.sub(r"\b(region|area|city)\b", "", region_term, flags=re.I).strip()else:# try to match known region-like tokens anywhere (Makkah, Jeddah, Taif, Madinah)for token in ["makkah", "madinah", "jeddah", "taif"]:if re.search(rf"\b{token}\b", q, re.I):region_term = tokenbreakif region_term and region_cols:region_mask = text_filter(df, region_cols, region_term)# Keyword filters (ODC, VIP, Active, etc.)kw_mask = keyword_filter(df, q)plan["filters"] = region_mask & kw_mask# Groupingif plan["intent"] == "group":# choose a sensible group column based on query wordsif "region" in q.lower() or "area" in q.lower():gcols = region_colselif "trm" in q.lower():gcols = find_cols(df, TRM_HINTS)elif "shelter" in q.lower() or "odc" in q.lower():gcols = find_cols(df, SHELTER_HINTS)elif "tower" in q.lower():gcols = find_cols(df, TOWER_HINTS)elif "status" in q.lower():gcols = find_cols(df, STATUS_HINTS)else:# fallback to region if availablegcols = region_colsplan["group_by"] = gcols[0] if gcols else Nonereturn plandef apply_plan(df: pd.DataFrame, plan: Dict[str, object]) -> Dict[str, object]:mask = plan.get("filters")if mask is None or not isinstance(mask, pd.Series):mask = pd.Series([True] * len(df))sub = df[mask].copy()result: Dict[str, object] = {"rows": len(sub), "df": sub}if plan.get("intent") == "count":result["mode"] = "count"return resultif plan.get("intent") == "list":result["mode"] = "list"return resultif plan.get("intent") == "group":g = plan.get("group_by")if g and g in sub.columns:gp = (sub.groupby(g, dropna=False).size().reset_index(name="Count").sort_values("Count", ascending=False))result["mode"] = "group"result["group"] = gpreturn resultelse:# fallback to count when no group column was foundresult["mode"] = "count"return result# defaultresult["mode"] = "count"return result# =========================# UI# =========================st.markdown('<div class="app-title">Sites Dashboard — Natural‑Language Q&A</div>', unsafe_allow_html=True)colA, colB, colC = st.columns([1,1,2])with colA:if st.button("Sync latest data", type="secondary", key="syncbtn"):load_data.clear()load_headers.clear()st.experimental_rerun()with colB:st.caption("Data source: Sites_Master.xlsx (fallback Sites_Master.csv)")with colC:st.caption("Tip: Try 'How many ODC sites in Makkah?' or 'List VIP sites in Jeddah' or 'Breakdown by region for TRM'")# Load artifactsalias_map = load_headers(HEADERS_JSON)df_raw = load_data(DATA_XLSX, DATA_CSV)if df_raw.empty:st.stop()# Normalize & show quick mappingdf, rename_map = canon_columns(df_raw, alias_map)with st.expander("Columns (after alias normalization)", expanded=False):left, right = st.columns([3,2])with left:st.write(pd.DataFrame({"Columns": list(df.columns)}))with right:if rename_map:st.write(pd.DataFrame({"Original": list(rename_map.keys()), "Canonical": list(rename_map.values())}))else:st.write("No header aliases applied.")# Ask boxq = st.text_input(label="Ask in plain English…",value="How many ODC sites in Makkah that are Active?",key="ask_input_main",help="We use headers.json to understand your column names (aliases).",)run = st.button("Run", type="primary", key="run_btn")if run and q.strip():plan = parse_query(df, q)res = apply_plan(df, plan)# Summary barst.markdown(f"<div class='metric-pill'>Intent: <b>{plan.get('intent')}</b></div>"f"<div class='metric-pill'>Rows matched: <b>{res.get('rows', 0)}</b></div>",unsafe_allow_html=True,)mode = res.get("mode")if mode == "count":st.subheader("Count")st.success(f"Total matching sites: {res.get('rows', 0)}")elif mode == "list":st.subheader("Matching rows (first 200 shown)")view = res["df"].copy()# Attempt to order with Site ID first if presentsite_cols = [c for c in df.columns if any(h in c.lower() for h in SITE_ID_HINTS)]if site_cols:cols = [site_cols[0]] + [c for c in view.columns if c != site_cols[0]]view = view[cols]st.dataframe(view.head(200), use_container_width=True)# Download all matchedcsv = view.to_csv(index=False).encode("utf-8")st.download_button("Download CSV (all matched)", data=csv, file_name="filtered_sites.csv", mime="text/csv", key="dl_csv")# Pretty small table text with tabulate (first 20 rows)small = view.head(20)st.markdown("**Preview (tabulate, 20 rows):**")st.code(tabulate(small, headers="keys", tablefmt="github", showindex=False))elif mode == "group":st.subheader(f"Breakdown by: {plan.get('group_by')}")gp: pd.DataFrame = res.get("group", pd.DataFrame())st.dataframe(gp, use_container_width=True)csv = gp.to_csv(index=False).encode("utf-8")st.download_button("Download Grouped CSV", data=csv, file_name="grouped_counts.csv", mime="text/csv", key="dl_group")else:st.info("Enter a question and click Run.")
app.py+367-356