devorah-ai-2016 commited on
Commit
c408c07
·
verified ·
1 Parent(s): 0a30bf9

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -764
app.py DELETED
@@ -1,764 +0,0 @@
1
- import sys
2
- import os
3
- import random
4
- import re
5
- import pandas as pd
6
- import streamlit as st
7
- from datetime import date, datetime, timedelta
8
- from io import BytesIO
9
- from openpyxl import Workbook, load_workbook
10
- from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
11
- from openpyxl.utils import get_column_letter
12
- from openai import OpenAI
13
-
14
- # 로컬 db_sync 모듈
15
- sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
16
- import db_sync
17
-
18
- CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
19
-
20
- # -----------------------------
21
- # Streamlit 기본 설정 & 테마 CSS
22
- # -----------------------------
23
- st.set_page_config(page_title="BeeCare Core Integration", page_icon="🐝", layout="wide")
24
-
25
- st.markdown("""
26
- <style>
27
- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Noto+Sans+KR:wght@300;400;500;700;900&display=swap');
28
-
29
- html, body, [class*="css"], .stApp {
30
- font-family: 'Inter', 'Noto Sans KR', sans-serif;
31
- background-color: #fbf9f5;
32
- color: #1b1c1a;
33
- }
34
- .block-container {
35
- max-width: 1200px;
36
- padding-top: 1.5rem;
37
- padding-bottom: 3rem;
38
- }
39
- .hero {
40
- background: linear-gradient(135deg, #f5e6d3, #efe0cd);
41
- border: 1px solid #ccc3d8;
42
- border-left: 9px solid #2E7D32;
43
- border-radius: 20px;
44
- padding: 28px 32px;
45
- margin-bottom: 24px;
46
- box-shadow: 0px 8px 24px rgba(46, 125, 50, 0.05);
47
- }
48
- .hero .eyebrow {
49
- display: inline-flex;
50
- align-items: center;
51
- gap: 6px;
52
- background: #2E7D32;
53
- color: #ffffff;
54
- border-radius: 999px;
55
- padding: 4px 12px;
56
- font-size: 13px;
57
- font-weight: 700;
58
- margin-bottom: 12px;
59
- }
60
- .hero h1 {
61
- margin: 0;
62
- font-size: clamp(24px, 3vw, 36px);
63
- line-height: 1.2;
64
- color: #1b5e20;
65
- font-weight: 800;
66
- }
67
- .hero p {
68
- margin: 8px 0 0;
69
- font-size: 15px;
70
- color: #4e483b;
71
- line-height: 1.6;
72
- }
73
- .notice {
74
- background: #ffffff;
75
- border: 1px solid #e4e2de;
76
- border-left: 6px solid #fb8c00;
77
- border-radius: 12px;
78
- padding: 14px 16px;
79
- margin-bottom: 20px;
80
- font-size: 14px;
81
- line-height: 1.6;
82
- color: #4a4455;
83
- }
84
- .section-card {
85
- background: #ffffff;
86
- border: 1px solid #e4e2de;
87
- border-radius: 16px;
88
- padding: 20px;
89
- margin-bottom: 18px;
90
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.01);
91
- }
92
- div[data-testid="stMetric"] {
93
- background: #ffffff;
94
- border: 1px solid #e4e2de;
95
- border-radius: 14px;
96
- padding: 12px;
97
- box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.01);
98
- }
99
- .stButton > button {
100
- border-radius: 10px !important;
101
- background: linear-gradient(135deg, #2E7D32, #4CAF50) !important;
102
- color: #ffffff !important;
103
- font-weight: 700 !important;
104
- border: none !important;
105
- padding: 8px 20px !important;
106
- min-height: 42px !important;
107
- box-shadow: 0px 4px 10px rgba(46, 125, 50, 0.2) !important;
108
- transition: all 0.2s ease-in-out !important;
109
- width: 100% !important;
110
- }
111
- .stButton > button:hover {
112
- transform: translateY(-1px) !important;
113
- box-shadow: 0px 6px 14px rgba(46, 125, 50, 0.3) !important;
114
- }
115
- .stDownloadButton > button {
116
- border-radius: 10px !important;
117
- background: #ffffff !important;
118
- color: #2E7D32 !important;
119
- font-weight: 700 !important;
120
- border: 1.5px solid #2E7D32 !important;
121
- padding: 8px 20px !important;
122
- min-height: 42px !important;
123
- width: 100% !important;
124
- }
125
- .stDownloadButton > button:hover {
126
- background: #e8f5e9 !important;
127
- color: #1b5e20 !important;
128
- }
129
- </style>
130
- """, unsafe_allow_html=True)
131
-
132
- # -----------------------------
133
- # 데이터 동기화 기동 시 자동 다운로드
134
- # -----------------------------
135
- if "db_downloaded" not in st.session_state:
136
- with st.spinner("허깅페이스 DB 데이터 로딩 중..."):
137
- db_sync.download_all()
138
- st.session_state["db_downloaded"] = True
139
-
140
- # -----------------------------
141
- # 엑셀 데이터 파일 입출력 헬퍼
142
- # -----------------------------
143
- def load_excel_data(relative_path, default_cols):
144
- local_path = os.path.join(CURRENT_DIR, relative_path)
145
- os.makedirs(os.path.dirname(local_path), exist_ok=True)
146
- if os.path.exists(local_path):
147
- try:
148
- df = pd.read_excel(local_path)
149
- # 결락 컬럼 보완
150
- for col in default_cols:
151
- if col not in df.columns:
152
- df[col] = ""
153
- return df
154
- except Exception:
155
- pass
156
- df = pd.DataFrame(columns=default_cols)
157
- df.to_excel(local_path, index=False)
158
- return df
159
-
160
- def save_excel_data(df, relative_path):
161
- local_path = os.path.join(CURRENT_DIR, relative_path)
162
- os.makedirs(os.path.dirname(local_path), exist_ok=True)
163
- df.to_excel(local_path, index=False)
164
-
165
- # -----------------------------
166
- # 기능별 컬럼 및 옵션 상수 선언
167
- # -----------------------------
168
- CLIENT_COLS = [
169
- "NO.", "수급자이름", "가명표기", "성별", "생년월일", "실질생일날짜", "장기요양등급", "인정번호",
170
- "인정기���시작일", "인정기간종료일", "입소일", "이용상태", "주요질환", "인지상태", "이동상태",
171
- "식사상태", "배변/배뇨상태", "보호자이름", "보호자연락처", "특이사항", "비고", "기관유형", "기관명"
172
- ]
173
-
174
- COUNSELING_COLS = [
175
- "NO.", "수급자이름", "가명표기", "상담일자", "상담자", "상담분류", "상담사유", "상담내용", "조치계획",
176
- "추가욕구요청사항", "사례관리필요", "욕구사정필요", "급여제공계획변경필요", "등록일자"
177
- ]
178
-
179
- CASE_MANAGEMENT_COLS = [
180
- "NO.", "수급자이름", "가명표기", "회의일자", "참석자", "회의분류", "사례선정이유",
181
- "해결방안(1차계획)", "시행과정", "종합결과(2차평가)", "등록일자"
182
- ]
183
-
184
- VALID_GENDERS = ["여", "남", "기타"]
185
- VALID_GRADES = ["1등급", "2등급", "3등급", "4등급", "5등급", "인지지원등급", "등급외", "미입력"]
186
- VALID_INST_TYPES = ["방문요양", "방문목욕", "방문간호", "주간보호", "요양원", "공동생활가정"]
187
- VALID_STATUS = ["이용중", "입소중", "퇴소", "중지", "사망"]
188
-
189
- def load_clients():
190
- df = load_excel_data("data/clients.xlsx", CLIENT_COLS)
191
- # 등급 숫자 정규화
192
- if not df.empty and "장기요양등급" in df.columns:
193
- df["장기요양등급"] = df["장기요양등급"].apply(lambda x: str(x).strip() + "등급" if str(x).strip() in ["1", "2", "3", "4", "5"] else str(x).strip())
194
- return df
195
-
196
- def load_counseling():
197
- return load_excel_data("data/counseling_logs.xlsx", COUNSELING_COLS)
198
-
199
- def load_case_management():
200
- return load_excel_data("data/case_management.xlsx", CASE_MANAGEMENT_COLS)
201
-
202
- def safe(val, default=""):
203
- if pd.isna(val) or val is None:
204
- return default
205
- return str(val).strip()
206
-
207
- def mask_name(name):
208
- name = safe(name)
209
- if len(name) >= 3:
210
- return name[0] + "○" + name[2:]
211
- if len(name) == 2:
212
- return name[0] + "○"
213
- return name
214
-
215
- # 🎂 생신 알림 기초 도구
216
- def get_this_year_birthday(birth_date_str, real_birth_date_str):
217
- md = ""
218
- r_val = safe(real_birth_date_str)
219
- if r_val and re.match(r"^\d{2}-\d{2}$", r_val):
220
- md = r_val
221
- if not md:
222
- b_val = safe(birth_date_str)
223
- if re.match(r"^\d{4}-\d{2}-\d{2}$", b_val):
224
- md = b_val[5:10]
225
- if not md:
226
- return None
227
- try:
228
- m, d = map(int, md.split("-"))
229
- return date(datetime.now().year, m, d)
230
- except Exception:
231
- return None
232
-
233
- def display_birthday_alerts(df):
234
- if df.empty:
235
- return
236
- today = date.today()
237
- this_month = today.month
238
- today_birthdays = []
239
- month_birthdays = []
240
-
241
- for _, row in df.iterrows():
242
- name_masked = mask_name(row.get("수급자이름"))
243
- bday = get_this_year_birthday(row.get("생년월일"), row.get("실질생일날짜"))
244
- if bday:
245
- if bday.month == today.month and bday.day == today.day:
246
- today_birthdays.append(f"**{name_masked} 어르신**" + (f" (실질생일: {row.get('실질생일날짜')})" if row.get('실질생일날짜') else ""))
247
- elif bday.month == this_month:
248
- month_birthdays.append(f"**{name_masked} 어르신** ({bday.day}일 - " + (f"실질: {row.get('실질생일날짜')}" if row.get('실질생일날짜') else f"생년월일: {row.get('생년월일')[5:10] if row.get('생년월일') else ''}") + ")")
249
-
250
- if today_birthdays or month_birthdays:
251
- st.markdown(f"### 🎂 {this_month}월 생신 알림")
252
- if today_birthdays:
253
- st.markdown(f"""
254
- <div style="background: #fff3e0; border-left: 6px solid #fb8c00; padding: 12px; border-radius: 10px; margin-bottom: 12px; color: #222;">
255
- 🎉 <strong>오늘 생신!</strong> 오늘은 {', '.join(today_birthdays)}의 생신입니다. 축하드립니다! 🎂
256
- </div>
257
- """, unsafe_allow_html=True)
258
- if month_birthdays:
259
- items = "".join([f"<li>{item}</li>" for item in month_birthdays])
260
- st.markdown(f"""
261
- <div style="background: #e8f5e9; border-left: 6px solid #43a047; padding: 12px; border-radius: 10px; margin-bottom: 12px; color: #222;">
262
- 🎁 <strong>{this_month}월 생신 어르신 목록:</strong>
263
- <ul style="margin: 6px 0 0 16px; padding: 0;">{items}</ul>
264
- </div>
265
- """, unsafe_allow_html=True)
266
-
267
- # 🤖 AI 전문 소견 API 연동부
268
- def generate_ai_opinion(system_prompt, user_prompt, client_name, reason, content):
269
- # API 키를 사이드바 혹은 환경 변수에서 가져옵니다
270
- api_key = st.sidebar.text_input("OpenAI API Key (선택)", value=os.environ.get("OPENAI_API_KEY", ""), type="password")
271
- use_lm_studio = st.sidebar.toggle("LM Studio 사용 (Qwen)", value=False)
272
-
273
- if use_lm_studio:
274
- try:
275
- ai_client = OpenAI(base_url="http://127.0.0.1:1234/v1", api_key="lm-studio")
276
- completion = ai_client.chat.completions.create(
277
- model="qwen2.5-7b-instruct",
278
- messages=[
279
- {"role": "system", "content": system_prompt},
280
- {"role": "user", "content": user_prompt}
281
- ],
282
- temperature=0.7
283
- )
284
- return completion.choices[0].message.content.strip()
285
- except Exception as e:
286
- st.sidebar.error(f"LM Studio 연결 실패: {e}")
287
-
288
- if api_key.strip():
289
- try:
290
- ai_client = OpenAI(api_key=api_key)
291
- completion = ai_client.chat.completions.create(
292
- model="gpt-4o-mini",
293
- messages=[
294
- {"role": "system", "content": system_prompt},
295
- {"role": "user", "content": user_prompt}
296
- ],
297
- temperature=0.5
298
- )
299
- return completion.choices[0].message.content.strip()
300
- except Exception as e:
301
- st.sidebar.error(f"OpenAI API 호출 실패: {e}")
302
-
303
- # Fallback Rule-based (룰 기반 대체 텍스트)
304
- return (
305
- f"1. {client_name} 어르신의 금번 상담 사유인 '{reason}'에 따라 수급자의 건강 및 생활 패턴 변화를 세밀하게 관찰하였습니다.\n"
306
- f"2. {content[:30]}...의 입력을 바탕으로 관찰한 결과, 일상 생활 지원 및 신체 활동 관리에 적극적인 개입이 요망됩니다.\n"
307
- f"3. 작성된 조치계획의 충실한 이행 여부를 정기 검토하고 상태 이상 징후 확인 시 즉각 보호자 및 유관 직종과 공유하겠습니다."
308
- )
309
-
310
- # -----------------------------
311
- # 공통 레이아웃 구성
312
- # -----------------------------
313
- st.markdown("""
314
- <div class="hero">
315
- <div class="eyebrow">BeeCare Core v1.0</div>
316
- <h1>🐝 BeeCare Core 통합 연동 문서시스템</h1>
317
- <p>수급자등록, 상담일지, 사례관리를 하나의 앱과 데이터베이스 환경으로 완전 연동하여 실시간 공유를 보장합니다.</p>
318
- </div>
319
- """, unsafe_allow_html=True)
320
-
321
- # 🔄 사이드바 동기화 제어판
322
- st.sidebar.subheader("🔄 실시간 동기화 제어")
323
- if st.sidebar.button("허깅페이스에서 DB 다운로드"):
324
- with st.spinner("다운로드 중..."):
325
- if db_sync.download_all():
326
- st.sidebar.success("성공적으로 다운로드되었습니다!")
327
- st.rerun()
328
- else:
329
- st.sidebar.error("다운로드 실패!")
330
-
331
- if st.sidebar.button("허깅페이스에 DB 업로드"):
332
- with st.spinner("업로드 중..."):
333
- if db_sync.upload_all():
334
- st.sidebar.success("성공적으로 업로드되었습니다!")
335
- else:
336
- st.sidebar.error("업로드 실패!")
337
-
338
- # -----------------------------
339
- # 탭 정의 (1차 통합)
340
- # -----------------------------
341
- tab1, tab2, tab3 = st.tabs(["👥 수급자 등록 · 관리", "📝 상담일지 작성", "📋 사례관리 회의록"])
342
-
343
- # ==========================================
344
- # 탭 1: 수급자 등록
345
- # ==========================================
346
- with tab1:
347
- st.subheader("👥 수급자 등록 및 기초 데이터 관리")
348
- df_clients = load_clients()
349
-
350
- display_birthday_alerts(df_clients)
351
-
352
- sub_menu = st.radio("수급자 관리 메뉴", ["수급자 직접 등록", "엑셀 일괄 업로드", "등록된 수급자 목록"], horizontal=True)
353
-
354
- if sub_menu == "수급자 직접 등록":
355
- with st.form("client_register_form"):
356
- st.markdown("##### 👤 기본 정보 입력")
357
- c1, c2, c3 = st.columns(3)
358
- name = c1.text_input("수급자 이름")
359
- gender = c2.selectbox("성별", VALID_GENDERS)
360
- birth_date = c3.text_input("생년월일 (YYYY-MM-DD)", placeholder="예: 1942-09-20")
361
-
362
- c4, c5, c6 = st.columns(3)
363
- real_birth_date = c4.text_input("실질생일날짜 (MM-DD)", placeholder="예: 09-20 (음력 등)")
364
- care_grade = c5.selectbox("장기요양등급", VALID_GRADES)
365
- rec_num = c6.text_input("인정번호", placeholder="숫자만 입력해도 L 자동 결합")
366
-
367
- c7, c8, c9 = st.columns(3)
368
- rec_start = c7.text_input("인정기간 시작일 (YYYY-MM-DD)", placeholder="예: 2025-03-03")
369
- rec_end = c8.text_input("인정기간 종료일 (YYYY-MM-DD)", placeholder="예: 2027-03-02")
370
- admission_date = c9.text_input("입소일/이용시작일 (YYYY-MM-DD)", placeholder="예: 2025-03-05")
371
-
372
- c10, c11, c12 = st.columns(3)
373
- inst_type = c10.selectbox("기관 유형", VALID_INST_TYPES)
374
- inst_name = c11.text_input("기관명")
375
- status = c12.selectbox("이용 상태", VALID_STATUS)
376
-
377
- st.markdown("##### 🏥 어르신 상태 및 케어 조건")
378
- cc1, cc2, cc3 = st.columns(3)
379
- main_cond = cc1.text_area("주요 질환 / 상태", height=80)
380
- cog_stat = cc2.text_area("인지 상태", height=80)
381
- mob_stat = cc3.text_area("이동 상태", height=80)
382
-
383
- cc4, cc5, cc6 = st.columns(3)
384
- diet_stat = cc4.text_area("식사 상태", height=80)
385
- toil_stat = cc5.text_area("배변/배뇨 상태", height=80)
386
- notes = cc6.text_area("특이사항 / 메모", height=80)
387
-
388
- st.markdown("##### 👥 보호자 정보")
389
- ccc1, ccc2, ccc3 = st.columns(3)
390
- guard_name = ccc1.text_input("보호자 성함")
391
- guard_phone = ccc2.text_input("보호자 연락처")
392
- remarks = ccc3.text_input("비고")
393
-
394
- submit = st.form_submit_button("수급자 정보 저장 및 동기화")
395
-
396
- if submit:
397
- if not name.strip():
398
- st.error("수급자 이름은 필수 입력 항목입니다.")
399
- else:
400
- # 인정번호 L 포맷 정리
401
- rec_num_clean = rec_num.replace(" ", "").upper()
402
- if rec_num_clean and not rec_num_clean.startswith("L"):
403
- rec_num_clean = "L" + re.sub(r"[^0-9]", "", rec_num_clean)
404
-
405
- new_no = len(df_clients) + 1
406
- new_row = {
407
- "NO.": new_no,
408
- "수급자이름": name.strip(),
409
- "가명표기": mask_name(name),
410
- "성별": gender,
411
- "생년월일": birth_date.strip(),
412
- "실질생일날짜": real_birth_date.strip(),
413
- "장기요양등급": care_grade,
414
- "인정번호": rec_num_clean,
415
- "인정기간시작일": rec_start.strip(),
416
- "인정기간종료일": rec_end.strip(),
417
- "입소일": admission_date.strip(),
418
- "이용상태": status,
419
- "주요질환": main_cond.strip(),
420
- "인지상태": cog_stat.strip(),
421
- "이동상태": mob_stat.strip(),
422
- "식사상태": diet_stat.strip(),
423
- "배변/배뇨상태": toil_stat.strip(),
424
- "보호자이름": guard_name.strip(),
425
- "보호자연락처": guard_phone.strip(),
426
- "특이사항": notes.strip(),
427
- "비고": remarks.strip(),
428
- "기관유형": inst_type,
429
- "기관명": inst_name.strip()
430
- }
431
- df_clients = pd.concat([df_clients, pd.DataFrame([new_row])], ignore_index=True)
432
- save_excel_data(df_clients, "data/clients.xlsx")
433
- db_sync.upload_all()
434
- st.success(f"{name} 어르신의 정보가 등록 및 동기화 완료되었습니다!")
435
- st.rerun()
436
-
437
- elif sub_menu == "엑셀 일괄 업로드":
438
- st.info("기존에 제공된 수급자 등록 양식과 동일한 구조의 엑셀 파일을 업로드해 주세요.")
439
- uploaded_file = st.file_uploader("수급자 엑셀 파일 선택", type=["xlsx"])
440
- overwrite = st.checkbox("중복 이름이 있을 경우 기존 데이터 덮어쓰기", value=True)
441
-
442
- if uploaded_file:
443
- try:
444
- uploaded_df = pd.read_excel(uploaded_file)
445
- # 정규화 및 바인딩
446
- st.dataframe(uploaded_df.head(3), use_container_width=True)
447
- if st.button("데이터 업로드 실행"):
448
- # 기존 데이터에 결합 로직 구현
449
- for _, row in uploaded_df.iterrows():
450
- u_name = safe(row.get("수급자이름"))
451
- if not u_name:
452
- continue
453
-
454
- # 등급 정규화
455
- grade_val = safe(row.get("장기요양등급"))
456
- if grade_val in ["1", "2", "3", "4", "5"]:
457
- grade_val += "등급"
458
- if grade_val not in VALID_GRADES:
459
- grade_val = "미입력"
460
-
461
- # 인정번호 L 정규화
462
- rec_raw = safe(row.get("인정번호")).upper()
463
- if rec_raw and not rec_raw.startswith("L"):
464
- rec_raw = "L" + re.sub(r"[^0-9]", "", rec_raw)
465
-
466
- # 중복 여부 확인
467
- duplicate_mask = df_clients["수급자이름"] == u_name
468
-
469
- row_data = {
470
- "NO.": len(df_clients) + 1 if not duplicate_mask.any() else df_clients.loc[duplicate_mask, "NO."].values[0],
471
- "수급자이름": u_name,
472
- "가명표기": mask_name(u_name),
473
- "성별": safe(row.get("성별")) if safe(row.get("성별")) in VALID_GENDERS else "여",
474
- "생년월일": safe(row.get("생년월일")),
475
- "실질생일날짜": safe(row.get("실질생일날짜")),
476
- "장기요양등급": grade_val,
477
- "인정번호": rec_raw,
478
- "인정기간시작일": safe(row.get("인정기간시작일")),
479
- "인정기간종료일": safe(row.get("인정기간종료일")),
480
- "입소일": safe(row.get("입소일")),
481
- "이용상태": safe(row.get("이용상태")) if safe(row.get("이용상태")) in VALID_STATUS else "이용중",
482
- "주요질환": safe(row.get("주요질환")),
483
- "인지상태": safe(row.get("인지상태")),
484
- "이동상태": safe(row.get("이동상태")),
485
- "식사상태": safe(row.get("식사상태")),
486
- "배변/배뇨상태": safe(row.get("배변/배뇨상태")),
487
- "보호자이름": safe(row.get("보호자이름")),
488
- "보호자연락처": safe(row.get("보호자연락처")),
489
- "특이사항": safe(row.get("특이사항")),
490
- "비고": safe(row.get("비고")),
491
- "기관유형": safe(row.get("기관유형")) if safe(row.get("기관유형")) in VALID_INST_TYPES else "방문요양",
492
- "기관명": safe(row.get("기관명"))
493
- }
494
-
495
- if duplicate_mask.any() and overwrite:
496
- df_clients.loc[duplicate_mask] = list(row_data.values())
497
- else:
498
- df_clients = pd.concat([df_clients, pd.DataFrame([row_data])], ignore_index=True)
499
-
500
- # 번호 재정렬
501
- df_clients["NO."] = range(1, len(df_clients) + 1)
502
- save_excel_data(df_clients, "data/clients.xlsx")
503
- db_sync.upload_all()
504
- st.success("엑셀 데이터 업로드 및 실시간 동기화가 완료되었습니다!")
505
- st.rerun()
506
- except Exception as e:
507
- st.error(f"엑셀 처리 중 오류 발생: {e}")
508
-
509
- elif sub_menu == "등록된 수급자 목록":
510
- if df_clients.empty:
511
- st.info("등록된 수급자 정보가 없습니다.")
512
- else:
513
- st.dataframe(df_clients, use_container_width=True, hide_index=True)
514
-
515
- # ==========================================
516
- # 탭 2: 상담일지
517
- # ==========================================
518
- with tab2:
519
- st.subheader("📝 연동 상담일지 작성")
520
- df_clients = load_clients()
521
- df_counseling = load_counseling()
522
-
523
- if df_clients.empty:
524
- st.warning("먼저 '수급자 등록' 탭에서 수급자 기본 정보를 1명 이상 등록해 주세요.")
525
- else:
526
- st.markdown("##### 1단계: 상담 대상 어르신 선택")
527
- client_options = df_clients.apply(
528
- lambda x: f"{x['NO.']}번 - {x['가명표기']} / {x['장기요양등급']} / {x['기관유형']} / {x['이용상태']}",
529
- axis=1
530
- ).tolist()
531
-
532
- selected_client_opt = st.selectbox("수급자 선택", client_options, key="counsel_client_select")
533
- selected_no = int(selected_client_opt.split("번")[0])
534
- client_row = df_clients[df_clients["NO."] == selected_no].iloc[0]
535
-
536
- st.markdown("---")
537
- st.markdown("##### 2단계: 상담 상세 내용 기록")
538
-
539
- with st.form("counseling_form"):
540
- col_c1, col_c2, col_c3 = st.columns(3)
541
- c_name = col_c1.text_input("수급자 성명", value=safe(client_row["수급자이름"]), disabled=True)
542
- c_masked = col_c2.text_input("가명 표기", value=safe(client_row["가명표기"]), disabled=True)
543
- c_date = col_c3.date_input("상담일자", value=date.today())
544
-
545
- col_c4, col_c5 = st.columns(2)
546
- c_writer = col_c4.text_input("상담자", value="사회복지사")
547
- c_type = col_c5.selectbox("상담분류", ["수급자상담", "보호자상담", "종사자상담", "기타상담"])
548
-
549
- c_reason = st.selectbox("상담사유", [
550
- "정기상담", "상태변화에 따른 상담", "수급자 요청", "보호자 요청", "요양보호사 건의", "응급조치 피드백"
551
- ])
552
-
553
- c_content = st.text_area("상담내용", placeholder="상담한 핵심 내용을 육하원칙에 의거해 기록해 주세요.", height=120)
554
- c_plan = st.text_area("조치계획", placeholder="상담 이후 어르신에게 제공될 조치나 조율사항을 적어주세요.", height=80)
555
- c_needs = st.text_area("추가욕구요청사항", placeholder="추가로 전달받은 서비스 요구나 보호자의 개선 요청 등을 상세히 입력해 주세요.", height=80)
556
-
557
- st.markdown("##### ⚠️ 후속 업무 연동 지정")
558
- st.info("상담 결과에 따라 연동 처리가 필요한 업무를 체크해 주세요. 탭 3(사례관리)은 '사례관리필요'가 활성화된 어르신만 연동됩니다.")
559
- col_cb1, col_cb2, col_cb3 = st.columns(3)
560
- need_case = col_cb1.checkbox("사례관리 회의 회부 필요", value=False)
561
- need_needs = col_cb2.checkbox("욕구사정 재평가 필요", value=False)
562
- need_careplan = col_cb3.checkbox("급여제공계획 변경/재작성 필요", value=False)
563
-
564
- st.markdown("##### 🤖 AI 소견 생성")
565
- st.caption("작성된 내용을 바탕으로 AI가 전문적인 요약을 생성합니다. (임의의 증상/상태는 지어내지 않습니다)")
566
-
567
- ai_opinion = ""
568
- if st.form_submit_button("🤖 AI 총평 임시 생성"):
569
- if not c_content.strip():
570
- st.error("상담내용을 입력해야 AI 총평을 구성할 수 있습니다.")
571
- else:
572
- sys_prompt = (
573
- "당신은 장기요양기관 평가와 상담기록 작성에 숙련된 20년 경력의 사회복지사입니다. "
574
- "평가 기준에 부합하게 핵심이 일목요연하고 명료한 종합소견으로 정리해 주십시오."
575
- )
576
- user_prompt = f"""
577
- [수급자 정보]
578
- 이름: {c_name} (가명: {c_masked})
579
- 장기요양등급: {safe(client_row["장기요양등급"])}
580
-
581
- [상담 기록]
582
- 상담사유: {c_reason}
583
- 상담내용: {c_content}
584
- 조치계획: {c_plan}
585
- 추가욕구요청사항: {c_needs}
586
-
587
- [주의사항/제약]
588
- - 상담 내용과 조치 계획에 기재되지 않은 사실(예: 낙상 흔적, 욕창 발생, 침해 행동, 기저귀 젖음 등)을 AI가 독단적으로 지어내거나 추정하여 기술하지 마십시오.
589
- - 오직 입력된 정보만을 바탕으로 사회복지사 종합 소견 형식의 문장들로 1., 2., 3. 번호 형태로 정리해주십시오.
590
- """
591
- ai_opinion = generate_ai_opinion(sys_prompt, user_prompt, c_name, c_reason, c_content)
592
- st.session_state["temp_ai_counsel"] = ai_opinion
593
-
594
- final_opinion = st.text_area("종합소견 (직접 보완 가능)", value=st.session_state.get("temp_ai_counsel", ""), height=120)
595
-
596
- save_counsel = st.form_submit_button("📝 상담일지 저장 및 허깅페이스 연동")
597
-
598
- if save_counsel:
599
- if not c_content.strip():
600
- st.error("상담내용을 입력해 주세요.")
601
- else:
602
- new_no = len(df_counseling) + 1
603
- new_row = {
604
- "NO.": new_no,
605
- "수급자이름": c_name,
606
- "가명표기": c_masked,
607
- "상담일자": str(c_date),
608
- "상담자": c_writer.strip(),
609
- "상담분류": c_type,
610
- "상담사유": c_reason,
611
- "상담내용": c_content.strip(),
612
- "조치계획": c_plan.strip() if c_plan.strip() else final_opinion.strip(),
613
- "추가욕구요청사항": c_needs.strip(),
614
- "사례관리필요": "True" if need_case else "False",
615
- "욕구사정필요": "True" if need_needs else "False",
616
- "급여제공계획변경필요": "True" if need_careplan else "False",
617
- "등록일자": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
618
- }
619
- df_counseling = pd.concat([df_counseling, pd.DataFrame([new_row])], ignore_index=True)
620
- save_excel_data(df_counseling, "data/counseling_logs.xlsx")
621
- db_sync.upload_all()
622
-
623
- # 세션 템플릿 비우기
624
- if "temp_ai_counsel" in st.session_state:
625
- del st.session_state["temp_ai_counsel"]
626
-
627
- st.success("상담일지 저장이 완료되었으며 실시간 업로드 동기화가 끝났습니다!")
628
- st.rerun()
629
-
630
- st.markdown("---")
631
- st.markdown("##### 📂 등록된 상담일지 목록")
632
- if df_counseling.empty:
633
- st.info("작성된 상담일지 내역이 ��습니다.")
634
- else:
635
- st.dataframe(df_counseling, use_container_width=True, hide_index=True)
636
-
637
- # ==========================================
638
- # 탭 3: 사례관리
639
- # ==========================================
640
- with tab3:
641
- st.subheader("📋 사례관리 회의록 작성 및 연동 관리")
642
- df_counseling = load_counseling()
643
- df_case = load_case_management()
644
-
645
- # ⚠️ 연동 규칙 필터링
646
- # 상담일지에서 사례관리필요 == True 이거나 추가욕구요청사항에 "사례관리" 단어가 포함된 것만 추출
647
- qualified_clients = []
648
- if not df_counseling.empty:
649
- # 문자열로 변환하여 안전하게 필터링
650
- df_counseling["사례관리필요"] = df_counseling["사례관리필요"].astype(str)
651
- df_counseling["추가욕구요청사항"] = df_counseling["추가욕구요청사항"].fillna("")
652
-
653
- filtered_df = df_counseling[
654
- (df_counseling["사례관리필요"] == "True") |
655
- (df_counseling["추가욕구요청사항"].str.contains("사례관리", case=False))
656
- ]
657
-
658
- if not filtered_df.empty:
659
- qualified_clients = filtered_df["수급자이름"].unique().tolist()
660
-
661
- if not qualified_clients:
662
- st.warning("현재 상담일지에서 '사례관리 필요'로 선별되거나 '추가욕구요청사항'에 '사례관리'가 지정된 연동 대상 어르신이 없습니다.")
663
- st.info("상담일지 작성 시 후속 업무 연동에서 '사례관리 회의 회부 필요'를 체크하시면 이곳에 자동으로 등록됩니다.")
664
- else:
665
- st.markdown("##### 🔗 상담 연동 사례관리 대상자 선택")
666
- selected_case_name = st.selectbox("사례관리 대상 어르신 선택", qualified_clients, key="case_client_select")
667
-
668
- # 해당 어르신의 최근 연동 상담 내역 요약 노출
669
- ref_counsel_logs = df_counseling[df_counseling["수급자이름"] == selected_case_name].sort_values(by="상담일자", ascending=False)
670
- latest_counsel = ref_counsel_logs.iloc[0]
671
-
672
- st.markdown(f"""
673
- <div style="background: #e1f5fe; border-left: 6px solid #03a9f4; padding: 12px; border-radius: 10px; margin-bottom: 12px; color: #222;">
674
- 📝 <strong>연동된 최근 상담 정보 ({latest_counsel['상담일자']}):</strong><br>
675
- • <strong>상담사유:</strong> {latest_counsel['상담사유']}<br>
676
- • <strong>상담내용:</strong> {latest_counsel['상담내용']}<br>
677
- • <strong>추가욕구/요청:</strong> {latest_counsel['추가욕구요청사항']}
678
- </div>
679
- """, unsafe_allow_html=True)
680
-
681
- with st.form("case_management_form"):
682
- col_m1, col_m2 = st.columns(2)
683
- m_name = col_m1.text_input("수급자 성명", value=selected_case_name, disabled=True)
684
- m_masked = col_m2.text_input("가명 표기", value=safe(latest_counsel["가명표기"]), disabled=True)
685
-
686
- col_m3, col_m4, col_m5 = st.columns(3)
687
- m_date = col_m3.date_input("회의 일자", value=date.today())
688
- m_participants = col_m4.text_input("참석자", value="시설장, 사회복지사, 간호조무사, 요양보호사")
689
- m_type = col_m5.selectbox("회의 구분", ["정기 사례회의", "응급 사례회의", "수시 사례회의"])
690
-
691
- m_reason = st.text_area("사례 선정 이유", value=f"상담기록 연동에 의거, 상담 사유 '{latest_counsel['상담사유']}' 및 추가 요청 '{latest_counsel['추가욕구요청사항']}' 해결을 위한 조율이 시급하여 사례회의 대상자로 선정함.", height=70)
692
-
693
- st.markdown("##### 📝 회의 핵심 기록")
694
- m_first_plan = st.text_area("해결 방안 및 1차 계획", placeholder="회의를 통해 결정된 구체적인 실행 계획을 작성해 주세요.", height=90)
695
- m_process = st.text_area("시행 과정 기록", placeholder="해결 방안 적용 후 실행 과정상의 피드백이나 특이사항을 입력해 주세요.", height=90)
696
- m_result = st.text_area("종합 결과 및 2차 평가", placeholder="회의 결과 평가 및 향후 반영할 급여 내용을 작성해 주세요.", height=90)
697
-
698
- st.markdown("##### 🤖 AI 전문 소견 생성")
699
- st.caption("입력된 구체적인 내용에만 한정하여 AI가 사례회의 종합 의견을 생성합니다.")
700
-
701
- ai_case_opinion = ""
702
- if st.form_submit_button("🤖 AI 종합 의견 임시 생성"):
703
- if not m_first_plan.strip():
704
- st.error("1차 계획 및 해결방안을 입력해야 종합 소견 작성이 가능합니다.")
705
- else:
706
- sys_prompt = (
707
- "당신은 장기요양기관 평가에 정통한 노인복지 전문가이자 사회복지사입니다. "
708
- "사례관리 회의록의 결과를 평가 기준에 부합하게 명료한 문장들로 정리해 주십시오."
709
- )
710
- user_prompt = f"""
711
- [수급자]
712
- 이름: {m_name} (가명: {m_masked})
713
-
714
- [사례관리 기록]
715
- 선정이유: {m_reason}
716
- 해결방안 및 1차계획: {m_first_plan}
717
- 시행과정: {m_process}
718
- 종합결과(2차평가): {m_result}
719
-
720
- [제약조건]
721
- - 절대로 입력된 내용 이외에 다른 병증 상태나 응급 낙상 사건 등을 거짓으로 지어내지 마십시오.
722
- - 오직 입력된 문맥에 의거하여 종합적인 사례회의 소견을 1., 2., 3. 번호 형태로 정리해주십시오.
723
- """
724
- ai_case_opinion = generate_ai_opinion(sys_prompt, user_prompt, m_name, "사례회의", m_first_plan)
725
- st.session_state["temp_ai_case"] = ai_case_opinion
726
-
727
- final_case_opinion = st.text_area("사례회의 종합의견 보완", value=st.session_state.get("temp_ai_case", ""), height=100)
728
-
729
- save_case = st.form_submit_button("📋 사례관리 회의록 저장 및 허깅페이스 연동")
730
-
731
- if save_case:
732
- if not m_first_plan.strip():
733
- st.error("해결방안(1차계획)을 입력해 주세요.")
734
- else:
735
- new_no = len(df_case) + 1
736
- new_row = {
737
- "NO.": new_no,
738
- "수급자이름": m_name,
739
- "가명표기": m_masked,
740
- "회의일자": str(m_date),
741
- "참석자": m_participants.strip(),
742
- "회의분류": m_type,
743
- "사례선정이유": m_reason.strip(),
744
- "해결방안(1차계획)": m_first_plan.strip(),
745
- "시행과정": m_process.strip(),
746
- "종합결과(2차평가)": m_result.strip() if m_result.strip() else final_case_opinion.strip(),
747
- "등록일자": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
748
- }
749
- df_case = pd.concat([df_case, pd.DataFrame([new_row])], ignore_index=True)
750
- save_excel_data(df_case, "data/case_management.xlsx")
751
- db_sync.upload_all()
752
-
753
- if "temp_ai_case" in st.session_state:
754
- del st.session_state["temp_ai_case"]
755
-
756
- st.success("사례관리 회의록 저장이 완료되었으며 실시간 업로드 동기화가 끝났습니다!")
757
- st.rerun()
758
-
759
- st.markdown("---")
760
- st.markdown("##### 📂 등록된 사례관리 회의록 목록")
761
- if df_case.empty:
762
- st.info("작성된 사례관리 회의록 내역이 없습니다.")
763
- else:
764
- st.dataframe(df_case, use_container_width=True, hide_index=True)