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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import io
|
| 5 |
+
import re
|
| 6 |
+
import gc
|
| 7 |
+
from typing import Tuple, Optional
|
| 8 |
+
|
| 9 |
+
# ---------- Helper functions ----------
|
| 10 |
+
def load_file_bytes_to_df(file) -> Tuple[Optional[pd.DataFrame], Optional[str]]:
|
| 11 |
+
"""
|
| 12 |
+
Read uploaded file bytes into a DataFrame WITHOUT saving to disk.
|
| 13 |
+
Returns (df, error_message).
|
| 14 |
+
"""
|
| 15 |
+
if file is None:
|
| 16 |
+
return None, "No file uploaded."
|
| 17 |
+
try:
|
| 18 |
+
# file is a TemporaryFile-like object in Gradio; read bytes once
|
| 19 |
+
content = file.read()
|
| 20 |
+
# use BytesIO to load into pandas
|
| 21 |
+
# decide by filename or by sniffing bytes
|
| 22 |
+
name = getattr(file, "name", "") or ""
|
| 23 |
+
# Basic heuristic for CSV vs Excel
|
| 24 |
+
if name.lower().endswith(".csv") or b"," in content[:200]:
|
| 25 |
+
df = pd.read_csv(io.BytesIO(content))
|
| 26 |
+
else:
|
| 27 |
+
df = pd.read_excel(io.BytesIO(content))
|
| 28 |
+
except Exception as e:
|
| 29 |
+
return None, f"Error reading file: {e}"
|
| 30 |
+
finally:
|
| 31 |
+
# Immediately try to remove raw bytes if present to minimize memory lifetime
|
| 32 |
+
try:
|
| 33 |
+
del content
|
| 34 |
+
except Exception:
|
| 35 |
+
pass
|
| 36 |
+
gc.collect()
|
| 37 |
+
return df, None
|
| 38 |
+
|
| 39 |
+
def simple_nl_to_action(df: pd.DataFrame, query: str):
|
| 40 |
+
"""Same simple NL parser as before (returns DataFrame or (None, message))."""
|
| 41 |
+
q = (query or "").strip().lower()
|
| 42 |
+
if q == "":
|
| 43 |
+
return None, "Please type a question like: 'show columns', 'show first 5 rows', 'describe column sales', or 'filter where Region = India and Year >= 2021'."
|
| 44 |
+
|
| 45 |
+
if "columns" in q or "show columns" in q or "list columns" in q:
|
| 46 |
+
return pd.DataFrame({"columns": df.columns}), None
|
| 47 |
+
|
| 48 |
+
m = re.search(r"(first|head)\s*(\d+)?", q)
|
| 49 |
+
if "head" in q or "first" in q:
|
| 50 |
+
n = 5
|
| 51 |
+
if m and m.group(2):
|
| 52 |
+
n = int(m.group(2))
|
| 53 |
+
return df.head(n), None
|
| 54 |
+
|
| 55 |
+
if "describe" in q or "summary" in q or "statistics" in q:
|
| 56 |
+
return df.describe(include='all').reset_index(), None
|
| 57 |
+
|
| 58 |
+
m = re.search(r"show (column )?([a-z0-9_ ]+)", q)
|
| 59 |
+
if m:
|
| 60 |
+
col = m.group(2).strip()
|
| 61 |
+
matches = [c for c in df.columns if c.lower() == col.lower()]
|
| 62 |
+
if matches:
|
| 63 |
+
return df[[matches[0]]].head(100), None
|
| 64 |
+
else:
|
| 65 |
+
return None, f"Column '{col}' not found. Try 'show columns' to see exact names."
|
| 66 |
+
|
| 67 |
+
m = re.search(r"filter where ([a-z0-9_ ]+?)\s*(=|>|<|>=|<=)\s*'?(?P<val>[^']+?)'?$", q)
|
| 68 |
+
if m:
|
| 69 |
+
col_text = m.group(1).strip()
|
| 70 |
+
op = m.group(2)
|
| 71 |
+
val = m.group('val').strip()
|
| 72 |
+
matches = [c for c in df.columns if c.lower() == col_text.lower()]
|
| 73 |
+
if not matches:
|
| 74 |
+
return None, f"Column '{col_text}' not found. Use 'show columns' to check names."
|
| 75 |
+
colname = matches[0]
|
| 76 |
+
try:
|
| 77 |
+
if pd.api.types.is_numeric_dtype(df[colname]):
|
| 78 |
+
val_num = float(val)
|
| 79 |
+
if op == "=":
|
| 80 |
+
res = df[df[colname] == val_num]
|
| 81 |
+
elif op == ">":
|
| 82 |
+
res = df[df[colname] > val_num]
|
| 83 |
+
elif op == "<":
|
| 84 |
+
res = df[df[colname] < val_num]
|
| 85 |
+
elif op == ">=":
|
| 86 |
+
res = df[df[colname] >= val_num]
|
| 87 |
+
elif op == "<=":
|
| 88 |
+
res = df[df[colname] <= val_num]
|
| 89 |
+
return res.head(200), None
|
| 90 |
+
else:
|
| 91 |
+
if op == "=":
|
| 92 |
+
res = df[df[colname].astype(str).str.lower() == val.lower()]
|
| 93 |
+
return res.head(200), None
|
| 94 |
+
else:
|
| 95 |
+
return None, f"Operator {op} not supported for non-numeric column '{colname}'."
|
| 96 |
+
except Exception as e:
|
| 97 |
+
return None, f"Error applying filter: {e}"
|
| 98 |
+
|
| 99 |
+
return df.head(10), "Couldn't parse exact request — showing first 10 rows. Try: 'show columns', 'show first 5 rows', 'describe', or 'filter where Column = Value'."
|
| 100 |
+
|
| 101 |
+
# ---------- Processing wrapper ----------
|
| 102 |
+
def process(file, query):
|
| 103 |
+
# Load into memory-only DataFrame
|
| 104 |
+
df, err = load_file_bytes_to_df(file)
|
| 105 |
+
if err:
|
| 106 |
+
# Ensure any partial objects are removed
|
| 107 |
+
try:
|
| 108 |
+
del file
|
| 109 |
+
except Exception:
|
| 110 |
+
pass
|
| 111 |
+
gc.collect()
|
| 112 |
+
return None, err
|
| 113 |
+
|
| 114 |
+
# Run the NLP-to-action
|
| 115 |
+
try:
|
| 116 |
+
res, msg = simple_nl_to_action(df, query)
|
| 117 |
+
# Convert DataFrame result if any to a safe small object (head) to limit memory/time
|
| 118 |
+
if isinstance(res, pd.DataFrame):
|
| 119 |
+
out_df = res.copy() # shallow copy that we will return
|
| 120 |
+
else:
|
| 121 |
+
out_df = None
|
| 122 |
+
except Exception as e:
|
| 123 |
+
out_df = None
|
| 124 |
+
msg = f"Error while processing: {e}"
|
| 125 |
+
|
| 126 |
+
# --- IMPORTANT: Remove references to large objects immediately ---
|
| 127 |
+
try:
|
| 128 |
+
del df
|
| 129 |
+
del file
|
| 130 |
+
except Exception:
|
| 131 |
+
pass
|
| 132 |
+
gc.collect()
|
| 133 |
+
|
| 134 |
+
if isinstance(out_df, pd.DataFrame):
|
| 135 |
+
return out_df, (msg or "OK")
|
| 136 |
+
else:
|
| 137 |
+
return None, (msg or "No result")
|
| 138 |
+
|
| 139 |
+
# ---------- Clear / reset function ----------
|
| 140 |
+
def clear_all():
|
| 141 |
+
"""
|
| 142 |
+
Returns Gradio update objects that clear inputs and outputs.
|
| 143 |
+
This helps remove file from the browser UI and server-side.
|
| 144 |
+
"""
|
| 145 |
+
# gradio update helpers: set inputs/outputs back to empty values
|
| 146 |
+
return (
|
| 147 |
+
gr.File.update(value=None),
|
| 148 |
+
gr.Textbox.update(value=""),
|
| 149 |
+
gr.Dataframe.update(value=None),
|
| 150 |
+
gr.Textbox.update(value=""),
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# ---------- Gradio UI ----------
|
| 154 |
+
with gr.Blocks() as demo:
|
| 155 |
+
gr.Markdown("# Chat-with-CSV — private ephemeral uploads (cleared on Reset)")
|
| 156 |
+
with gr.Row():
|
| 157 |
+
file_input = gr.File(label="Upload CSV or XLSX (will not be saved)", file_count="single")
|
| 158 |
+
query_input = gr.Textbox(label="Ask a question (example: 'show columns' or 'filter where Country = India')", placeholder="Type your question here")
|
| 159 |
+
with gr.Row():
|
| 160 |
+
submit = gr.Button("Run query")
|
| 161 |
+
clear_btn = gr.Button("Clear / Reset (remove uploaded file & results)")
|
| 162 |
+
output_table = gr.Dataframe(headers="auto", label="Result table")
|
| 163 |
+
status = gr.Textbox(label="Status / Messages", interactive=False)
|
| 164 |
+
|
| 165 |
+
submit.click(fn=process, inputs=[file_input, query_input], outputs=[output_table, status])
|
| 166 |
+
# Clear button clears UI (and removes server-side references)
|
| 167 |
+
clear_btn.click(fn=clear_all, inputs=None, outputs=[file_input, query_input, output_table, status])
|
| 168 |
+
|
| 169 |
+
if __name__ == "__main__":
|
| 170 |
+
# Do not enable "share" or persistent caching here; default launch is fine for Spaces
|
| 171 |
+
demo.launch()
|