"""Sweep Lite — plain-English reports for CSV / Excel spreadsheets. Built for Hugging Face Spaces with ZeroGPU. The model is loaded once on CPU at import time and moved to CUDA only inside the @spaces.GPU-decorated event handler, so GPU memory is allocated on demand and released between requests. """ from __future__ import annotations import os from pathlib import Path from queue import Empty from threading import Thread try: # Import before torch: ZeroGPU patches CUDA at import time. import spaces except ImportError: # local development without the `spaces` package class _LocalSpaces: @staticmethod def GPU(duration: int = 60): def decorator(fn): return fn return decorator spaces = _LocalSpaces() import gradio as gr # noqa: E402 import pandas as pd # noqa: E402 import torch # noqa: E402 import transformers # noqa: E402 from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer # noqa: E402 # --------------------------------------------------------------------------- # # Config # --------------------------------------------------------------------------- # MODEL_ID = os.getenv("SWEEP_LITE_MODEL", "Qwen/Qwen3.5-4B") MAX_PROFILE_CHARS = 12_000 # keep the prompt comfortably inside the context window MAX_COLUMNS = 30 MAX_CELL_CHARS = 80 SAMPLE_ROWS = 10 MAX_NEW_TOKENS = 1024 SYSTEM_PROMPT = """You are Sweep Lite, an expert data analyst who writes clear, plain-English reports for busy executives. You are given a structured profile of a CSV/Excel spreadsheet: its shape, column names, dtypes, missing-value counts, summary statistics and a small sample of rows. Treat that profile as your only source of truth. Write a markdown report with these sections, in this order: 1. **Executive summary** — 2-4 sentences on what the dataset contains and the headline takeaway. 2. **Key findings** — 4-8 bullets with concrete numbers and column names. 3. **Anomalies & data quality** — 4-8 bullets on missing values, odd types, suspicious ranges, or imbalanced categories. 4. **Answer to your question** — include only when the user asked a question; answer it directly and state what the data can and cannot support. Rules: - Cite exact numbers from the profile. Never invent figures, columns, or rows. - If something cannot be determined from the profile, say "not determinable from the profile". - Keep the whole report under 500 words. No preamble, no sign-off. - Output markdown only; do not wrap the report in a code fence. """ # --------------------------------------------------------------------------- # # Model (CPU at startup; GPU inside the decorated function) # --------------------------------------------------------------------------- # print(f"[Sweep Lite] Loading {MODEL_ID} on CPU in bfloat16 ...", flush=True) tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token or "<|endoftext|>" tokenizer.padding_side = "right" # transformers 5 renamed `torch_dtype` to `dtype`; support either major version. _dtype_kwarg = "dtype" if int(transformers.__version__.split(".", 1)[0]) >= 5 else "torch_dtype" model = AutoModelForCausalLM.from_pretrained( MODEL_ID, **{_dtype_kwarg: torch.bfloat16}, trust_remote_code=True, low_cpu_mem_usage=True, attn_implementation="sdpa", # safest backend on ZeroGPU hardware ) model.eval() print("[Sweep Lite] Model ready.", flush=True) # --------------------------------------------------------------------------- # # Spreadsheet profiling (pure pandas, no GPU) # --------------------------------------------------------------------------- # def read_spreadsheet(path: str) -> pd.DataFrame: """Read a supported upload into a DataFrame, with a friendly failure mode.""" suffix = Path(path).suffix.lower() if suffix == ".csv": df = pd.read_csv(path) elif suffix in {".xlsx", ".xls", ".xlsm", ".ods"}: df = pd.read_excel(path) else: # Gradio sometimes gives a temp file without the original extension. try: df = pd.read_csv(path) except Exception: df = pd.read_excel(path) if df.shape[0] == 0 or df.shape[1] == 0: raise ValueError("the file has no data rows or no columns") return df def build_profile(df: pd.DataFrame) -> str: """Compact, bounded text description of a DataFrame for the LLM prompt.""" n_rows, n_cols = df.shape lines = [ f"Dataset shape: {n_rows} rows x {n_cols} columns", f"Columns ({n_cols}): {', '.join(str(col) for col in df.columns)}", "", "Column types and missing values:", ] for col in df.columns[:MAX_COLUMNS]: series = df[col] missing = int(series.isna().sum()) pct = missing / max(n_rows, 1) lines.append( f"- {str(col)!r}: dtype={series.dtype}, non_null={int(series.notna().sum())}, " f"missing={missing} ({pct:.1%}), unique={int(series.nunique(dropna=True))}" ) if n_cols > MAX_COLUMNS: lines.append(f"- ... {n_cols - MAX_COLUMNS} more columns omitted") lines += ["", "Summary statistics (numeric columns, df.describe()):"] numeric = df.describe(include="number").T lines.append( "(no numeric columns)" if numeric.empty else numeric.head(MAX_COLUMNS).round(3).to_string() ) lines += ["", f"First {SAMPLE_ROWS} rows:"] sample = df.head(SAMPLE_ROWS).iloc[:, :MAX_COLUMNS].astype(str) sample = sample.apply(lambda col: col.str.slice(0, MAX_CELL_CHARS)) lines.append(sample.to_string(index=False)) profile = "\n".join(lines) if len(profile) > MAX_PROFILE_CHARS: profile = profile[:MAX_PROFILE_CHARS] + "\n... [profile truncated for context limit]" return profile # --------------------------------------------------------------------------- # # Inference # --------------------------------------------------------------------------- # def render_messages(profile: str, question: str) -> list[dict]: user = ( "Below is a structured profile of the uploaded spreadsheet. " "Use it as the only source of facts.\n\n" f"\n{profile}\n\n\n" ) user += ( f"User question: {question}" if question.strip() else "User question: none — write the general report." ) return [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user}, ] def encode_messages(messages: list[dict]): kwargs = { "tokenize": True, "add_generation_prompt": True, "return_tensors": "pt", } # Qwen templates support thinking mode; turn it off for a clean report. if "enable_thinking" in (tokenizer.chat_template or ""): kwargs["enable_thinking"] = False return tokenizer.apply_chat_template(messages, **kwargs) def _run_generation(streamer: TextIteratorStreamer, **kwargs) -> None: try: with torch.inference_mode(): model.generate(streamer=streamer, **kwargs) except Exception as exc: # keep the stream from hanging forever print(f"[Sweep Lite] Generation failed: {exc}", flush=True) def stream_report(profile: str, question: str): """Generate the report on GPU and yield cumulative markdown.""" device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) input_ids = encode_messages(render_messages(profile, question)).to(device) streamer = TextIteratorStreamer( tokenizer, skip_prompt=True, skip_special_tokens=True ) thread = Thread( target=_run_generation, kwargs={ "streamer": streamer, "input_ids": input_ids, "attention_mask": torch.ones_like(input_ids), "max_new_tokens": MAX_NEW_TOKENS, "do_sample": False, "pad_token_id": tokenizer.pad_token_id, }, daemon=True, ) thread.start() report = "" while True: try: chunk = streamer.text_queue.get(timeout=0.5) except Empty: if not thread.is_alive(): break continue if chunk is None: break report += chunk yield report thread.join(timeout=1.0) # --------------------------------------------------------------------------- # # Gradio UI + ZeroGPU Entrypoint # --------------------------------------------------------------------------- # @spaces.GPU(duration=60) def analyze(file_obj, question: str): if file_obj is None: yield "**Error:** Please upload a `.csv` or `.xlsx` spreadsheet first." return file_path = file_obj.name if hasattr(file_obj, "name") else str(file_obj) try: df = read_spreadsheet(file_path) profile = build_profile(df) except Exception as exc: yield f"**Error reading file:** {exc}" return yield "*Analyzing spreadsheet with Qwen 3.5 4B on ZeroGPU...*" yield from stream_report(profile, question or "") with gr.Blocks(title="Sweep Lite") as demo: gr.Markdown( "# Sweep Lite\n" "Upload a CSV or Excel spreadsheet to generate a plain-English executive report powered by **Qwen 3.5 4B** on ZeroGPU." ) with gr.Row(): with gr.Column(scale=1): file_input = gr.File( label="Upload Spreadsheet (.csv, .xlsx, .xls)", file_types=[".csv", ".xlsx", ".xls", ".xlsm", ".ods"], ) question_input = gr.Textbox( label="Optional Question", placeholder="e.g., Which region had the highest growth or unusual outliers?", lines=2, ) run_btn = gr.Button("Generate Report", variant="primary") with gr.Column(scale=2):