Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -11,22 +11,52 @@ import pymupdf
|
|
11 |
###############################
|
12 |
# 환경 설정
|
13 |
###############################
|
|
|
14 |
os.system('pip uninstall -y magic-pdf')
|
15 |
os.system('pip install git+https://github.com/opendatalab/MinerU.git@dev')
|
16 |
os.system('wget https://github.com/opendatalab/MinerU/raw/dev/scripts/download_models_hf.py -O download_models_hf.py')
|
17 |
-
os.system('python download_models_hf.py')
|
18 |
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
21 |
|
22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
if os.getenv('apikey'):
|
24 |
data['llm-aided-config']['title_aided']['api_key'] = os.getenv('apikey')
|
25 |
data['llm-aided-config']['title_aided']['enable'] = True
|
26 |
|
27 |
-
|
|
|
28 |
json.dump(data, file, indent=4)
|
29 |
|
|
|
30 |
os.system('cp -r paddleocr /home/user/.paddleocr')
|
31 |
|
32 |
###############################
|
@@ -145,7 +175,7 @@ def replace_image_with_base64(markdown_text, image_dir_path):
|
|
145 |
def to_pdf(file_path):
|
146 |
"""
|
147 |
이미지(JPG/PNG 등)를 PDF로 컨버팅.
|
148 |
-
TXT, CSV 파일인 경우 변환 없이 원본 경로를
|
149 |
"""
|
150 |
ext = Path(file_path).suffix.lower()
|
151 |
if ext in ['.txt', '.csv']:
|
@@ -286,7 +316,7 @@ def format_chat_history(messages: list) -> list:
|
|
286 |
|
287 |
def convert_chat_messages_to_gradio_format(messages):
|
288 |
"""
|
289 |
-
ChatMessage list -> [
|
290 |
"""
|
291 |
gradio_chat = []
|
292 |
user_text, assistant_text = None, None
|
@@ -309,7 +339,7 @@ def convert_chat_messages_to_gradio_format(messages):
|
|
309 |
|
310 |
def stream_gemini_response(user_message: str, messages: list) -> Iterator[list]:
|
311 |
"""
|
312 |
-
Gemini
|
313 |
"""
|
314 |
if not user_message.strip():
|
315 |
user_message = "...(No content from user)..."
|
@@ -358,12 +388,12 @@ def stream_gemini_response(user_message: str, messages: list) -> Iterator[list]:
|
|
358 |
print(f"\n=== [Gemini] Final Response ===\n{response_buffer}")
|
359 |
except Exception as e:
|
360 |
print(f"\n=== [Gemini] Error ===\n{str(e)}")
|
361 |
-
messages.append(ChatMessage(role="assistant", content=f"
|
362 |
yield convert_chat_messages_to_gradio_format(messages)
|
363 |
|
364 |
def user_message(msg: str, history: list, doc_text: str) -> tuple[str, list]:
|
365 |
"""
|
366 |
-
|
367 |
"""
|
368 |
if doc_text.strip():
|
369 |
user_query = f"다음 문서를 참고하여 답변:\n\n{doc_text}\n\n질문: {msg}"
|
@@ -374,7 +404,7 @@ def user_message(msg: str, history: list, doc_text: str) -> tuple[str, list]:
|
|
374 |
|
375 |
def reset_states(file_a, file_b):
|
376 |
"""
|
377 |
-
새 파일 업로드 시 chat_history
|
378 |
"""
|
379 |
return [], "", ""
|
380 |
|
@@ -394,7 +424,7 @@ if __name__ == "__main__":
|
|
394 |
|
395 |
# 변환 결과를 보여줄 visible Markdown 컴포넌트
|
396 |
conversion_md = gr.Markdown(label="변환 결과", visible=True)
|
397 |
-
md_state = gr.State("") # 내부 상태 (문서 변환 결과)
|
398 |
chat_history = gr.State([]) # ChatMessage 리스트
|
399 |
|
400 |
# visible Chatbot 컴포넌트
|
@@ -463,4 +493,5 @@ if __name__ == "__main__":
|
|
463 |
outputs=[chat_history, md_state, chatbot]
|
464 |
)
|
465 |
|
|
|
466 |
demo.launch(server_name="0.0.0.0", server_port=7860, debug=True, ssr_mode=True)
|
|
|
11 |
###############################
|
12 |
# 환경 설정
|
13 |
###############################
|
14 |
+
# 필요 없다면 주석 처리 가능
|
15 |
os.system('pip uninstall -y magic-pdf')
|
16 |
os.system('pip install git+https://github.com/opendatalab/MinerU.git@dev')
|
17 |
os.system('wget https://github.com/opendatalab/MinerU/raw/dev/scripts/download_models_hf.py -O download_models_hf.py')
|
|
|
18 |
|
19 |
+
# 모델 다운로드 (네트워크가 없는 환경이라면 try/except로 묶거나 주석 처리)
|
20 |
+
try:
|
21 |
+
os.system('python download_models_hf.py')
|
22 |
+
except Exception as e:
|
23 |
+
print("모델 다운로드 중 에러가 발생했습니다. 네트워크 연결을 확인하거나, 수동으로 모델을 배치하세요.")
|
24 |
+
print("에러 메시지:", e)
|
25 |
|
26 |
+
###############################
|
27 |
+
# magic-pdf.json 처리
|
28 |
+
###############################
|
29 |
+
json_path = "/home/user/magic-pdf.json"
|
30 |
+
if os.path.exists(json_path):
|
31 |
+
# 기존에 파일이 있으면 로드
|
32 |
+
with open(json_path, 'r', encoding='utf-8') as file:
|
33 |
+
data = json.load(file)
|
34 |
+
else:
|
35 |
+
# 없으면 기본값 생성
|
36 |
+
data = {
|
37 |
+
"device-mode": "cuda", # CPU만 쓰려면 "cpu"
|
38 |
+
"llm-aided-config": {
|
39 |
+
"title_aided": {
|
40 |
+
"api_key": os.getenv('apikey', ""),
|
41 |
+
"enable": bool(os.getenv('apikey'))
|
42 |
+
}
|
43 |
+
}
|
44 |
+
}
|
45 |
+
# 파일 생성 (필요 없으면 생략)
|
46 |
+
with open(json_path, 'w', encoding='utf-8') as file:
|
47 |
+
json.dump(data, file, indent=4)
|
48 |
+
|
49 |
+
# 이후 device-mode나 llm-aided-config 필요한 경우 수정
|
50 |
+
data['device-mode'] = "cuda" # 원하는 디바이스로 세팅
|
51 |
if os.getenv('apikey'):
|
52 |
data['llm-aided-config']['title_aided']['api_key'] = os.getenv('apikey')
|
53 |
data['llm-aided-config']['title_aided']['enable'] = True
|
54 |
|
55 |
+
# 변경사항 다시 저장
|
56 |
+
with open(json_path, 'w', encoding='utf-8') as file:
|
57 |
json.dump(data, file, indent=4)
|
58 |
|
59 |
+
# paddleocr 복사
|
60 |
os.system('cp -r paddleocr /home/user/.paddleocr')
|
61 |
|
62 |
###############################
|
|
|
175 |
def to_pdf(file_path):
|
176 |
"""
|
177 |
이미지(JPG/PNG 등)를 PDF로 컨버팅.
|
178 |
+
TXT, CSV 파일인 경우 변환 없이 원본 경로를 그대로 반환.
|
179 |
"""
|
180 |
ext = Path(file_path).suffix.lower()
|
181 |
if ext in ['.txt', '.csv']:
|
|
|
316 |
|
317 |
def convert_chat_messages_to_gradio_format(messages):
|
318 |
"""
|
319 |
+
ChatMessage list -> [(유저발화, 봇응답), ...] 형태로 변환
|
320 |
"""
|
321 |
gradio_chat = []
|
322 |
user_text, assistant_text = None, None
|
|
|
339 |
|
340 |
def stream_gemini_response(user_message: str, messages: list) -> Iterator[list]:
|
341 |
"""
|
342 |
+
Gemini 응답을 스트리밍 형태로 출력 (user_message 공백 시 임시 문구 사용)
|
343 |
"""
|
344 |
if not user_message.strip():
|
345 |
user_message = "...(No content from user)..."
|
|
|
388 |
print(f"\n=== [Gemini] Final Response ===\n{response_buffer}")
|
389 |
except Exception as e:
|
390 |
print(f"\n=== [Gemini] Error ===\n{str(e)}")
|
391 |
+
messages.append(ChatMessage(role="assistant", content=f"오류가 발생했습니다: {str(e)}"))
|
392 |
yield convert_chat_messages_to_gradio_format(messages)
|
393 |
|
394 |
def user_message(msg: str, history: list, doc_text: str) -> tuple[str, list]:
|
395 |
"""
|
396 |
+
문서 변환 결과(문자열)와 함께 질의를 결합하여 history에 추가
|
397 |
"""
|
398 |
if doc_text.strip():
|
399 |
user_query = f"다음 문서를 참고하여 답변:\n\n{doc_text}\n\n질문: {msg}"
|
|
|
404 |
|
405 |
def reset_states(file_a, file_b):
|
406 |
"""
|
407 |
+
새 파일 업로드 시 chat_history, md_state, chatbot을 초기화
|
408 |
"""
|
409 |
return [], "", ""
|
410 |
|
|
|
424 |
|
425 |
# 변환 결과를 보여줄 visible Markdown 컴포넌트
|
426 |
conversion_md = gr.Markdown(label="변환 결과", visible=True)
|
427 |
+
md_state = gr.State("") # 내부 상태 (문서 변환 결과 저장)
|
428 |
chat_history = gr.State([]) # ChatMessage 리스트
|
429 |
|
430 |
# visible Chatbot 컴포넌트
|
|
|
493 |
outputs=[chat_history, md_state, chatbot]
|
494 |
)
|
495 |
|
496 |
+
# 로컬 서버 실행
|
497 |
demo.launch(server_name="0.0.0.0", server_port=7860, debug=True, ssr_mode=True)
|