palwasha-khan commited on
Commit
5fea1a5
Β·
verified Β·
1 Parent(s): d279deb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -29
app.py CHANGED
@@ -3,62 +3,58 @@ import pandas as pd
3
  import traceback
4
  import ast
5
  import re
6
- from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
7
 
8
  st.set_page_config(page_title="Auto Dashboard Generator", layout="wide")
9
- st.title("πŸ“Š Auto Dashboard Generator (DeepSeek Edition)")
10
 
11
  @st.cache_resource(show_spinner=True)
12
- def load_model():
13
- tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/deepseek-coder-1.3b-instruct")
14
- model = AutoModelForCausalLM.from_pretrained("deepseek-ai/deepseek-coder-1.3b-instruct")
15
- return pipeline("text-generation", model=model, tokenizer=tokenizer)
16
 
17
- generator = load_model()
18
 
19
  uploaded_file = st.file_uploader("πŸ“ Upload CSV", type="csv")
20
  prompt = st.text_area(
21
- "πŸ“ What dashboard should I build?",
22
  placeholder="Example: Plot churn rate by contract type and tenure"
23
  )
24
 
25
  if st.button("πŸš€ Generate Dashboard") and uploaded_file and prompt:
26
  df = pd.read_csv(uploaded_file)
27
- st.subheader("πŸ“„ Preview Data")
28
  st.dataframe(df.head())
29
 
30
  sample_data = df.sample(min(len(df), 100)).to_csv(index=False)
31
 
32
  gen_prompt = (
33
- f"You are a Python expert. Use pandas and plotly inside a Streamlit app.\n"
34
  f"Sample data:\n{sample_data}\n\n"
35
  f"Task: {prompt}\n\n"
36
  f"Write Python code starting with `def dashboard():` only.\n"
37
- f"Important: Use the dataframe named `df` already loaded; do NOT load any CSV files inside the function."
38
  )
39
 
40
- with st.spinner("Generating Python code..."):
41
  try:
42
- output = generator(gen_prompt, max_new_tokens=512, do_sample=False, temperature=0.1)[0]['generated_text']
43
 
44
- # Clean the output to extract valid dashboard() function only
45
  if "def dashboard():" in output:
46
- code_part = output.split("def dashboard():", 1)[1]
47
-
48
- code_lines = code_part.splitlines()
49
- cleaned_lines = []
50
- for line in code_lines:
51
- # Stop if line contains markdown or instruction artifacts
52
- if re.search(r'```|` only\.|Note:|Remember to', line):
53
- break
54
- cleaned_lines.append(line)
55
- cleaned_code_body = "\n".join(cleaned_lines)
56
- code = "def dashboard():\n" + cleaned_code_body
57
  else:
58
- st.error("🚨 No dashboard() function generated.")
59
  st.code(output)
60
  st.stop()
61
 
 
 
 
 
 
 
 
 
 
62
  st.subheader("🧠 Generated Code")
63
  st.code(code, language="python")
64
 
@@ -71,14 +67,14 @@ if st.button("πŸš€ Generate Dashboard") and uploaded_file and prompt:
71
  st.code(code, language="python")
72
  st.stop()
73
 
74
- # Execute code safely, passing df, st, and pd
75
  exec_globals = {"df": df, "st": st, "pd": pd}
76
  exec(code, exec_globals)
77
 
78
  if "dashboard" in exec_globals:
79
  exec_globals["dashboard"]()
80
  else:
81
- st.warning("⚠️ No dashboard() function found.")
82
  except Exception as e:
83
- st.error("🚨 Generation or execution error:")
84
  st.text(traceback.format_exc())
 
3
  import traceback
4
  import ast
5
  import re
6
+ from transformers import pipeline
7
 
8
  st.set_page_config(page_title="Auto Dashboard Generator", layout="wide")
9
+ st.title("πŸ“Š Auto Dashboard Generator (Simplified CodeGen)")
10
 
11
  @st.cache_resource(show_spinner=True)
12
+ def load_generator():
13
+ return pipeline("text-generation", model="Salesforce/codegen-350M-mono")
 
 
14
 
15
+ generator = load_generator()
16
 
17
  uploaded_file = st.file_uploader("πŸ“ Upload CSV", type="csv")
18
  prompt = st.text_area(
19
+ "πŸ“ What dashboard should I build?",
20
  placeholder="Example: Plot churn rate by contract type and tenure"
21
  )
22
 
23
  if st.button("πŸš€ Generate Dashboard") and uploaded_file and prompt:
24
  df = pd.read_csv(uploaded_file)
25
+ st.subheader("πŸ“„ Data Preview")
26
  st.dataframe(df.head())
27
 
28
  sample_data = df.sample(min(len(df), 100)).to_csv(index=False)
29
 
30
  gen_prompt = (
31
+ f"You are a Python expert. Use pandas and plotly in Streamlit.\n"
32
  f"Sample data:\n{sample_data}\n\n"
33
  f"Task: {prompt}\n\n"
34
  f"Write Python code starting with `def dashboard():` only.\n"
35
+ f"Important: Use the existing `df` DataFrame; do NOT load CSV files."
36
  )
37
 
38
+ with st.spinner("Generating code..."):
39
  try:
40
+ output = generator(gen_prompt, max_new_tokens=512, do_sample=False, temperature=0.1)[0]["generated_text"]
41
 
 
42
  if "def dashboard():" in output:
43
+ code = "def dashboard():" + output.split("def dashboard():", 1)[1]
 
 
 
 
 
 
 
 
 
 
44
  else:
45
+ st.error("🚨 No function named `dashboard()` found in generated text.")
46
  st.code(output)
47
  st.stop()
48
 
49
+ # Clean residues
50
+ code_lines = code.splitlines()
51
+ cleaned_lines = []
52
+ for line in code_lines:
53
+ if re.search(r'```|` only\.|Note:|Remember to', line):
54
+ break
55
+ cleaned_lines.append(line)
56
+ code = "\n".join(cleaned_lines)
57
+
58
  st.subheader("🧠 Generated Code")
59
  st.code(code, language="python")
60
 
 
67
  st.code(code, language="python")
68
  st.stop()
69
 
70
+ # Execute
71
  exec_globals = {"df": df, "st": st, "pd": pd}
72
  exec(code, exec_globals)
73
 
74
  if "dashboard" in exec_globals:
75
  exec_globals["dashboard"]()
76
  else:
77
+ st.warning("⚠️ `dashboard()` function didn't run.")
78
  except Exception as e:
79
+ st.error("🚨 Error during generation or execution:")
80
  st.text(traceback.format_exc())