syeda-Rija20 commited on
Commit
9b5bd69
Β·
verified Β·
1 Parent(s): 526ae85

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -65
app.py CHANGED
@@ -46,98 +46,125 @@
46
  import streamlit as st
47
  import sympy as sp
48
  import pandas as pd
 
49
 
50
- # Page config
 
 
51
  st.set_page_config(page_title="AI Logic Solver", layout="centered")
52
 
53
- # Title
54
  st.title("🧩 AI Logic Solver")
55
- st.markdown("Solve logical expressions with **steps + truth table**")
56
 
57
- # Instructions
58
- st.info("Use: ~ (NOT), & (AND), | (OR), >> (IMPLIES)")
59
-
60
- # Quick input buttons
61
- col1, col2, col3, col4 = st.columns(4)
62
 
 
 
 
63
  if "expr" not in st.session_state:
64
  st.session_state.expr = ""
65
 
66
- if col1.button("p"):
67
- st.session_state.expr += "p"
68
- if col2.button("q"):
69
- st.session_state.expr += "q"
70
- if col3.button("r"):
71
- st.session_state.expr += "r"
72
- if col4.button("Clear"):
73
- st.session_state.expr = ""
74
-
75
- col5, col6, col7, col8 = st.columns(4)
76
-
77
- if col5.button("~"):
78
- st.session_state.expr += "~"
79
- if col6.button("&"):
80
- st.session_state.expr += " & "
81
- if col7.button("|"):
82
- st.session_state.expr += " | "
83
- if col8.button(">>"):
84
- st.session_state.expr += " >> "
85
 
86
- # Input box
87
- expr_input = st.text_input("Enter expression:", value=st.session_state.expr)
88
 
89
- # Process
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  if expr_input:
91
  try:
92
- # Define symbols
93
- p, q, r = sp.symbols('p q r')
94
 
95
- # Convert expression
96
- expr = sp.sympify(expr_input)
 
97
 
98
- st.success("βœ… Expression parsed successfully!")
 
99
 
100
- # =========================
101
- # STEP-BY-STEP (Basic)
102
- # =========================
103
- st.subheader("🧠 Step-by-Step Simplification")
104
-
105
- steps = []
106
 
107
- # Step 1: Original
108
- steps.append(f"Original: {expr}")
109
 
110
- # Step 2: Remove implication
111
- expr_no_impl = expr.replace(
112
- lambda x: isinstance(x, sp.Implies),
113
- lambda x: ~x.args[0] | x.args[1]
114
- )
115
- steps.append(f"Remove implication: {expr_no_impl}")
116
 
117
- # Step 3: Simplify
118
- simplified = sp.simplify_logic(expr_no_impl)
119
- steps.append(f"Simplified: {simplified}")
 
120
 
121
- for step in steps:
122
- st.write("➑️", step)
123
-
124
- # Final simplified
125
- st.subheader("πŸ“Œ Final Simplified Expression:")
126
  st.write(simplified)
127
 
128
- # =========================
129
  # TRUTH TABLE
130
- # =========================
131
  st.subheader("πŸ“Š Truth Table")
132
 
133
  variables = sorted(expr.free_symbols, key=lambda x: str(x))
134
  rows = []
135
 
136
  for values in range(2**len(variables)):
137
- combination = list(map(int, bin(values)[2:].zfill(len(variables))))
138
- subs = dict(zip(variables, combination))
139
 
140
- result = bool(expr.subs(subs)) # βœ… FIXED
141
 
142
  row = {str(var): val for var, val in subs.items()}
143
  row["Result"] = int(result)
@@ -148,12 +175,20 @@ if expr_input:
148
 
149
  # Download option
150
  st.download_button(
151
- "πŸ“₯ Download Truth Table",
152
  df.to_csv(index=False),
153
  file_name="truth_table.csv",
154
  mime="text/csv"
155
  )
156
 
157
  except Exception as e:
158
- st.error(f"❌ Invalid expression: {str(e)}")
159
- st.info("πŸ’‘ Example: ~(p & q) >> r")
 
 
 
 
 
 
 
 
 
46
  import streamlit as st
47
  import sympy as sp
48
  import pandas as pd
49
+ from sympy.logic.boolalg import Xor
50
 
51
+ # -----------------------
52
+ # Page Setup
53
+ # -----------------------
54
  st.set_page_config(page_title="AI Logic Solver", layout="centered")
55
 
 
56
  st.title("🧩 AI Logic Solver")
57
+ st.markdown("Solve logical expressions easily (with truth table)")
58
 
59
+ st.info("Use: ~ (NOT), & (AND), | (OR), >> (IMPLIES), ^ (XOR)")
 
 
 
 
60
 
61
+ # -----------------------
62
+ # Session State
63
+ # -----------------------
64
  if "expr" not in st.session_state:
65
  st.session_state.expr = ""
66
 
67
+ # -----------------------
68
+ # BUTTON FUNCTIONS
69
+ # -----------------------
70
+ def add(val):
71
+ st.session_state.expr += val
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
+ def clear():
74
+ st.session_state.expr = ""
75
 
76
+ def backspace():
77
+ st.session_state.expr = st.session_state.expr[:-1]
78
+
79
+ # -----------------------
80
+ # SIMPLE BUTTON UI
81
+ # -----------------------
82
+ st.subheader("πŸ”˜ Build Expression")
83
+
84
+ col1, col2, col3 = st.columns(3)
85
+
86
+ with col1:
87
+ if st.button("p"):
88
+ add("p")
89
+ if st.button("q"):
90
+ add("q")
91
+ if st.button("r"):
92
+ add("r")
93
+
94
+ with col2:
95
+ if st.button("AND (&)"):
96
+ add(" & ")
97
+ if st.button("OR (|)"):
98
+ add(" | ")
99
+ if st.button("NOT (~)"):
100
+ add("~")
101
+
102
+ with col3:
103
+ if st.button("IMPLIES (>>)"):
104
+ add(" >> ")
105
+ if st.button("XOR (^)"):
106
+ add(" ^ ")
107
+ if st.button("( )"):
108
+ add("()")
109
+
110
+ # Extra controls
111
+ col4, col5 = st.columns(2)
112
+ with col4:
113
+ if st.button("β¬… Backspace"):
114
+ backspace()
115
+ with col5:
116
+ if st.button("πŸ—‘ Clear"):
117
+ clear()
118
+
119
+ # -----------------------
120
+ # INPUT BOX
121
+ # -----------------------
122
+ expr_input = st.text_input("✏️ Your Expression:", value=st.session_state.expr)
123
+
124
+ # -----------------------
125
+ # PROCESSING
126
+ # -----------------------
127
  if expr_input:
128
  try:
129
+ # Clean input
130
+ expr_clean = expr_input.strip()
131
 
132
+ # Check parentheses
133
+ if expr_clean.count("(") != expr_clean.count(")"):
134
+ st.warning("⚠️ Unbalanced parentheses!")
135
 
136
+ # Replace XOR
137
+ expr_clean = expr_clean.replace("^", "Xor")
138
 
139
+ # Define symbols
140
+ p, q, r = sp.symbols('p q r')
 
 
 
 
141
 
142
+ # Parse expression
143
+ expr = sp.sympify(expr_clean, locals={"Xor": Xor})
144
 
145
+ st.success("βœ… Expression is valid!")
 
 
 
 
 
146
 
147
+ # -----------------------
148
+ # SIMPLIFY
149
+ # -----------------------
150
+ simplified = sp.simplify_logic(expr)
151
 
152
+ st.subheader("πŸ“Œ Simplified Expression:")
 
 
 
 
153
  st.write(simplified)
154
 
155
+ # -----------------------
156
  # TRUTH TABLE
157
+ # -----------------------
158
  st.subheader("πŸ“Š Truth Table")
159
 
160
  variables = sorted(expr.free_symbols, key=lambda x: str(x))
161
  rows = []
162
 
163
  for values in range(2**len(variables)):
164
+ combo = list(map(int, bin(values)[2:].zfill(len(variables))))
165
+ subs = dict(zip(variables, combo))
166
 
167
+ result = bool(expr.subs(subs)) # stable
168
 
169
  row = {str(var): val for var, val in subs.items()}
170
  row["Result"] = int(result)
 
175
 
176
  # Download option
177
  st.download_button(
178
+ "πŸ“₯ Download CSV",
179
  df.to_csv(index=False),
180
  file_name="truth_table.csv",
181
  mime="text/csv"
182
  )
183
 
184
  except Exception as e:
185
+ st.error("❌ Invalid expression!")
186
+
187
+ st.write("πŸ” Error detail:")
188
+ st.code(str(e))
189
+
190
+ st.info("πŸ’‘ Try examples:")
191
+ st.code("~(p & q) >> r")
192
+ st.code("p | q")
193
+ st.code("p ^ q")
194
+ st.code("(p & q) | (r)")