Entz commited on
Commit
15b84bc
·
verified ·
1 Parent(s): fe3f785

Upload index.py

Browse files
Files changed (1) hide show
  1. index.py +79 -93
index.py CHANGED
@@ -5,6 +5,8 @@ import time
5
  import random
6
  import os
7
 
 
 
8
  API_URL = os.getenv("API_URL")
9
 
10
  TRANSITION_MESSAGES = [
@@ -15,41 +17,14 @@ TRANSITION_MESSAGES = [
15
  "Onward to question {number}!"
16
  ]
17
 
18
- TAB1_FILE = "tab1.txt"
19
- TAB1_FALLBACK = """
20
- # Registration System Demo
21
-
22
- Data quality issues have long plagued council databases, burdening W2 workflow teams (e.g. the Assisted Travel Team's dashboard I am working on), data analysts, and engineers with manual cleaning and validation. This pilot explores how AI-driven workflows can address these pain points by streamlining user registration, ensuring accurate data collection, and reducing validation overhead.
23
-
24
- *If you see this message, `tab1.txt` was not found. Please upload it to the app directory for the full intro page.*
25
- """
26
-
27
- def read_content_from_file(file_path):
28
- try:
29
- import os
30
- st.write("Current working directory:", os.getcwd())
31
- st.write("Files in directory:", os.listdir())
32
- with open(file_path, 'r') as file:
33
- return file.read()
34
- except FileNotFoundError:
35
- return TAB1_FALLBACK
36
-
37
- def reset_registration_state():
38
- for key in [
39
- "session_id", "current_question", "answer", "feedback", "summary",
40
- "skip_address", "skip_phone", "prev_question", "question_number",
41
- "edit_field_values"
42
- ]:
43
- if key in st.session_state:
44
- del st.session_state[key]
45
-
46
  def start_registration():
47
- reset_registration_state()
48
  try:
49
  headers = {"Origin": "https://entz-council-3.hf.space"}
50
- response = requests.post(f"{API_URL}/start_registration", headers=headers, timeout=2)
51
  response.raise_for_status()
52
  data = response.json()
 
53
  st.session_state.session_id = data["session_id"]
54
  st.session_state.current_question = data["message"]
55
  st.session_state.feedback = ""
@@ -59,10 +34,14 @@ def start_registration():
59
  st.session_state.skip_phone = False
60
  st.session_state.prev_question = ""
61
  st.session_state.question_number = 1
62
- st.session_state.edit_field_values = {}
63
  except requests.RequestException as e:
 
64
  st.error(f"Error starting registration: {e}")
65
-
 
 
 
 
66
  def submit_response():
67
  if not st.session_state.session_id:
68
  st.error("No active session. Please start registration.")
@@ -77,10 +56,12 @@ def submit_response():
77
  "answer": st.session_state.answer,
78
  "skip_steps": skip_steps
79
  }
 
80
  try:
81
  response = requests.post(f"{API_URL}/submit_response", json=payload)
82
  response.raise_for_status()
83
  data = response.json()
 
84
  if data.get("message") == "Registration complete!":
85
  st.session_state.summary = data["summary"]
86
  st.session_state.current_question = ""
@@ -97,6 +78,7 @@ def submit_response():
97
  st.session_state.skip_phone = False
98
  st.rerun()
99
  except requests.RequestException as e:
 
100
  st.error(f"Error submitting response: {e}")
101
 
102
  def edit_field(field, value):
@@ -108,10 +90,12 @@ def edit_field(field, value):
108
  "field_to_edit": field,
109
  "new_value": value
110
  }
 
111
  try:
112
  response = requests.post(f"{API_URL}/edit_field", json=payload)
113
  response.raise_for_status()
114
  data = response.json()
 
115
  st.session_state.feedback = data.get("validation_feedback", "")
116
  st.session_state.summary = data.get("summary", st.session_state.summary)
117
  if data.get("message") == "Needs clarification":
@@ -120,57 +104,63 @@ def edit_field(field, value):
120
  st.success("Database updated.")
121
  st.rerun()
122
  except requests.RequestException as e:
 
123
  st.error(f"Error editing field: {e}")
124
 
125
- def ensure_registration_state():
126
- if "session_id" not in st.session_state:
127
- start_registration()
128
- if "edit_field_values" not in st.session_state:
129
- st.session_state.edit_field_values = {}
130
-
131
- def run_registration_app():
132
- ensure_registration_state()
133
- st.title("AI-Powered Registration System")
134
- st.markdown("*** If 403 or other connection errors, please refresh the page every 1 minute, because the backend server is being spun up. Developed by [email protected]**")
135
-
136
- if st.session_state.summary:
137
- st.success("Registration Complete!")
138
- st.subheader("Summary")
139
- for key, value in st.session_state.summary.items():
140
- edit_key = f"edit_{key}"
141
- if edit_key not in st.session_state.edit_field_values:
142
- st.session_state.edit_field_values[edit_key] = ""
143
- st.write(f"**{key}**: {value}")
144
- st.session_state.edit_field_values[edit_key] = st.text_input(
145
- f"Edit {key}",
146
- value=st.session_state.edit_field_values[edit_key],
147
- key=edit_key
148
- )
149
- if st.button(f"Update {key}", key=f"update_{key}"):
150
- edit_field(key, st.session_state.edit_field_values[edit_key])
151
-
152
- col1, col2 = st.columns(2)
153
- with col1:
154
- if st.button("Next Registration", key="next_reg"):
155
- start_registration()
156
- st.rerun()
157
- with col2:
158
- if st.button("End Session", key="end_sess"):
159
- reset_registration_state()
160
- st.success("Session ended. Please select 'Registration' tab to start again.")
161
-
162
- elif st.session_state.current_question:
163
- if st.session_state.feedback and st.session_state.feedback != "Registration complete!":
 
 
 
 
 
164
  st.error(st.session_state.feedback)
165
  if st.session_state.prev_question and st.session_state.prev_question != st.session_state.current_question:
166
  transition_msg = random.choice(TRANSITION_MESSAGES).format(number=st.session_state.question_number)
167
  st.info(transition_msg)
168
  time.sleep(1)
169
-
170
  st.subheader(f"Question {st.session_state.question_number}: {st.session_state.current_question}")
171
 
172
- is_address_question = st.session_state.current_question.strip().lower() == "what is your address?"
173
- is_phone_question = st.session_state.current_question.strip().lower() == "what is your phone number?"
174
 
175
  if is_address_question or is_phone_question:
176
  st.info(
@@ -179,27 +169,23 @@ def run_registration_app():
179
  f"- For phone: Use 10 digits for landlines (e.g., 020 123 4567) or 11 digits for mobiles starting with 07 (e.g., 07700 900 123). Do not use +44 or other region numbers."
180
  )
181
  if is_address_question:
182
- st.session_state.skip_address = st.checkbox("Skip this question", value=st.session_state.skip_address, key="skip_address_checkbox")
183
  elif is_phone_question:
184
- st.session_state.skip_phone = st.checkbox("Skip this question", value=st.session_state.skip_phone, key="skip_phone_checkbox")
185
 
186
- answer_key = f"answer_input_q{st.session_state.question_number}"
187
- st.session_state.answer = st.text_input(
188
- "Your Answer",
189
- value=st.session_state.answer,
190
- key=answer_key
191
- )
 
 
 
192
 
193
- if st.button("Submit", key=f"submit_button_q{st.session_state.question_number}"):
194
- submit_response()
195
 
 
 
196
  else:
197
- st.info("Initializing registration session...")
198
-
199
- tab1, tab2 = st.tabs(["Intro", "Registration"])
200
-
201
- with tab1:
202
- st.markdown(read_content_from_file(TAB1_FILE))
203
-
204
- with tab2:
205
- run_registration_app()
 
5
  import random
6
  import os
7
 
8
+
9
+
10
  API_URL = os.getenv("API_URL")
11
 
12
  TRANSITION_MESSAGES = [
 
17
  "Onward to question {number}!"
18
  ]
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  def start_registration():
21
+ print("Starting registration...")
22
  try:
23
  headers = {"Origin": "https://entz-council-3.hf.space"}
24
+ response = requests.post(f"{API_URL}/start_registration", headers=headers, timeout=1)
25
  response.raise_for_status()
26
  data = response.json()
27
+ print("API Response:", data)
28
  st.session_state.session_id = data["session_id"]
29
  st.session_state.current_question = data["message"]
30
  st.session_state.feedback = ""
 
34
  st.session_state.skip_phone = False
35
  st.session_state.prev_question = ""
36
  st.session_state.question_number = 1
 
37
  except requests.RequestException as e:
38
+ print(f"Error starting registration: {e}, Response: {getattr(e.response, 'text', 'No response')}")
39
  st.error(f"Error starting registration: {e}")
40
+
41
+
42
+
43
+
44
+
45
  def submit_response():
46
  if not st.session_state.session_id:
47
  st.error("No active session. Please start registration.")
 
56
  "answer": st.session_state.answer,
57
  "skip_steps": skip_steps
58
  }
59
+ print("Submitting response with payload:", payload)
60
  try:
61
  response = requests.post(f"{API_URL}/submit_response", json=payload)
62
  response.raise_for_status()
63
  data = response.json()
64
+ print("API Response:", data)
65
  if data.get("message") == "Registration complete!":
66
  st.session_state.summary = data["summary"]
67
  st.session_state.current_question = ""
 
78
  st.session_state.skip_phone = False
79
  st.rerun()
80
  except requests.RequestException as e:
81
+ print(f"Error submitting response: {e}")
82
  st.error(f"Error submitting response: {e}")
83
 
84
  def edit_field(field, value):
 
90
  "field_to_edit": field,
91
  "new_value": value
92
  }
93
+ print("Editing field with payload:", payload)
94
  try:
95
  response = requests.post(f"{API_URL}/edit_field", json=payload)
96
  response.raise_for_status()
97
  data = response.json()
98
+ print("API Response:", data)
99
  st.session_state.feedback = data.get("validation_feedback", "")
100
  st.session_state.summary = data.get("summary", st.session_state.summary)
101
  if data.get("message") == "Needs clarification":
 
104
  st.success("Database updated.")
105
  st.rerun()
106
  except requests.RequestException as e:
107
+ print(f"Error editing field: {e}")
108
  st.error(f"Error editing field: {e}")
109
 
110
+ if "session_state" not in st.session_state:
111
+ st.session_state.session_state = {}
112
+ st.session_state.session_id = None
113
+ st.session_state.current_question = ""
114
+ st.session_state.answer = ""
115
+ st.session_state.feedback = ""
116
+ st.session_state.summary = None
117
+ st.session_state.skip_address = False
118
+ st.session_state.skip_phone = False
119
+ st.session_state.prev_question = ""
120
+ st.session_state.question_number = 1
121
+
122
+ if st.session_state.session_id is None:
123
+ start_registration()
124
+
125
+ # Read content from text files
126
+ def read_content_from_file(file_path):
127
+ try:
128
+ with open(file_path, 'r') as file:
129
+ return file.read()
130
+ except FileNotFoundError:
131
+ return f"Error: {file_path} not found."
132
+
133
+ st.title("AI-Powered Registration System")
134
+ st.markdown("If 403 or other connection errors, please refresh the page every 1 minute, because the backend server is being spun up. Developed by [email protected]")
135
+
136
+ if st.session_state.summary:
137
+ st.success("Registration Complete!")
138
+ st.subheader("Summary")
139
+ for key, value in st.session_state.summary.items():
140
+ st.write(f"**{key}**: {value}")
141
+ new_value = st.text_input(f"Edit {key}", key=f"edit_{key}")
142
+ if st.button(f"Update {key}", key=f"update_{key}"):
143
+ edit_field(key, new_value)
144
+ col1, col2 = st.columns(2)
145
+ with col1:
146
+ if st.button("Next Registration", key="next_reg", on_click=start_registration):
147
+ pass
148
+ with col2:
149
+ if st.button("End Session", key="end_sess", on_click=start_registration):
150
+ pass
151
+ else:
152
+ if st.session_state.current_question:
153
+ if st.session_state.feedback:
154
  st.error(st.session_state.feedback)
155
  if st.session_state.prev_question and st.session_state.prev_question != st.session_state.current_question:
156
  transition_msg = random.choice(TRANSITION_MESSAGES).format(number=st.session_state.question_number)
157
  st.info(transition_msg)
158
  time.sleep(1)
159
+ print(f"Displaying question: {st.session_state.current_question}")
160
  st.subheader(f"Question {st.session_state.question_number}: {st.session_state.current_question}")
161
 
162
+ is_address_question = st.session_state.current_question == "What is your address?"
163
+ is_phone_question = st.session_state.current_question == "What is your phone number?"
164
 
165
  if is_address_question or is_phone_question:
166
  st.info(
 
169
  f"- For phone: Use 10 digits for landlines (e.g., 020 123 4567) or 11 digits for mobiles starting with 07 (e.g., 07700 900 123). Do not use +44 or other region numbers."
170
  )
171
  if is_address_question:
172
+ st.session_state.skip_address = st.checkbox("Skip this question", value=st.session_state.skip_address)
173
  elif is_phone_question:
174
+ st.session_state.skip_phone = st.checkbox("Skip this question", value=st.session_state.skip_phone)
175
 
176
+ st.components.v1.html("""
177
+ document.addEventListener('keypress', function(e) {
178
+ if (e.key === 'Enter' && document.activeElement.tagName === 'INPUT') {
179
+ e.preventDefault();
180
+ const submitButton = document.querySelector('button[key="submit_button"]');
181
+ if (submitButton && !submitButton.disabled) submitButton.click();
182
+ }
183
+ });
184
+ """, height=0)
185
 
186
+ st.session_state.answer = st.text_input("Your Answer", value="", key=f"answer_input_{st.session_state.question_number}")
 
187
 
188
+ if st.button("Submit", key="submit_button"):
189
+ submit_response()
190
  else:
191
+ print("Waiting for session to initialize...")