razaali10 commited on
Commit
a4aef68
·
verified ·
1 Parent(s): b5cb4e1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -72
app.py CHANGED
@@ -1,19 +1,10 @@
1
  import streamlit as st
2
  import wntr
3
- from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
4
  import tempfile
5
  import os
6
  import re
 
7
 
8
- def answer():
9
- return 42 # Returns an integer
10
-
11
- Only return code, no explanations. Example:
12
- ```python
13
- def answer():
14
- # Your code
15
- return result
16
- @st.cache_resource
17
  @st.cache_resource
18
  def load_llm(model_name="tiiuae/falcon-rw-1b"):
19
  tokenizer = AutoTokenizer.from_pretrained(model_name)
@@ -23,11 +14,10 @@ def load_llm(model_name="tiiuae/falcon-rw-1b"):
23
  pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
24
  return pipe
25
 
26
- def simulate_epanet(inp_path):
27
- wn = wntr.network.WaterNetworkModel(inp_path)
28
- sim = wntr.sim.WNTRSimulator(wn)
29
- results = sim.run_sim()
30
- return wn, results
31
  def generate_python_code(pipe, prompt):
32
  full_prompt = f"""You are a Python expert using the `wntr` library.
33
  The user asks: "{prompt}"
@@ -36,74 +26,53 @@ You have the following variables:
36
  - `wn`: a `WaterNetworkModel` object from the EPANET `.inp` file.
37
  - `results`: simulation output from `wntr.sim`.
38
 
39
- You have these variables:
40
- - `wn`: the EPANET WaterNetworkModel
41
- - `results`: the simulation output
42
-
43
- Write a Python function named `answer()` that answers the question and returns a single result.
44
 
45
- Begin your function with:
 
46
  def answer():
 
 
 
47
  """
48
- esponse = pipe(full_prompt, max_new_tokens=300, do_sample=True)[0]["generated_text"]
49
-
50
- # Extract code block only
51
- code_block = re.findall(r"```python(.*?)```", response, re.DOTALL)
52
- if code_block:
53
- return code_block[0].strip()
54
- else:
55
- # fallback: look for `def answer():` manually
56
- return extract_code(response)
57
-
58
- def extract_code(text):
59
- lines = text.splitlines()
60
- code_lines = []
61
- in_func = False
62
- for line in lines:
63
- if line.strip().startswith("def answer("):
64
- in_func = True
65
- if in_func:
66
- code_lines.append(line)
67
- if in_func and line.strip() == "":
68
- break
69
- return "\n".join(code_lines)
70
 
71
  def run_answer_function(code, wn, results):
72
  local_vars = {"wn": wn, "results": results}
73
- exec(code, {}, local_vars)
74
- return local_vars["answer"]()
 
 
 
75
 
76
- # --- Streamlit UI ---
77
- st.title("💧 EPANET + LLM with Streamlit")
78
 
79
- uploaded_file = st.file_uploader("Upload your EPANET .inp file", type=["inp"])
80
- user_prompt = st.text_input("Ask a question (e.g., 'What's the max pressure at node 101?')")
81
 
82
- if uploaded_file and user_prompt:
83
- with tempfile.NamedTemporaryFile(delete=False, suffix=".inp") as temp:
84
- temp.write(uploaded_file.read())
85
- temp_path = temp.name
86
 
87
- with st.spinner("Simulating EPANET model..."):
88
- try:
89
- wn, results = simulate_epanet(temp_path)
90
- except Exception as e:
91
- st.error(f"Failed to simulate EPANET model: {e}")
92
- st.stop()
93
 
94
- with st.spinner("Loading model..."):
95
- pipe = load_llm()
96
 
97
- with st.spinner("Generating Python code..."):
98
- code = generate_python_code(pipe, user_prompt)
99
- st.code(code, language="python")
100
 
101
- with st.spinner("Running generated code..."):
102
- try:
103
- output = run_answer_function(code, wn, results)
104
- st.success("Answer:")
105
- st.write(output)
106
- except Exception as e:
107
- st.error(f"Error running generated code: {e}")
108
 
109
- os.remove(temp_path)
 
1
  import streamlit as st
2
  import wntr
 
3
  import tempfile
4
  import os
5
  import re
6
+ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
7
 
 
 
 
 
 
 
 
 
 
8
  @st.cache_resource
9
  def load_llm(model_name="tiiuae/falcon-rw-1b"):
10
  tokenizer = AutoTokenizer.from_pretrained(model_name)
 
14
  pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
15
  return pipe
16
 
17
+ def extract_code(response):
18
+ match = re.search(r"def answer\(\):[\s\S]+?return.+", response)
19
+ return match.group(0) if match else "def answer():\n return 'Error: No valid function found'"
20
+
 
21
  def generate_python_code(pipe, prompt):
22
  full_prompt = f"""You are a Python expert using the `wntr` library.
23
  The user asks: "{prompt}"
 
26
  - `wn`: a `WaterNetworkModel` object from the EPANET `.inp` file.
27
  - `results`: simulation output from `wntr.sim`.
28
 
29
+ Write a single function named `answer()` that returns the answer as a Python object (int, float, str, or list).
 
 
 
 
30
 
31
+ Only return code, no explanations. Example:
32
+ ```python
33
  def answer():
34
+ # Your code
35
+ return result
36
+ ```
37
  """
38
+ response = pipe(full_prompt, max_new_tokens=300, do_sample=True)[0]["generated_text"]
39
+ code_block = re.findall(r"```python(.*?)```", response, re.DOTALL)
40
+ if code_block:
41
+ return code_block[0].strip()
42
+ else:
43
+ return extract_code(response)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  def run_answer_function(code, wn, results):
46
  local_vars = {"wn": wn, "results": results}
47
+ try:
48
+ exec(code, {}, local_vars)
49
+ return local_vars["answer"]()
50
+ except Exception as e:
51
+ return f"⚠️ Error in generated code: {e}"
52
 
53
+ st.set_page_config(page_title="EPANET + LLM", layout="wide")
54
+ st.title("💧 EPANET + LLM (via WNTR + Falcon LLM)")
55
 
56
+ uploaded_file = st.file_uploader("Upload EPANET .inp file", type=["inp"])
57
+ question = st.text_input("Ask a question about your water network model")
58
 
59
+ if uploaded_file and question:
60
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".inp") as tmp:
61
+ tmp.write(uploaded_file.read())
62
+ tmp_path = tmp.name
63
 
64
+ wn = wntr.network.WaterNetworkModel(tmp_path)
65
+ sim = wntr.sim.EpanetSimulator(wn)
66
+ results = sim.run_sim()
 
 
 
67
 
68
+ pipe = load_llm()
69
+ code = generate_python_code(pipe, question)
70
 
71
+ st.subheader("🧠 Generated Code")
72
+ st.code(code, language="python")
 
73
 
74
+ st.subheader("📊 Output")
75
+ output = run_answer_function(code, wn, results)
76
+ st.write(output)
 
 
 
 
77
 
78
+ os.remove(tmp_path)