Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -179,8 +179,10 @@ def to_markdown(file_path, end_pages, is_ocr, layout_mode, formula_enable, table
|
|
179 |
zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)
|
180 |
if zip_archive_success == 0:
|
181 |
logger.info("압축 성공")
|
|
|
182 |
else:
|
183 |
logger.error("압축 실패")
|
|
|
184 |
time.sleep(0.5)
|
185 |
|
186 |
progress(70, "마크다운 읽는 중...")
|
@@ -194,13 +196,13 @@ def to_markdown(file_path, end_pages, is_ocr, layout_mode, formula_enable, table
|
|
194 |
time.sleep(0.5)
|
195 |
|
196 |
progress(100, "변환 완료!")
|
197 |
-
return md_content
|
198 |
|
199 |
def to_markdown_comparison(file_a, file_b, end_pages, is_ocr, layout_mode, formula_enable, table_enable, language, progress=gr.Progress(track_tqdm=False)):
|
200 |
"""
|
201 |
두 개의 파일을 변환하여 A/B 비교를 위한 마크다운을 생성한다.
|
202 |
각 파일의 변환 결과는 "문서 A", "문서 B" 헤더로 구분되며,
|
203 |
-
두 문서 모두 업로드된 경우 두 문서의
|
204 |
"""
|
205 |
combined_md = ""
|
206 |
if file_a is not None:
|
@@ -212,7 +214,7 @@ def to_markdown_comparison(file_a, file_b, end_pages, is_ocr, layout_mode, formu
|
|
212 |
md_b = to_markdown(file_b, end_pages, is_ocr, layout_mode, formula_enable, table_enable, language, progress=progress)
|
213 |
combined_md += md_b + "\n"
|
214 |
if file_a is not None and file_b is not None:
|
215 |
-
combined_md += "### 비교 분석:\n두 문서의 차이점, 장단점 및
|
216 |
return combined_md
|
217 |
|
218 |
def init_model():
|
@@ -302,8 +304,7 @@ def convert_chat_messages_to_gradio_format(messages):
|
|
302 |
|
303 |
def stream_gemini_response(user_message: str, messages: list) -> Iterator[list]:
|
304 |
"""
|
305 |
-
Gemini 응답 스트리밍
|
306 |
-
(user_message가 공백이면 기본 문구로 대체)
|
307 |
"""
|
308 |
if not user_message.strip():
|
309 |
user_message = "...(No content from user)..."
|
@@ -318,7 +319,7 @@ def stream_gemini_response(user_message: str, messages: list) -> Iterator[list]:
|
|
318 |
response_buffer = ""
|
319 |
thinking_complete = False
|
320 |
|
321 |
-
# "Thinking" 역할
|
322 |
messages.append(
|
323 |
ChatMessage(
|
324 |
role="assistant",
|
@@ -332,7 +333,6 @@ def stream_gemini_response(user_message: str, messages: list) -> Iterator[list]:
|
|
332 |
parts = chunk.candidates[0].content.parts
|
333 |
current_chunk = parts[0].text
|
334 |
|
335 |
-
# 만약 parts가 2개라면, parts[0]는 thinking, parts[1]은 최종답변
|
336 |
if len(parts) == 2 and not thinking_complete:
|
337 |
thought_buffer += current_chunk
|
338 |
messages[-1] = ChatMessage(
|
@@ -367,7 +367,7 @@ def stream_gemini_response(user_message: str, messages: list) -> Iterator[list]:
|
|
367 |
|
368 |
def user_message(msg: str, history: list, doc_text: str) -> tuple[str, list]:
|
369 |
"""
|
370 |
-
|
371 |
"""
|
372 |
if doc_text.strip():
|
373 |
user_query = f"다음 문서를 참고하여 답변:\n\n{doc_text}\n\n질문: {msg}"
|
@@ -379,10 +379,7 @@ def user_message(msg: str, history: list, doc_text: str) -> tuple[str, list]:
|
|
379 |
|
380 |
def reset_states(file_a, file_b):
|
381 |
"""
|
382 |
-
새 파일 업로드 시
|
383 |
-
- chat_history -> 빈 리스트
|
384 |
-
- md_state -> 빈 문자열
|
385 |
-
- chatbot -> 빈 리스트
|
386 |
"""
|
387 |
return [], "", []
|
388 |
|
@@ -403,20 +400,24 @@ if __name__ == "__main__":
|
|
403 |
md_state = gr.State("") # 변환된 마크다운 텍스트 (두 파일의 결과 통합)
|
404 |
chat_history = gr.State([]) # ChatMessage 리스트
|
405 |
|
|
|
|
|
|
|
406 |
with gr.Row():
|
407 |
file_a = gr.File(label="문서 A 업로드", file_types=[".pdf", ".png", ".jpeg", ".jpg"], interactive=True)
|
408 |
file_b = gr.File(label="문서 B 업로드", file_types=[".pdf", ".png", ".jpeg", ".jpg"], interactive=True)
|
409 |
convert_btn = gr.Button("비교용 변환하기")
|
410 |
|
|
|
411 |
file_a.change(
|
412 |
fn=reset_states,
|
413 |
inputs=[file_a, file_b],
|
414 |
-
outputs=[chat_history, md_state,
|
415 |
)
|
416 |
file_b.change(
|
417 |
fn=reset_states,
|
418 |
inputs=[file_a, file_b],
|
419 |
-
outputs=[chat_history, md_state,
|
420 |
)
|
421 |
|
422 |
max_pages = gr.Slider(1, 20, 10, visible=False)
|
@@ -446,6 +447,7 @@ if __name__ == "__main__":
|
|
446 |
chat_input = gr.Textbox(lines=1, placeholder="질문을 입력하세요...")
|
447 |
clear_btn = gr.Button("대화 초기화")
|
448 |
|
|
|
449 |
chat_input.submit(
|
450 |
fn=user_message,
|
451 |
inputs=[chat_input, chat_history, md_state],
|
@@ -453,7 +455,7 @@ if __name__ == "__main__":
|
|
453 |
).then(
|
454 |
fn=stream_gemini_response,
|
455 |
inputs=[chat_input, chat_history],
|
456 |
-
outputs=
|
457 |
)
|
458 |
|
459 |
def clear_all():
|
@@ -462,7 +464,7 @@ if __name__ == "__main__":
|
|
462 |
clear_btn.click(
|
463 |
fn=clear_all,
|
464 |
inputs=[],
|
465 |
-
outputs=[chat_history, md_state,
|
466 |
)
|
467 |
|
468 |
demo.launch(server_name="0.0.0.0", server_port=7860, debug=True, ssr_mode=True)
|
|
|
179 |
zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)
|
180 |
if zip_archive_success == 0:
|
181 |
logger.info("압축 성공")
|
182 |
+
status_message = "\n\n**변환 완료 (압축 성공)**"
|
183 |
else:
|
184 |
logger.error("압축 실패")
|
185 |
+
status_message = "\n\n**변환 완료 (압축 실패)**"
|
186 |
time.sleep(0.5)
|
187 |
|
188 |
progress(70, "마크다운 읽는 중...")
|
|
|
196 |
time.sleep(0.5)
|
197 |
|
198 |
progress(100, "변환 완료!")
|
199 |
+
return md_content + status_message
|
200 |
|
201 |
def to_markdown_comparison(file_a, file_b, end_pages, is_ocr, layout_mode, formula_enable, table_enable, language, progress=gr.Progress(track_tqdm=False)):
|
202 |
"""
|
203 |
두 개의 파일을 변환하여 A/B 비교를 위한 마크다운을 생성한다.
|
204 |
각 파일의 변환 결과는 "문서 A", "문서 B" 헤더로 구분되며,
|
205 |
+
두 문서 모두 업로드된 경우 두 문서의 차이점, 장단점 및 주요 내용을 비교 분석하도록 추가 지시사항을 포함한다.
|
206 |
"""
|
207 |
combined_md = ""
|
208 |
if file_a is not None:
|
|
|
214 |
md_b = to_markdown(file_b, end_pages, is_ocr, layout_mode, formula_enable, table_enable, language, progress=progress)
|
215 |
combined_md += md_b + "\n"
|
216 |
if file_a is not None and file_b is not None:
|
217 |
+
combined_md += "### 비교 분석:\n두 문서의 차이점, 장단점 및 주요 내용을 비교 분석하십시오.\n"
|
218 |
return combined_md
|
219 |
|
220 |
def init_model():
|
|
|
304 |
|
305 |
def stream_gemini_response(user_message: str, messages: list) -> Iterator[list]:
|
306 |
"""
|
307 |
+
Gemini 응답 스트리밍 (user_message가 공백이면 기본 문구로 대체)
|
|
|
308 |
"""
|
309 |
if not user_message.strip():
|
310 |
user_message = "...(No content from user)..."
|
|
|
319 |
response_buffer = ""
|
320 |
thinking_complete = False
|
321 |
|
322 |
+
# "Thinking" 역할 추가
|
323 |
messages.append(
|
324 |
ChatMessage(
|
325 |
role="assistant",
|
|
|
333 |
parts = chunk.candidates[0].content.parts
|
334 |
current_chunk = parts[0].text
|
335 |
|
|
|
336 |
if len(parts) == 2 and not thinking_complete:
|
337 |
thought_buffer += current_chunk
|
338 |
messages[-1] = ChatMessage(
|
|
|
367 |
|
368 |
def user_message(msg: str, history: list, doc_text: str) -> tuple[str, list]:
|
369 |
"""
|
370 |
+
입력 프롬프트와 변환된 문서를 활용해 질문을 구성
|
371 |
"""
|
372 |
if doc_text.strip():
|
373 |
user_query = f"다음 문서를 참고하여 답변:\n\n{doc_text}\n\n질문: {msg}"
|
|
|
379 |
|
380 |
def reset_states(file_a, file_b):
|
381 |
"""
|
382 |
+
새 파일 업로드 시 chat_history와 md_state를 초기화 (Chatbot은 숨김 처리)
|
|
|
|
|
|
|
383 |
"""
|
384 |
return [], "", []
|
385 |
|
|
|
400 |
md_state = gr.State("") # 변환된 마크다운 텍스트 (두 파일의 결과 통합)
|
401 |
chat_history = gr.State([]) # ChatMessage 리스트
|
402 |
|
403 |
+
# 단일(숨김) Chatbot 컴포넌트: 화면에 보이지 않음
|
404 |
+
hidden_chatbot = gr.Chatbot(visible=False)
|
405 |
+
|
406 |
with gr.Row():
|
407 |
file_a = gr.File(label="문서 A 업로드", file_types=[".pdf", ".png", ".jpeg", ".jpg"], interactive=True)
|
408 |
file_b = gr.File(label="문서 B 업로드", file_types=[".pdf", ".png", ".jpeg", ".jpg"], interactive=True)
|
409 |
convert_btn = gr.Button("비교용 변환하기")
|
410 |
|
411 |
+
# 파일 업로드 시 상태 초기화 (Chatbot은 숨김 처리)
|
412 |
file_a.change(
|
413 |
fn=reset_states,
|
414 |
inputs=[file_a, file_b],
|
415 |
+
outputs=[chat_history, md_state, hidden_chatbot]
|
416 |
)
|
417 |
file_b.change(
|
418 |
fn=reset_states,
|
419 |
inputs=[file_a, file_b],
|
420 |
+
outputs=[chat_history, md_state, hidden_chatbot]
|
421 |
)
|
422 |
|
423 |
max_pages = gr.Slider(1, 20, 10, visible=False)
|
|
|
447 |
chat_input = gr.Textbox(lines=1, placeholder="질문을 입력하세요...")
|
448 |
clear_btn = gr.Button("대화 초기화")
|
449 |
|
450 |
+
# 채팅 입력 후, LLM 응답은 hidden_chatbot에 저장(화면에 보이지 않음)
|
451 |
chat_input.submit(
|
452 |
fn=user_message,
|
453 |
inputs=[chat_input, chat_history, md_state],
|
|
|
455 |
).then(
|
456 |
fn=stream_gemini_response,
|
457 |
inputs=[chat_input, chat_history],
|
458 |
+
outputs=hidden_chatbot
|
459 |
)
|
460 |
|
461 |
def clear_all():
|
|
|
464 |
clear_btn.click(
|
465 |
fn=clear_all,
|
466 |
inputs=[],
|
467 |
+
outputs=[chat_history, md_state, hidden_chatbot]
|
468 |
)
|
469 |
|
470 |
demo.launch(server_name="0.0.0.0", server_port=7860, debug=True, ssr_mode=True)
|