seawolf2357 commited on
Commit
e11a6cb
·
verified ·
1 Parent(s): f537804

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -79
app.py CHANGED
@@ -785,12 +785,13 @@ def process_file(file_path: str) -> tuple:
785
 
786
  def chat_response(
787
  message: str,
788
- history: List[List[str]],
789
  file: Optional[str],
790
  session_id: str,
791
  groq_api_key: str,
792
  fireworks_api_key: str
793
  ) -> Generator[tuple, None, None]:
 
794
 
795
  if not message.strip() and file is None:
796
  yield history, session_id
@@ -812,24 +813,37 @@ def chat_response(
812
  })
813
 
814
  if file_type == "error":
815
- history = history + [[message, f"❌ {file_content}"]]
 
 
 
816
  yield history, session_id
817
  return
818
  elif file_type == "unsupported":
819
- history = history + [[message, f"⚠️ {file_content}"]]
 
 
 
820
  yield history, session_id
821
  return
822
 
 
823
  user_display_message = message
824
  if file is not None:
825
  filename = os.path.basename(file)
826
  user_display_message = f"📎 {filename}\n\n{message}" if message else f"📎 {filename}"
827
 
828
- history = history + [[user_display_message, ""]]
 
 
 
 
829
  yield history, session_id
830
 
 
831
  db_messages = get_session_messages(session_id, limit=10)
832
 
 
833
  api_messages = []
834
 
835
  api_messages.append({
@@ -857,17 +871,20 @@ def chat_response(
857
  if file_type == "image":
858
  for chunk in call_fireworks_api_stream(api_messages, file_content, file_mime, fireworks_api_key):
859
  full_response += chunk
860
- history[-1][1] = full_response
 
861
  yield history, session_id
862
  else:
863
  for chunk in call_groq_api_stream(api_messages, groq_api_key):
864
  full_response += chunk
865
- history[-1][1] = full_response
866
  yield history, session_id
867
 
 
868
  save_message(session_id, "user", current_content, file_info)
869
  save_message(session_id, "assistant", full_response)
870
 
 
871
  if len(db_messages) == 0 and message:
872
  title = message[:50] + "..." if len(message) > 50 else message
873
  update_session_title(session_id, title)
@@ -881,18 +898,10 @@ def load_session(session_id: str) -> tuple:
881
  return [], ""
882
 
883
  messages = get_session_messages(session_id, limit=50)
 
884
  history = []
885
-
886
- i = 0
887
- while i < len(messages):
888
- if messages[i]["role"] == "user":
889
- user_msg = messages[i]["content"]
890
- assistant_msg = ""
891
- if i + 1 < len(messages) and messages[i + 1]["role"] == "assistant":
892
- assistant_msg = messages[i + 1]["content"]
893
- i += 1
894
- history.append([user_msg, assistant_msg])
895
- i += 1
896
 
897
  return history, session_id
898
 
@@ -1141,10 +1150,6 @@ def convert_hwp(file, output_format, progress=gr.Progress()):
1141
 
1142
  # ============== CSS 스타일 ==============
1143
  css = """
1144
- #col-container {
1145
- margin: 0 auto;
1146
- max-width: 1200px;
1147
- }
1148
  .upload-box {
1149
  border: 2px dashed #6366f1 !important;
1150
  border-radius: 12px !important;
@@ -1152,7 +1157,6 @@ css = """
1152
  .download-box {
1153
  border: 2px solid #22c55e !important;
1154
  border-radius: 12px !important;
1155
- background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%) !important;
1156
  }
1157
  .preview-box {
1158
  max-height: 400px;
@@ -1217,6 +1221,7 @@ with gr.Blocks(title="AI 문서 어시스턴트") as demo:
1217
  refresh_sessions_btn = gr.Button("🔄 새로고침", size="sm")
1218
 
1219
  with gr.Column(scale=3):
 
1220
  chatbot = gr.Chatbot(
1221
  label="대화",
1222
  height=500
@@ -1245,71 +1250,73 @@ with gr.Blocks(title="AI 문서 어시스턴트") as demo:
1245
 
1246
  # Tab 2: HWP 변환기
1247
  with gr.Tab("📄 HWP 변환기", id="converter"):
1248
- with gr.Column(elem_id="col-container"):
1249
- gr.Markdown("""
1250
- ### HWP 파일 변환기
1251
- 한글(HWP) 문서를 다양한 형식으로 변환합니다.
1252
- """)
1253
-
1254
- with gr.Row():
1255
- with gr.Column(scale=1):
1256
- gr.Markdown("#### 📤 파일 업로드")
1257
- hwp_file_input = gr.File(
1258
- label="HWP 파일 선택",
1259
- file_types=[".hwp"],
1260
- type="filepath",
1261
- elem_classes=["upload-box"]
1262
- )
1263
-
1264
- format_select = gr.Radio(
1265
- label="변환 형식",
1266
- choices=["HTML", "ODT (OpenDocument)", "TXT (텍스트)", "Markdown", "XML"],
1267
- value="TXT (텍스트)",
1268
- info="원하는 출력 형식을 선택하세요"
1269
- )
1270
-
1271
- convert_btn = gr.Button("🔄 변환하기", variant="primary", size="lg")
1272
 
1273
- with gr.Column(scale=1):
1274
- gr.Markdown("#### 📥 변환 결과")
1275
- status_output = gr.Textbox(
1276
- label="상태",
1277
- interactive=False,
1278
- lines=2
1279
- )
1280
-
1281
- file_output = gr.File(
1282
- label="다운로드",
1283
- elem_classes=["download-box"]
1284
- )
1285
 
1286
- with gr.Accordion("📋 내용 미리보기", open=False):
1287
- preview_output = gr.Textbox(
1288
- label="",
1289
- lines=15,
1290
- max_lines=25,
1291
  interactive=False,
1292
- elem_classes=["preview-box"]
1293
  )
1294
-
1295
- gr.Markdown("""
1296
- ---
1297
- #### ℹ️ 안내사항
1298
-
1299
- | 형식 | 설명 | 용도 |
1300
- |------|------|------|
1301
- | **HTML** | 웹 페이지 형식 | 브라우저에서 보기 |
1302
- | **ODT** | OpenDocument | LibreOffice, Google Docs |
1303
- | **TXT** | 순수 텍스트 | 텍스트 추출 |
1304
- | **Markdown** | 마크다운 형식 | GitHub, 노션 |
1305
- | **XML** | 구조화 데이터 | 데이터 처리 |
1306
-
1307
- > ⚠️ HWP v5 형식(한글 2007+)만 지원 | 암호화 파일 불가
1308
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1309
 
1310
  # ============== 이벤트 핸들러 ==============
1311
 
1312
  def on_submit(message, history, file, session_id, groq_key, fireworks_key):
 
 
 
1313
  for result in chat_response(message, history, file, session_id, groq_key, fireworks_key):
1314
  yield result[0], result[1], "", None
1315
 
 
785
 
786
  def chat_response(
787
  message: str,
788
+ history: List[Dict],
789
  file: Optional[str],
790
  session_id: str,
791
  groq_api_key: str,
792
  fireworks_api_key: str
793
  ) -> Generator[tuple, None, None]:
794
+ """채팅 응답 생성 (Gradio 6.0 messages 형식)"""
795
 
796
  if not message.strip() and file is None:
797
  yield history, session_id
 
813
  })
814
 
815
  if file_type == "error":
816
+ history = history + [
817
+ {"role": "user", "content": message or "파일 업로드"},
818
+ {"role": "assistant", "content": f"❌ {file_content}"}
819
+ ]
820
  yield history, session_id
821
  return
822
  elif file_type == "unsupported":
823
+ history = history + [
824
+ {"role": "user", "content": message or "파일 업로드"},
825
+ {"role": "assistant", "content": f"⚠️ {file_content}"}
826
+ ]
827
  yield history, session_id
828
  return
829
 
830
+ # 사용자 메시지 구성
831
  user_display_message = message
832
  if file is not None:
833
  filename = os.path.basename(file)
834
  user_display_message = f"📎 {filename}\n\n{message}" if message else f"📎 {filename}"
835
 
836
+ # 히스토리에 사용자 메시지와 빈 어시스턴트 메시지 추가
837
+ history = history + [
838
+ {"role": "user", "content": user_display_message},
839
+ {"role": "assistant", "content": ""}
840
+ ]
841
  yield history, session_id
842
 
843
+ # DB에서 이전 대화 가져오기
844
  db_messages = get_session_messages(session_id, limit=10)
845
 
846
+ # API 메시지 구성
847
  api_messages = []
848
 
849
  api_messages.append({
 
871
  if file_type == "image":
872
  for chunk in call_fireworks_api_stream(api_messages, file_content, file_mime, fireworks_api_key):
873
  full_response += chunk
874
+ # 마지막 메시지(assistant) 업데이트
875
+ history[-1] = {"role": "assistant", "content": full_response}
876
  yield history, session_id
877
  else:
878
  for chunk in call_groq_api_stream(api_messages, groq_api_key):
879
  full_response += chunk
880
+ history[-1] = {"role": "assistant", "content": full_response}
881
  yield history, session_id
882
 
883
+ # DB에 저장
884
  save_message(session_id, "user", current_content, file_info)
885
  save_message(session_id, "assistant", full_response)
886
 
887
+ # 첫 메시지면 세션 제목 업데이트
888
  if len(db_messages) == 0 and message:
889
  title = message[:50] + "..." if len(message) > 50 else message
890
  update_session_title(session_id, title)
 
898
  return [], ""
899
 
900
  messages = get_session_messages(session_id, limit=50)
901
+ # Gradio 6.0 messages 형식으로 변환
902
  history = []
903
+ for msg in messages:
904
+ history.append({"role": msg["role"], "content": msg["content"]})
 
 
 
 
 
 
 
 
 
905
 
906
  return history, session_id
907
 
 
1150
 
1151
  # ============== CSS 스타일 ==============
1152
  css = """
 
 
 
 
1153
  .upload-box {
1154
  border: 2px dashed #6366f1 !important;
1155
  border-radius: 12px !important;
 
1157
  .download-box {
1158
  border: 2px solid #22c55e !important;
1159
  border-radius: 12px !important;
 
1160
  }
1161
  .preview-box {
1162
  max-height: 400px;
 
1221
  refresh_sessions_btn = gr.Button("🔄 새로고침", size="sm")
1222
 
1223
  with gr.Column(scale=3):
1224
+ # Gradio 6.0: Chatbot은 기본적으로 messages 형식 사용
1225
  chatbot = gr.Chatbot(
1226
  label="대화",
1227
  height=500
 
1250
 
1251
  # Tab 2: HWP 변환기
1252
  with gr.Tab("📄 HWP 변환기", id="converter"):
1253
+ gr.Markdown("""
1254
+ ### HWP 파일 변환기
1255
+ 한글(HWP) 문서를 다양한 형식으로 변환합니다.
1256
+ """)
1257
+
1258
+ with gr.Row():
1259
+ with gr.Column(scale=1):
1260
+ gr.Markdown("#### 📤 파일 업로드")
1261
+ hwp_file_input = gr.File(
1262
+ label="HWP 파일 선택",
1263
+ file_types=[".hwp"],
1264
+ type="filepath",
1265
+ elem_classes=["upload-box"]
1266
+ )
 
 
 
 
 
 
 
 
 
 
1267
 
1268
+ format_select = gr.Radio(
1269
+ label="변환 형식",
1270
+ choices=["HTML", "ODT (OpenDocument)", "TXT (텍스트)", "Markdown", "XML"],
1271
+ value="TXT (텍스트)",
1272
+ info="원하는 출력 형식을 선택하세요"
1273
+ )
1274
+
1275
+ convert_btn = gr.Button("🔄 변환하기", variant="primary", size="lg")
 
 
 
 
1276
 
1277
+ with gr.Column(scale=1):
1278
+ gr.Markdown("#### 📥 변환 결과")
1279
+ status_output = gr.Textbox(
1280
+ label="상태",
 
1281
  interactive=False,
1282
+ lines=2
1283
  )
1284
+
1285
+ file_output = gr.File(
1286
+ label="다운로드",
1287
+ elem_classes=["download-box"]
1288
+ )
1289
+
1290
+ with gr.Accordion("📋 내용 미리보기", open=False):
1291
+ preview_output = gr.Textbox(
1292
+ label="",
1293
+ lines=15,
1294
+ max_lines=25,
1295
+ interactive=False,
1296
+ elem_classes=["preview-box"]
1297
+ )
1298
+
1299
+ gr.Markdown("""
1300
+ ---
1301
+ #### ℹ️ 안내사항
1302
+
1303
+ | 형식 | 설명 | 용도 |
1304
+ |------|------|------|
1305
+ | **HTML** | 웹 페이지 형식 | 브라우저에서 보기 |
1306
+ | **ODT** | OpenDocument | LibreOffice, Google Docs |
1307
+ | **TXT** | 순수 텍스트 | 텍스트 추출 |
1308
+ | **Markdown** | 마크다운 형식 | GitHub, 노션 |
1309
+ | **XML** | 구조화 데이터 | 데이터 처리 |
1310
+
1311
+ > ⚠️ HWP v5 형식(한글 2007+)만 지원 | 암호화 파일 불가
1312
+ """)
1313
 
1314
  # ============== 이벤트 핸들러 ==============
1315
 
1316
  def on_submit(message, history, file, session_id, groq_key, fireworks_key):
1317
+ # history가 None이면 빈 리스트로 초기화
1318
+ if history is None:
1319
+ history = []
1320
  for result in chat_response(message, history, file, session_id, groq_key, fireworks_key):
1321
  yield result[0], result[1], "", None
1322