File size: 9,940 Bytes
1a1ae93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef7a182
1a1ae93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef7a182
1a1ae93
 
 
ef7a182
1a1ae93
 
 
ef7a182
1a1ae93
 
ef7a182
 
 
1a1ae93
 
ef7a182
1a1ae93
 
 
 
ef7a182
1a1ae93
 
ef7a182
 
1a1ae93
 
ef7a182
1a1ae93
33eed91
ef7a182
1a1ae93
 
 
ef7a182
 
 
1a1ae93
ef7a182
 
 
 
1a1ae93
ef7a182
1a1ae93
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
"""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"<data_profile>\n{profile}\n</data_profile>\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):