Spaces:
Sleeping

clementBE commited on
Commit
b45b70b
Β·
verified Β·
1 Parent(s): 561360f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -67
app.py CHANGED
@@ -1,76 +1,46 @@
1
  import gradio as gr
2
  import pandas as pd
3
- from transformers import pipeline
4
- from pathlib import Path
5
-
6
- # === Load FLAN-T5 Model ===
7
- generator = pipeline("text2text-generation", model="google/flan-t5-base", device=-1)
8
-
9
- # === Shared state ===
10
- uploaded_df = {}
11
-
12
- # === Helper: Format table sample for readable input ===
13
- def format_dataframe_summary(df, max_rows=5, max_cols=8):
14
- if df.empty:
15
- return "No data to show."
16
-
17
- df = df.fillna("").astype(str)
18
- cols = df.columns[:max_cols]
19
- header = ", ".join(cols)
20
- rows = [" - " + ", ".join(row) for row in df[cols].head(max_rows).values.tolist()]
21
- return f"Columns: {header}\nSample:\n" + "\n".join(rows)
22
-
23
- # === Upload file handler ===
24
- def upload_file(file):
25
- try:
26
- if file.name.endswith(".csv"):
27
- df = pd.read_csv(file.name)
28
- elif file.name.endswith(".xlsx"):
29
- df = pd.read_excel(file.name)
30
- else:
31
- return "Unsupported file format. Please upload a CSV or XLSX.", None
32
- uploaded_df["df"] = df
33
- return "βœ… File uploaded successfully.", df
34
- except Exception as e:
35
- return f"❌ Error: {e}", None
36
-
37
- # === Prompt handler ===
38
- def generate_ai_summary(prompt):
39
- df = uploaded_df.get("df")
40
- if df is None:
41
- return "⚠️ No file uploaded yet."
42
- if not prompt.strip():
43
- return "⚠️ Please ask a question."
44
- sample = format_dataframe_summary(df)
45
- full_prompt = f"{prompt.strip()}\n\n{sample}"
46
- result = generator(full_prompt, max_length=256)[0]["generated_text"]
47
- return result
48
-
49
- # === Gradio UI ===
50
- with gr.Blocks(title="🧠 Smart Table AI") as demo:
51
- gr.Markdown("## πŸ“Š Smart Table Assistant with FLAN-T5\nUpload your data and ask a question.")
52
 
53
  with gr.Row():
54
- file = gr.File(label="πŸ“ Upload CSV or Excel file")
55
- upload_msg = gr.Textbox(label="πŸ“„ Upload Status", interactive=False)
56
-
57
- table_preview = gr.Dataframe(
58
- label="πŸ“‹ Table Preview",
59
- interactive=False,
60
- wrap=True
61
- )
62
 
63
- file.upload(fn=upload_file, inputs=file, outputs=[upload_msg, table_preview])
64
-
65
- prompt = gr.Textbox(
66
- label="πŸ’¬ Ask a question about the table",
67
- placeholder="Ex: What is the most commented video? Or: Who are the top 5 authors?",
68
- lines=2
69
- )
70
 
71
- answer_btn = gr.Button("πŸš€ Generate Answer")
72
- output = gr.Textbox(label="πŸ€– AI Response")
73
 
74
- answer_btn.click(fn=generate_ai_summary, inputs=prompt, outputs=output)
 
75
 
76
  demo.launch()
 
1
  import gradio as gr
2
  import pandas as pd
3
+ import torch
4
+ from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, pipeline
5
+
6
+ # Use a small model under 900MB. We use google/flan-t5-small (~300MB)
7
+ model_name = "google/flan-t5-small"
8
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
9
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
10
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
+ model.to(device)
12
+
13
+ def load_table(file):
14
+ if file.name.endswith(".csv"):
15
+ df = pd.read_csv(file.name)
16
+ else:
17
+ df = pd.read_excel(file.name)
18
+ preview = df.iloc[:5, :8] if df.shape[1] > 8 else df.head()
19
+ return df, preview
20
+
21
+ def ask_question(df, question):
22
+ sample = df.iloc[:5].to_string(index=False)
23
+ prompt = f"Given this table:\n{sample}\nAnswer this question: {question}"
24
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512).to(device)
25
+ outputs = model.generate(**inputs, max_new_tokens=100)
26
+ return tokenizer.decode(outputs[0], skip_special_tokens=True)
27
+
28
+ df_state = gr.State()
29
+
30
+ with gr.Blocks() as demo:
31
+ gr.Markdown("## Ask Questions About Your Table (with FLAN-T5-Small)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  with gr.Row():
34
+ file_input = gr.File(label="Upload CSV or Excel file")
35
+ table_preview = gr.Dataframe(label="Table Preview")
 
 
 
 
 
 
36
 
37
+ with gr.Row():
38
+ question = gr.Textbox(placeholder="Ask a question about the table", label="Your question")
39
+ ask_btn = gr.Button("Ask")
 
 
 
 
40
 
41
+ answer = gr.Textbox(label="Answer", lines=3)
 
42
 
43
+ file_input.change(fn=load_table, inputs=file_input, outputs=[df_state, table_preview])
44
+ ask_btn.click(fn=ask_question, inputs=[df_state, question], outputs=answer)
45
 
46
  demo.launch()