JP-AI-2026 commited on
Commit
1a1ae93
·
verified ·
1 Parent(s): bc6339a

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +300 -0
  2. requirements.txt +10 -0
app.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sweep Lite — plain-English reports for CSV / Excel spreadsheets.
2
+
3
+ Built for Hugging Face Spaces with ZeroGPU. The model is loaded once on CPU at
4
+ import time and moved to CUDA only inside the @spaces.GPU-decorated event
5
+ handler, so GPU memory is allocated on demand and released between requests.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from pathlib import Path
12
+ from queue import Empty
13
+ from threading import Thread
14
+
15
+ try: # Import before torch: ZeroGPU patches CUDA at import time.
16
+ import spaces
17
+ except ImportError: # local development without the `spaces` package
18
+
19
+ class _LocalSpaces:
20
+ @staticmethod
21
+ def GPU(duration: int = 60):
22
+ def decorator(fn):
23
+ return fn
24
+
25
+ return decorator
26
+
27
+ spaces = _LocalSpaces()
28
+
29
+ import gradio as gr # noqa: E402
30
+ import pandas as pd # noqa: E402
31
+ import torch # noqa: E402
32
+ import transformers # noqa: E402
33
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer # noqa: E402
34
+
35
+
36
+ # --------------------------------------------------------------------------- #
37
+ # Config
38
+ # --------------------------------------------------------------------------- #
39
+ MODEL_ID = os.getenv("SWEEP_LITE_MODEL", "Qwen/Qwen3.5-4B-Instruct")
40
+
41
+ MAX_PROFILE_CHARS = 12_000 # keep the prompt comfortably inside the context window
42
+ MAX_COLUMNS = 30
43
+ MAX_CELL_CHARS = 80
44
+ SAMPLE_ROWS = 10
45
+ MAX_NEW_TOKENS = 1024
46
+
47
+ SYSTEM_PROMPT = """You are Sweep Lite, an expert data analyst who writes clear, plain-English reports for busy executives.
48
+
49
+ 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.
50
+
51
+ Write a markdown report with these sections, in this order:
52
+ 1. **Executive summary** — 2-4 sentences on what the dataset contains and the headline takeaway.
53
+ 2. **Key findings** — 4-8 bullets with concrete numbers and column names.
54
+ 3. **Anomalies & data quality** — 4-8 bullets on missing values, odd types, suspicious ranges, or imbalanced categories.
55
+ 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.
56
+
57
+ Rules:
58
+ - Cite exact numbers from the profile. Never invent figures, columns, or rows.
59
+ - If something cannot be determined from the profile, say "not determinable from the profile".
60
+ - Keep the whole report under 500 words. No preamble, no sign-off.
61
+ - Output markdown only; do not wrap the report in a code fence.
62
+ """
63
+
64
+
65
+ # --------------------------------------------------------------------------- #
66
+ # Model (CPU at startup; GPU inside the decorated function)
67
+ # --------------------------------------------------------------------------- #
68
+ print(f"[Sweep Lite] Loading {MODEL_ID} on CPU in bfloat16 ...", flush=True)
69
+
70
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
71
+ if tokenizer.pad_token is None:
72
+ tokenizer.pad_token = tokenizer.eos_token or "<|endoftext|>"
73
+ tokenizer.padding_side = "right"
74
+
75
+ # transformers 5 renamed `torch_dtype` to `dtype`; support either major version.
76
+ _dtype_kwarg = "dtype" if int(transformers.__version__.split(".", 1)[0]) >= 5 else "torch_dtype"
77
+
78
+ model = AutoModelForCausalLM.from_pretrained(
79
+ MODEL_ID,
80
+ **{_dtype_kwarg: torch.bfloat16},
81
+ trust_remote_code=True,
82
+ low_cpu_mem_usage=True,
83
+ attn_implementation="sdpa", # safest backend on ZeroGPU hardware
84
+ )
85
+ model.eval()
86
+ print("[Sweep Lite] Model ready.", flush=True)
87
+
88
+
89
+ # --------------------------------------------------------------------------- #
90
+ # Spreadsheet profiling (pure pandas, no GPU)
91
+ # --------------------------------------------------------------------------- #
92
+ def read_spreadsheet(path: str) -> pd.DataFrame:
93
+ """Read a supported upload into a DataFrame, with a friendly failure mode."""
94
+ suffix = Path(path).suffix.lower()
95
+ if suffix == ".csv":
96
+ df = pd.read_csv(path)
97
+ elif suffix in {".xlsx", ".xls", ".xlsm", ".ods"}:
98
+ df = pd.read_excel(path)
99
+ else:
100
+ # Gradio sometimes gives a temp file without the original extension.
101
+ try:
102
+ df = pd.read_csv(path)
103
+ except Exception:
104
+ df = pd.read_excel(path)
105
+
106
+ if df.shape[0] == 0 or df.shape[1] == 0:
107
+ raise ValueError("the file has no data rows or no columns")
108
+ return df
109
+
110
+
111
+ def build_profile(df: pd.DataFrame) -> str:
112
+ """Compact, bounded text description of a DataFrame for the LLM prompt."""
113
+ n_rows, n_cols = df.shape
114
+ lines = [
115
+ f"Dataset shape: {n_rows} rows x {n_cols} columns",
116
+ f"Columns ({n_cols}): {', '.join(str(col) for col in df.columns)}",
117
+ "",
118
+ "Column types and missing values:",
119
+ ]
120
+
121
+ for col in df.columns[:MAX_COLUMNS]:
122
+ series = df[col]
123
+ missing = int(series.isna().sum())
124
+ pct = missing / max(n_rows, 1)
125
+ lines.append(
126
+ f"- {str(col)!r}: dtype={series.dtype}, non_null={int(series.notna().sum())}, "
127
+ f"missing={missing} ({pct:.1%}), unique={int(series.nunique(dropna=True))}"
128
+ )
129
+ if n_cols > MAX_COLUMNS:
130
+ lines.append(f"- ... {n_cols - MAX_COLUMNS} more columns omitted")
131
+
132
+ lines += ["", "Summary statistics (numeric columns, df.describe()):"]
133
+ numeric = df.describe(include="number").T
134
+ lines.append(
135
+ "(no numeric columns)"
136
+ if numeric.empty
137
+ else numeric.head(MAX_COLUMNS).round(3).to_string()
138
+ )
139
+
140
+ lines += ["", f"First {SAMPLE_ROWS} rows:"]
141
+ sample = df.head(SAMPLE_ROWS).iloc[:, :MAX_COLUMNS].astype(str)
142
+ sample = sample.apply(lambda col: col.str.slice(0, MAX_CELL_CHARS))
143
+ lines.append(sample.to_string(index=False))
144
+
145
+ profile = "\n".join(lines)
146
+ if len(profile) > MAX_PROFILE_CHARS:
147
+ profile = profile[:MAX_PROFILE_CHARS] + "\n... [profile truncated for context limit]"
148
+ return profile
149
+
150
+
151
+ # --------------------------------------------------------------------------- #
152
+ # Inference
153
+ # --------------------------------------------------------------------------- #
154
+ def render_messages(profile: str, question: str) -> list[dict]:
155
+ user = (
156
+ "Below is a structured profile of the uploaded spreadsheet. "
157
+ "Use it as the only source of facts.\n\n"
158
+ f"<data_profile>\n{profile}\n</data_profile>\n\n"
159
+ )
160
+ user += (
161
+ f"User question: {question}"
162
+ if question.strip()
163
+ else "User question: none — write the general report."
164
+ )
165
+ return [
166
+ {"role": "system", "content": SYSTEM_PROMPT},
167
+ {"role": "user", "content": user},
168
+ ]
169
+
170
+
171
+ def encode_messages(messages: list[dict]):
172
+ kwargs = {
173
+ "tokenize": True,
174
+ "add_generation_prompt": True,
175
+ "return_tensors": "pt",
176
+ }
177
+ # Qwen templates support thinking mode; turn it off for a clean report.
178
+ if "enable_thinking" in (tokenizer.chat_template or ""):
179
+ kwargs["enable_thinking"] = False
180
+ return tokenizer.apply_chat_template(messages, **kwargs)
181
+
182
+
183
+ def _run_generation(streamer: TextIteratorStreamer, **kwargs) -> None:
184
+ try:
185
+ with torch.inference_mode():
186
+ model.generate(streamer=streamer, **kwargs)
187
+ except Exception as exc: # keep the stream from hanging forever
188
+ print(f"[Sweep Lite] Generation failed: {exc}", flush=True)
189
+
190
+
191
+ def stream_report(profile: str, question: str):
192
+ """Generate the report on GPU and yield cumulative markdown."""
193
+ device = "cuda" if torch.cuda.is_available() else "cpu"
194
+ model.to(device)
195
+
196
+ input_ids = encode_messages(render_messages(profile, question)).to(device)
197
+ streamer = TextIteratorStreamer(
198
+ tokenizer, skip_prompt=True, skip_special_tokens=True
199
+ )
200
+ thread = Thread(
201
+ target=_run_generation,
202
+ kwargs={
203
+ "streamer": streamer,
204
+ "input_ids": input_ids,
205
+ "attention_mask": torch.ones_like(input_ids),
206
+ "max_new_tokens": MAX_NEW_TOKENS,
207
+ "do_sample": False,
208
+ "pad_token_id": tokenizer.pad_token_id,
209
+ },
210
+ daemon=True,
211
+ )
212
+ thread.start()
213
+
214
+ report = ""
215
+ while True:
216
+ try:
217
+ chunk = streamer.text_queue.get(timeout=0.5)
218
+ except Empty:
219
+ if not thread.is_alive():
220
+ break
221
+ continue
222
+ if chunk is streamer.stop_signal:
223
+ break
224
+ report += chunk
225
+ yield report
226
+
227
+ thread.join(timeout=5)
228
+ if not report.strip():
229
+ yield "_The model returned an empty response. Try rephrasing your question._"
230
+
231
+
232
+ # --------------------------------------------------------------------------- #
233
+ # Gradio UI — the decorated handler is the function bound to the button
234
+ # --------------------------------------------------------------------------- #
235
+ @spaces.GPU(duration=60)
236
+ def analyze(file_path: str | None, question: str | None):
237
+ if not file_path:
238
+ yield "### Sweep Lite\n\nUpload a `.csv`, `.xlsx`, or `.xls` file to get started."
239
+ return
240
+
241
+ try:
242
+ df = read_spreadsheet(file_path)
243
+ profile = build_profile(df)
244
+ except Exception as exc:
245
+ yield (
246
+ "### ⚠️ Could not read that file\n\n"
247
+ f"`{type(exc).__name__}: {exc}`\n\n"
248
+ "Please upload a valid, non-empty `.csv`, `.xlsx`, or `.xls` file."
249
+ )
250
+ return
251
+
252
+ yield (
253
+ "### 🔍 Writing your report…\n\n"
254
+ f"_Profiled {df.shape[0]:,} rows × {df.shape[1]:,} columns._"
255
+ )
256
+ yield from stream_report(profile, (question or "").strip())
257
+
258
+
259
+ with gr.Blocks(title="Sweep Lite", theme=gr.themes.Soft(primary_hue="indigo")) as demo:
260
+ gr.Markdown(
261
+ "# 🧹 Sweep Lite\n"
262
+ "Upload a spreadsheet and get a plain-English data report. "
263
+ "Powered by **Qwen 3.5 4B** on Hugging Face ZeroGPU."
264
+ )
265
+
266
+ with gr.Row():
267
+ with gr.Column(scale=1):
268
+ file_box = gr.File(
269
+ label="Spreadsheet (.csv, .xlsx, .xls)",
270
+ file_types=[".csv", ".xlsx", ".xls"],
271
+ type="filepath",
272
+ )
273
+ question_box = gr.Textbox(
274
+ label="Question (optional)",
275
+ placeholder="e.g. Which product line drove the margin drop?",
276
+ lines=3,
277
+ )
278
+ run_button = gr.Button("Generate report", variant="primary")
279
+ gr.Markdown(
280
+ "<small>Only a compact profile (shape, types, missing values, "
281
+ "statistics and 10 sample rows) is sent to the model.</small>"
282
+ )
283
+ with gr.Column(scale=2):
284
+ report_box = gr.Markdown(
285
+ value="Upload a spreadsheet and click **Generate report**.",
286
+ label="Report",
287
+ show_copy_button=True,
288
+ )
289
+
290
+ run_button.click(
291
+ analyze,
292
+ inputs=[file_box, question_box],
293
+ outputs=report_box,
294
+ )
295
+
296
+ # One request at a time: the model object is shared and moved to GPU in place.
297
+ demo.queue(default_concurrency_limit=1)
298
+
299
+ if __name__ == "__main__":
300
+ demo.launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", "7860")))
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Sweep Lite — Hugging Face Space (Gradio + ZeroGPU)
2
+ gradio>=5.0
3
+ pandas>=2.0
4
+ openpyxl>=3.1
5
+ xlrd>=2.0.1
6
+ torch>=2.3
7
+ transformers>=4.53
8
+ accelerate>=1.0
9
+ safetensors>=0.4
10
+ sentencepiece>=0.2