Claude commited on
Commit
8dbc191
·
unverified ·
1 Parent(s): 1f7e056

fix: 제출 섹션을 @st .fragment로 분리 — 쿨다운 rerun이 하단 콘텐츠 숨기는 문제 해결

Browse files

st.rerun()이 프래그먼트 밖 렌더링을 중단시켜 채팅 보드 등 하단 콘텐츠가
사라지던 문제를 수정합니다. 입력 섹션을 @st .fragment로 감싸 쿨다운 rerun이
해당 영역만 재실행하도록 하고, 제출 성공 시에는 scope="app"으로 전체 앱을
새로고침합니다.

https://claude.ai/code/session_01BRbPoMBBfvgN58bGkNhmv7

Files changed (1) hide show
  1. app.py +98 -94
app.py CHANGED
@@ -99,102 +99,106 @@ else:
99
  st.title(f"🎙️ 말자취(Talk-Trace) AI [{room_name}]")
100
  st.info(f"**현재 주제:** {current_topic} ({current_mode})")
101
 
102
- st.subheader("🗣️ 내 의견 작성")
103
- col_input, col_stt = st.columns([4, 1])
104
- with col_input:
105
- user_input = st.text_area(
106
- "의견을 입력하세요",
107
- key=f"input_{st.session_state['reset_key']}",
108
- height=80,
109
- label_visibility="collapsed",
110
- )
111
- opts = ["🔵 찬성", "🔴 반대"] if current_mode == "⚔️ 찬반 토론" else ["💡 아이디어", "➕ 보충", "❓ 질문"]
112
- sentiment = st.radio("의견 성격", opts, horizontal=True)
113
-
114
- with col_stt:
115
- st.components.v1.html(
116
- """
117
- <button id="stt-btn" style="width:100%; height:80px; font-weight:bold; border-radius:10px; background-color:#e8f0fe; border:1px solid #1a73e8; color:#1a73e8; cursor:pointer;">🎤 음성 입력 시작</button>
118
- <p id="status" style="font-size:11px; color:gray; text-align:center; margin-top:5px;">대기 중...</p>
119
- <script>
120
- const btn = document.getElementById('stt-btn');
121
- const status = document.getElementById('status');
122
- const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
123
- recognition.lang = 'ko-KR';
124
- let isRecognizing = false;
125
- btn.onclick = () => { if (!isRecognizing) recognition.start(); else recognition.stop(); };
126
- recognition.onstart = () => { isRecognizing = true; status.innerText = "듣는 중..."; btn.style.backgroundColor = "#ff4b4b"; btn.style.color = "white"; btn.innerHTML = "🛑 음성 입력 중지"; };
127
- recognition.onresult = (event) => {
128
- const text = event.results[0][0].transcript;
129
- const textArea = window.parent.document.querySelector('textarea[aria-label="의견을 입력하세요"]');
130
- if (textArea) {
131
- const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
132
- nativeInputValueSetter.call(textArea, textArea.value + " " + text);
133
- textArea.dispatchEvent(new Event('input', { bubbles: true }));
134
- status.innerText = "입력 완료!";
135
- }
136
- };
137
- recognition.onend = () => { isRecognizing = false; setTimeout(() => { status.innerText = "대기 중..."; btn.style.backgroundColor = "#e8f0fe"; btn.style.color = "#1a73e8"; btn.innerHTML = "🎤 음성 입력 시작"; }, 1500); };
138
- </script>
139
- """,
140
- height=120,
141
- )
142
-
143
- _elapsed = time.time() - st.session_state.get('last_submit_ts', 0)
144
- _submit_cooldown = _elapsed < 3
145
- _submit_disabled = _submit_cooldown or st.session_state.get('is_working', False)
146
- if st.button("의견 제출", use_container_width=True, type="primary", disabled=_submit_disabled):
147
- if st.session_state.get('is_working', False):
148
- st.stop()
149
- st.session_state['is_working'] = True
150
- input_ok, safe_input, input_error_code, input_error_message = validate_opinion_content(user_input, max_len=700)
151
- student_ok, safe_student_name, student_error_code, student_error_message = validate_student_name(student_name, max_len=MAX_STUDENT_NAME_LEN)
152
- student_number_ok, safe_student_number, _, student_number_error_message = validate_student_name(student_number, max_len=20)
153
- if not student_number_ok and user_role == "학생":
154
- st.session_state['is_working'] = False
155
- st.error(f"❌ {student_number_error_message}")
156
- st.stop()
157
- if user_role == "학생" and (not safe_student_name or safe_student_name == "익명"):
158
- safe_student_name = safe_student_number or "학번미입력"
159
- if input_ok and safe_input:
160
- now = get_kst_now_str()
161
- author_role_for_submit = "교사" if user_role == "교사" else "학생"
162
- client_ip = get_client_ip()
163
- insert_payload = {
164
- "room_name": room_name, "timestamp": now, "student_name": safe_student_name,
165
- "content": safe_input, "sentiment": sentiment, "author_role": author_role_for_submit,
166
- }
167
- if debate_ip_column_available() and client_ip:
168
- parts = client_ip.split(".")
169
- anonymized_ip = f"{parts[0]}.0.0.{parts[3]}" if len(parts) == 4 else None
170
- if anonymized_ip:
171
- insert_payload["ip_address"] = anonymized_ip
172
- try:
173
- res = submit_opinion(supabase, insert_payload)
174
- if res is None:
175
- st.session_state['is_working'] = False
176
- st.stop()
177
- st.session_state['last_submit_ts'] = time.time()
178
  st.session_state['is_working'] = False
179
- fetch_live_messages.clear()
180
- log_audit(
181
- "opinion_submitted",
182
- room_name=room_name, actor_name=safe_student_name,
183
- role=author_role_for_submit, sentiment=sentiment,
184
- client_ip=client_ip if client_ip else "N/A",
185
- )
186
- st.session_state['reset_key'] += 1
187
- st.rerun()
188
- except Exception as e:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  st.session_state['is_working'] = False
190
- st.error(f"저장 실패: {e}")
191
- else:
192
- st.session_state['is_working'] = False
193
- st.warning(f"{input_error_message} ({input_error_code})")
194
- if _submit_cooldown:
195
- st.caption("⏳ 제출 성공 후 3초간 의견을 제출할 수 없습니다.")
196
- time.sleep(0.5)
197
- st.rerun()
198
 
199
  st.divider()
200
 
 
99
  st.title(f"🎙️ 말자취(Talk-Trace) AI [{room_name}]")
100
  st.info(f"**현재 주제:** {current_topic} ({current_mode})")
101
 
102
+ @st.fragment
103
+ def _render_opinion_input(supabase, room_name, user_role, student_name, student_number, current_mode):
104
+ st.subheader("🗣️ 내 의견 작성")
105
+ col_input, col_stt = st.columns([4, 1])
106
+ with col_input:
107
+ user_input = st.text_area(
108
+ "의견을 입력하세요",
109
+ key=f"input_{st.session_state['reset_key']}",
110
+ height=80,
111
+ label_visibility="collapsed",
112
+ )
113
+ opts = ["🔵 찬성", "🔴 반대"] if current_mode == "⚔️ 찬반 토론" else ["💡 아이디어", "➕ 보충", "❓ 질문"]
114
+ sentiment = st.radio("의견 성격", opts, horizontal=True)
115
+
116
+ with col_stt:
117
+ st.components.v1.html(
118
+ """
119
+ <button id="stt-btn" style="width:100%; height:80px; font-weight:bold; border-radius:10px; background-color:#e8f0fe; border:1px solid #1a73e8; color:#1a73e8; cursor:pointer;">🎤 음성 입력 시작</button>
120
+ <p id="status" style="font-size:11px; color:gray; text-align:center; margin-top:5px;">대기 중...</p>
121
+ <script>
122
+ const btn = document.getElementById('stt-btn');
123
+ const status = document.getElementById('status');
124
+ const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
125
+ recognition.lang = 'ko-KR';
126
+ let isRecognizing = false;
127
+ btn.onclick = () => { if (!isRecognizing) recognition.start(); else recognition.stop(); };
128
+ recognition.onstart = () => { isRecognizing = true; status.innerText = "듣는 중..."; btn.style.backgroundColor = "#ff4b4b"; btn.style.color = "white"; btn.innerHTML = "🛑 음성 입력 중지"; };
129
+ recognition.onresult = (event) => {
130
+ const text = event.results[0][0].transcript;
131
+ const textArea = window.parent.document.querySelector('textarea[aria-label="의견을 입력하세요"]');
132
+ if (textArea) {
133
+ const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
134
+ nativeInputValueSetter.call(textArea, textArea.value + " " + text);
135
+ textArea.dispatchEvent(new Event('input', { bubbles: true }));
136
+ status.innerText = "입력 완료!";
137
+ }
138
+ };
139
+ recognition.onend = () => { isRecognizing = false; setTimeout(() => { status.innerText = "대기 중..."; btn.style.backgroundColor = "#e8f0fe"; btn.style.color = "#1a73e8"; btn.innerHTML = "🎤 음성 입력 시작"; }, 1500); };
140
+ </script>
141
+ """,
142
+ height=120,
143
+ )
144
+
145
+ _elapsed = time.time() - st.session_state.get('last_submit_ts', 0)
146
+ _submit_cooldown = _elapsed < 3
147
+ _submit_disabled = _submit_cooldown or st.session_state.get('is_working', False)
148
+ if st.button("의견 제출", use_container_width=True, type="primary", disabled=_submit_disabled):
149
+ if st.session_state.get('is_working', False):
150
+ st.stop()
151
+ st.session_state['is_working'] = True
152
+ input_ok, safe_input, input_error_code, input_error_message = validate_opinion_content(user_input, max_len=700)
153
+ student_ok, safe_student_name, student_error_code, student_error_message = validate_student_name(student_name, max_len=MAX_STUDENT_NAME_LEN)
154
+ student_number_ok, safe_student_number, _, student_number_error_message = validate_student_name(student_number, max_len=20)
155
+ if not student_number_ok and user_role == "학생":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  st.session_state['is_working'] = False
157
+ st.error(f"❌ {student_number_error_message}")
158
+ st.stop()
159
+ if user_role == "학생" and (not safe_student_name or safe_student_name == "익명"):
160
+ safe_student_name = safe_student_number or "학번미입력"
161
+ if input_ok and safe_input:
162
+ now = get_kst_now_str()
163
+ author_role_for_submit = "교사" if user_role == "교사" else "학생"
164
+ client_ip = get_client_ip()
165
+ insert_payload = {
166
+ "room_name": room_name, "timestamp": now, "student_name": safe_student_name,
167
+ "content": safe_input, "sentiment": sentiment, "author_role": author_role_for_submit,
168
+ }
169
+ if debate_ip_column_available() and client_ip:
170
+ parts = client_ip.split(".")
171
+ anonymized_ip = f"{parts[0]}.0.0.{parts[3]}" if len(parts) == 4 else None
172
+ if anonymized_ip:
173
+ insert_payload["ip_address"] = anonymized_ip
174
+ try:
175
+ res = submit_opinion(supabase, insert_payload)
176
+ if res is None:
177
+ st.session_state['is_working'] = False
178
+ st.stop()
179
+ st.session_state['last_submit_ts'] = time.time()
180
+ st.session_state['is_working'] = False
181
+ fetch_live_messages.clear()
182
+ log_audit(
183
+ "opinion_submitted",
184
+ room_name=room_name, actor_name=safe_student_name,
185
+ role=author_role_for_submit, sentiment=sentiment,
186
+ client_ip=client_ip if client_ip else "N/A",
187
+ )
188
+ st.session_state['reset_key'] += 1
189
+ st.rerun(scope="app")
190
+ except Exception as e:
191
+ st.session_state['is_working'] = False
192
+ st.error(f"저장 실패: {e}")
193
+ else:
194
  st.session_state['is_working'] = False
195
+ st.warning(f"{input_error_message} ({input_error_code})")
196
+ if _submit_cooldown:
197
+ st.caption("⏳ 제출 성공 후 3초간 의견을 제출할 수 없습니다.")
198
+ time.sleep(0.5)
199
+ st.rerun()
200
+
201
+ _render_opinion_input(supabase, room_name, user_role, student_name, student_number, current_mode)
 
202
 
203
  st.divider()
204