Spaces:
Runtime error
Runtime error
File size: 23,476 Bytes
0cc1374 c1ae26a 0cc1374 0a681f9 0cc1374 084672b 125d9ca 211503b 5bada5a a7cd5ed 0cc1374 66eda5d 1d8778f cf7458b 084672b cf7458b 0cc1374 084672b 0cc1374 084672b ee6fe06 0cc1374 084672b b0061a0 084672b b0061a0 be51037 fdc1e97 be51037 b0061a0 be51037 00039aa b0061a0 be51037 b0061a0 be51037 b0061a0 a1dc3ca b0061a0 be51037 b0061a0 0cc1374 ee6fe06 0cc1374 a011e6d 0cc1374 fdc1e97 0cc1374 a011e6d 00039aa 0cc1374 a1dc3ca 084672b a1dc3ca fdc1e97 084672b 00039aa 630dc5d 00039aa 630dc5d 00039aa 630dc5d cf7458b 630dc5d cf7458b 630dc5d a1dc3ca b07522c 084672b b07522c fdc1e97 a9fc50d fdc1e97 b07522c 34bd9cd b07522c 084672b a011e6d fdc1e97 a011e6d fdc1e97 a011e6d 02e04a3 a011e6d 084672b be51037 a1dc3ca 084672b a1dc3ca 22b544c a1dc3ca 22b544c a1dc3ca 084672b a1dc3ca 084672b 00039aa cf7458b a1dc3ca fdc1e97 a1dc3ca 084672b a1dc3ca be51037 a1dc3ca 084672b a1dc3ca b0061a0 be51037 a1dc3ca be51037 a1dc3ca 084672b a1dc3ca be51037 a1dc3ca 084672b a1dc3ca b0061a0 a1dc3ca be51037 a1dc3ca fdc1e97 a1dc3ca fdc1e97 be51037 a1dc3ca be51037 084672b fdc1e97 22b544c fdc1e97 be51037 a1dc3ca cf7458b 21d018a cf7458b a1dc3ca 084672b cf7458b 084672b a1dc3ca 084672b a1dc3ca 084672b a1dc3ca 084672b 00039aa 084672b a1dc3ca 084672b a1dc3ca 084672b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 |
import base64
import json
import os
import time
import zipfile
from pathlib import Path
import re
import uuid
import pymupdf
###############################
# ํ๊ฒฝ ์ค์
###############################
os.system('pip uninstall -y magic-pdf')
os.system('pip install git+https://github.com/opendatalab/MinerU.git@dev')
os.system('wget https://github.com/opendatalab/MinerU/raw/dev/scripts/download_models_hf.py -O download_models_hf.py')
os.system('python download_models_hf.py')
with open('/home/user/magic-pdf.json', 'r') as file:
data = json.load(file)
data['device-mode'] = "cuda"
if os.getenv('apikey'):
data['llm-aided-config']['title_aided']['api_key'] = os.getenv('apikey')
data['llm-aided-config']['title_aided']['enable'] = True
with open('/home/user/magic-pdf.json', 'w') as file:
json.dump(data, file, indent=4)
os.system('cp -r paddleocr /home/user/.paddleocr')
###############################
# ๊ทธ ์ธ ๋ผ์ด๋ธ๋ฌ๋ฆฌ
###############################
import gradio as gr
from loguru import logger
from gradio_pdf import PDF
###############################
# magic_pdf ๊ด๋ จ ๋ชจ๋
###############################
from magic_pdf.data.data_reader_writer import FileBasedDataReader
from magic_pdf.libs.hash_utils import compute_sha256
from magic_pdf.tools.common import do_parse, prepare_env
###############################
# ๊ณตํต ํจ์๋ค
###############################
def create_css():
"""
๊ธฐ๋ณธ CSS ์คํ์ผ.
"""
return """
.gradio-container {
width: 100vw !important;
min-height: 100vh !important;
margin: 0 !important;
padding: 0 !important;
background: linear-gradient(135deg, #EFF6FF 0%, #F5F3FF 100%);
display: flex;
flex-direction: column;
overflow-y: auto !important;
}
.title-area {
text-align: center;
margin: 1rem auto;
padding: 1rem;
background: white;
border-radius: 1rem;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
max-width: 800px;
}
.title-area h1 {
background: linear-gradient(90deg, #2563EB 0%, #7C3AED 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 2.5rem;
font-weight: bold;
margin-bottom: 0.5rem;
}
.title-area p {
color: #6B7280;
font-size: 1.1rem;
}
.invisible {
display: none !important;
}
.gr-block, .gr-box {
padding: 0.5rem !important;
}
"""
def read_fn(path):
disk_rw = FileBasedDataReader(os.path.dirname(path))
return disk_rw.read(os.path.basename(path))
def parse_pdf(doc_path, output_dir, end_page_id, is_ocr, layout_mode, formula_enable, table_enable, language):
os.makedirs(output_dir, exist_ok=True)
try:
file_name = f"{str(Path(doc_path).stem)}_{time.time()}"
pdf_data = read_fn(doc_path)
parse_method = "ocr" if is_ocr else "auto"
local_image_dir, local_md_dir = prepare_env(output_dir, file_name, parse_method)
do_parse(
output_dir,
file_name,
pdf_data,
[],
parse_method,
False,
end_page_id=end_page_id,
layout_model=layout_mode,
formula_enable=formula_enable,
table_enable=table_enable,
lang=language,
f_dump_orig_pdf=False
)
return local_md_dir, file_name
except Exception as e:
logger.exception(e)
def compress_directory_to_zip(directory_path, output_zip_path):
try:
with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(directory_path):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path, directory_path)
zipf.write(file_path, arcname)
return 0
except Exception as e:
logger.exception(e)
return -1
def image_to_base64(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
def replace_image_with_base64(markdown_text, image_dir_path):
pattern = r'\!\[(?:[^\]]*)\]\(([^)]+)\)'
def replace(match):
relative_path = match.group(1)
full_path = os.path.join(image_dir_path, relative_path)
base64_image = image_to_base64(full_path)
return f""
return re.sub(pattern, replace, markdown_text)
def to_pdf(file_path):
"""
์ด๋ฏธ์ง(JPG/PNG ๋ฑ)๋ฅผ PDF๋ก ์ปจ๋ฒํ
.
"""
with pymupdf.open(file_path) as f:
if f.is_pdf:
return file_path
else:
pdf_bytes = f.convert_to_pdf()
unique_filename = f"{uuid.uuid4()}.pdf"
tmp_file_path = os.path.join(os.path.dirname(file_path), unique_filename)
with open(tmp_file_path, 'wb') as tmp_pdf_file:
tmp_pdf_file.write(pdf_bytes)
return tmp_file_path
def to_markdown(file_path, end_pages, is_ocr, layout_mode, formula_enable, table_enable, language, progress=gr.Progress(track_tqdm=False)):
"""
์
๋ก๋๋ PDF/์ด๋ฏธ์ง -> PDF ๋ณํ -> ๋งํฌ๋ค์ด ๋ณํ
(ํ๋ก๊ทธ๋ ์ค ๋ฐ ํ์์ฉ)
"""
progress(0, "PDF๋ก ๋ณํ ์ค...")
file_path = to_pdf(file_path)
time.sleep(0.5)
if end_pages > 20:
end_pages = 20
progress(20, "๋ฌธ์ ํ์ฑ ์ค...")
local_md_dir, file_name = parse_pdf(file_path, './output', end_pages - 1, is_ocr,
layout_mode, formula_enable, table_enable, language)
time.sleep(0.5)
progress(50, "์์ถ(zip) ์์ฑ ์ค...")
archive_zip_path = os.path.join("./output", compute_sha256(local_md_dir) + ".zip")
zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)
if zip_archive_success == 0:
logger.info("์์ถ ์ฑ๊ณต")
else:
logger.error("์์ถ ์คํจ")
time.sleep(0.5)
progress(70, "๋งํฌ๋ค์ด ์ฝ๋ ์ค...")
md_path = os.path.join(local_md_dir, file_name + ".md")
with open(md_path, 'r', encoding='utf-8') as f:
txt_content = f.read()
time.sleep(0.5)
progress(90, "์ด๋ฏธ์ง base64 ๋ณํ ์ค...")
md_content = replace_image_with_base64(txt_content, local_md_dir)
time.sleep(0.5)
progress(100, "๋ณํ ์๋ฃ!")
return md_content
def init_model():
"""
magic-pdf ๋ชจ๋ธ ์ด๊ธฐํ
"""
from magic_pdf.model.doc_analyze_by_custom_model import ModelSingleton
try:
model_manager = ModelSingleton()
txt_model = model_manager.get_model(False, False)
logger.info("txt_model init final")
ocr_model = model_manager.get_model(True, False)
logger.info("ocr_model init final")
return 0
except Exception as e:
logger.exception(e)
return -1
model_init = init_model()
logger.info(f"model_init: {model_init}")
###############################
# ์ธ์ด ๋ชฉ๋ก
###############################
latin_lang = [
'af','az','bs','cs','cy','da','de','es','et','fr','ga','hr','hu','id','is','it','ku',
'la','lt','lv','mi','ms','mt','nl','no','oc','pi','pl','pt','ro','rs_latin','sk','sl',
'sq','sv','sw','tl','tr','uz','vi','french','german'
]
arabic_lang = ['ar','fa','ug','ur']
cyrillic_lang = ['ru','rs_cyrillic','be','bg','uk','mn','abq','ady','kbd','ava','dar','inh','che','lbe','lez','tab']
devanagari_lang = ['hi','mr','ne','bh','mai','ang','bho','mah','sck','new','gom','sa','bgc']
other_lang = ['ch','en','korean','japan','chinese_cht','ta','te','ka']
all_lang = ['', 'auto']
all_lang.extend([*other_lang, *latin_lang, *arabic_lang, *cyrillic_lang, *devanagari_lang])
###############################
# (1) PDF Chat ์ฉ LLM ๊ด๋ จ
###############################
import google.generativeai as genai
from gradio import ChatMessage
from typing import Iterator
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
genai.configure(api_key=GEMINI_API_KEY)
model = genai.GenerativeModel("gemini-2.0-flash-thinking-exp-1219")
def format_chat_history(messages: list) -> list:
"""
Gemini๊ฐ ์ดํดํ ์ ์๋ (role, parts[]) ํ์์ผ๋ก ๋ณํ
"""
formatted_history = []
for message in messages:
if not (message.role == "assistant" and hasattr(message, "metadata")):
formatted_history.append({
"role": "user" if message.role == "user" else "assistant",
"parts": [message.content]
})
return formatted_history
def convert_chat_messages_to_gradio_format(messages):
"""
ChatMessage list -> [ (์ ์ ๋ฐํ, ๋ด์๋ต), (...), ... ]
"""
gradio_chat = []
user_text, assistant_text = None, None
for msg in messages:
if msg.role == "user":
if user_text is not None or assistant_text is not None:
gradio_chat.append((user_text or "", assistant_text or ""))
user_text = msg.content
assistant_text = None
else:
if user_text is None:
user_text = ""
if assistant_text is None:
assistant_text = msg.content
else:
assistant_text += msg.content
if user_text is not None or assistant_text is not None:
gradio_chat.append((user_text or "", assistant_text or ""))
return gradio_chat
def stream_gemini_response(user_message: str, messages: list) -> Iterator[list]:
"""
Gemini ์๋ต ์คํธ๋ฆฌ๋ฐ
(user_message๊ฐ ๊ณต๋ฐฑ์ด๋ฉด ๊ธฐ๋ณธ ๋ฌธ๊ตฌ๋ก ๋์ฒด)
"""
if not user_message.strip():
user_message = "...(No content from user)..."
try:
print(f"\n=== [Gemini] New Request ===\nUser message: '{user_message}'")
chat_history = format_chat_history(messages)
chat = model.start_chat(history=chat_history)
response = chat.send_message(user_message, stream=True)
thought_buffer = ""
response_buffer = ""
thinking_complete = False
# "Thinking" ์ญํ
messages.append(
ChatMessage(
role="assistant",
content="",
metadata={"title": "โ๏ธ Thinking: *The thoughts produced by the model are experimental"}
)
)
yield convert_chat_messages_to_gradio_format(messages)
for chunk in response:
parts = chunk.candidates[0].content.parts
current_chunk = parts[0].text
# ๋ง์ฝ parts ๊ฐ 2๊ฐ๋ผ๋ฉด, parts[0]๋ thinking, parts[1]์ ์ต์ข
๋ต๋ณ
if len(parts) == 2 and not thinking_complete:
thought_buffer += current_chunk
messages[-1] = ChatMessage(
role="assistant",
content=thought_buffer,
metadata={"title": "โ๏ธ Thinking: *The thoughts produced by the model are experimental"}
)
yield convert_chat_messages_to_gradio_format(messages)
response_buffer = parts[1].text
messages.append(ChatMessage(role="assistant", content=response_buffer))
thinking_complete = True
elif thinking_complete:
# ์ด๋ฏธ ์ต์ข
๋ต๋ณ ์ค
response_buffer += current_chunk
messages[-1] = ChatMessage(role="assistant", content=response_buffer)
else:
# ์์ง thinking ์ค
thought_buffer += current_chunk
messages[-1] = ChatMessage(
role="assistant",
content=thought_buffer,
metadata={"title": "โ๏ธ Thinking: *The thoughts produced by the model are experimental"}
)
yield convert_chat_messages_to_gradio_format(messages)
print(f"\n=== [Gemini] Final Response ===\n{response_buffer}")
except Exception as e:
print(f"\n=== [Gemini] Error ===\n{str(e)}")
messages.append(ChatMessage(role="assistant", content=f"I encountered an error: {str(e)}"))
yield convert_chat_messages_to_gradio_format(messages)
def user_message(msg: str, history: list, doc_text: str) -> tuple[str, list]:
"""
doc_text(๋งํฌ๋ค์ด) ์ฌ์ฉํด ์ง๋ฌธ ์๋ ๋ณํ
"""
if doc_text.strip():
user_query = f"๋ค์ ๋ฌธ์๋ฅผ ์ฐธ๊ณ ํ์ฌ ๋ต๋ณ:\n\n{doc_text}\n\n์ง๋ฌธ: {msg}"
else:
user_query = msg
history.append(ChatMessage(role="user", content=user_query))
return "", history
def reset_states(_):
"""
์ ํ์ผ ์
๋ก๋ ์
- chat_history -> ๋น ๋ฆฌ์คํธ
- md_state -> ๋น ๋ฌธ์์ด
- chatbot -> ๋น list of tuples
"""
return [], "", []
###############################
# (2) OCR FLEX ์ ์ฉ (์ค๋ํซ)
###############################
# ๋ณ๋์ LaTeX ์ค์
latex_delimiters = [
{"left": "$$", "right": "$$", "display": True},
{"left": '$', "right": '$', "display": False}
]
def to_markdown_ocr_flex(file_path, end_pages, is_ocr, layout_mode, formula_enable, table_enable, language):
"""
์ค๋ํซ์์ ์ฌ์ฉ:
์
๋ก๋๋ PDF/์ด๋ฏธ์ง๋ฅผ ๋ณํ ํ
(๋งํฌ๋ค์ด ๋ ๋๋ง / ๋งํฌ๋ค์ด ํ
์คํธ / ์์ถํ์ผ / PDF๋ฏธ๋ฆฌ๋ณด๊ธฐ) ๋ฐํ
"""
file_path = to_pdf(file_path)
if end_pages > 20:
end_pages = 20
local_md_dir, file_name = parse_pdf(
file_path, './output', end_pages - 1, is_ocr,
layout_mode, formula_enable, table_enable, language
)
archive_zip_path = os.path.join("./output", compute_sha256(local_md_dir) + ".zip")
zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)
if zip_archive_success == 0:
logger.info("์์ถ ์ฑ๊ณต")
else:
logger.error("์์ถ ์คํจ")
md_path = os.path.join(local_md_dir, file_name + ".md")
with open(md_path, 'r', encoding='utf-8') as f:
txt_content = f.read()
md_content = replace_image_with_base64(txt_content, local_md_dir)
new_pdf_path = os.path.join(local_md_dir, file_name + "_layout.pdf")
return md_content, txt_content, archive_zip_path, new_pdf_path
###############################
# UI ํตํฉ
###############################
if __name__ == "__main__":
with gr.Blocks(title="VisionOCR", css=create_css()) as demo:
# ํญ ์์ญ
with gr.Tabs():
#########################################################
# Tab (1) : PDF -> Markdown ๋ณํ + Chat
#########################################################
with gr.Tab("PDF Chat with LLM"):
gr.HTML("""
<div class="title-area">
<h1>VisionOCR</h1>
<p>PDF/์ด๋ฏธ์ง -> ํ
์คํธ(๋งํฌ๋ค์ด) ๋ณํ ํ, ์ถ LLM๊ณผ ๋ํ</p>
</div>
""")
md_state = gr.State("") # ๋ณํ๋ ๋งํฌ๋ค์ด ํ
์คํธ
chat_history = gr.State([]) # ChatMessage ๋ฆฌ์คํธ
# ์
๋ก๋ & ๋ณํ
with gr.Row():
file = gr.File(label="PDF/์ด๋ฏธ์ง ์
๋ก๋", file_types=[".pdf", ".png", ".jpeg", ".jpg"], interactive=True)
convert_btn = gr.Button("๋ณํํ๊ธฐ")
chatbot = gr.Chatbot(height=600)
# ์ ํ์ผ ์
๋ก๋ ์: ์ด์ ๋ํ/๋งํฌ๋ค์ด/์ฑ๋ด ์ด๊ธฐํ
file.change(
fn=reset_states,
inputs=file,
outputs=[chat_history, md_state, chatbot]
)
# ์จ๊น ์์๋ค
max_pages = gr.Slider(1, 20, 10, visible=False, elem_classes="invisible")
layout_mode = gr.Dropdown(["layoutlmv3","doclayout_yolo"], value="doclayout_yolo", visible=False, elem_classes="invisible")
language = gr.Dropdown(all_lang, value='auto', visible=False, elem_classes="invisible")
formula_enable = gr.Checkbox(value=True, visible=False, elem_classes="invisible")
is_ocr = gr.Checkbox(value=False, visible=False, elem_classes="invisible")
table_enable = gr.Checkbox(value=True, visible=False, elem_classes="invisible")
convert_btn.click(
fn=to_markdown,
inputs=[file, max_pages, is_ocr, layout_mode, formula_enable, table_enable, language],
outputs=md_state,
show_progress=True
)
# Gemini Chat
gr.Markdown("## ์ถ๋ก LLM๊ณผ ๋ํ")
with gr.Row():
chat_input = gr.Textbox(lines=1, placeholder="์ง๋ฌธ์ ์
๋ ฅํ์ธ์...")
clear_btn = gr.Button("๋ํ ์ด๊ธฐํ")
chat_input.submit(
fn=user_message,
inputs=[chat_input, chat_history, md_state],
outputs=[chat_input, chat_history]
).then(
fn=stream_gemini_response,
inputs=[chat_input, chat_history],
outputs=chatbot
)
def clear_all():
return [], "", []
clear_btn.click(
fn=clear_all,
inputs=[],
outputs=[chat_history, md_state, chatbot]
)
#########################################################
# Tab (2) : OCR FLEX (์ค๋ํซ ์ฝ๋)
#########################################################
with gr.Tab("OCR FLEX"):
gr.HTML("""
<div class="title-area">
<h1>OCR FLEX</h1>
<p>PDF์ ์ด๋ฏธ์ง์์ ํ
์คํธ๋ฅผ ๋น ๋ฅด๊ณ ์ ํํ๊ฒ ์ถ์ถํ์ธ์</p>
</div>
""")
with gr.Row():
# ์ผ์ชฝ ํจ๋
with gr.Column(variant='panel', scale=5):
file_ocr = gr.File(
label="PDF ๋๋ ์ด๋ฏธ์ง ํ์ผ์ ์
๋ก๋ํ์ธ์",
file_types=[".pdf", ".png", ".jpeg", ".jpg"],
elem_classes="file-upload"
)
max_pages_ocr = gr.Slider(
1, 20, 10,
step=1,
label='์ต๋ ๋ณํ ํ์ด์ง ์'
)
with gr.Row():
layout_mode_ocr = gr.Dropdown(
["layoutlmv3", "doclayout_yolo"],
label="๋ ์ด์์ ๋ชจ๋ธ",
value="doclayout_yolo"
)
language_ocr = gr.Dropdown(
all_lang,
label="์ธ์ด",
value='auto'
)
with gr.Row():
formula_enable_ocr = gr.Checkbox(
label="์์ ์ธ์ ํ์ฑํ",
value=True
)
is_ocr_ocr = gr.Checkbox(
label="OCR ๊ฐ์ ํ์ฑํ",
value=False
)
table_enable_ocr = gr.Checkbox(
label="ํ ์ธ์ ํ์ฑํ(ํ
์คํธ)",
value=True
)
with gr.Row():
change_bu_ocr = gr.Button("๋ณํ")
clear_bu_ocr = gr.ClearButton("์ด๊ธฐํ")
pdf_show_ocr = PDF(
label='PDF ๋ฏธ๋ฆฌ๋ณด๊ธฐ',
interactive=False,
visible=True,
height=800
)
# ์์ ํด๋๊ฐ ์๋ค๋ฉด ์ฌ์ฉ (์ค์ ์คํํ๊ฒฝ์ ๋ฐ๋ผ ์ฃผ์)
with gr.Accordion("์์ :", open=False):
# __file__ ์ด ์กด์ฌํ์ง ์๋ ํ๊ฒฝ์์๋ ์์๊ฐ ๋์ ์ ํ ์ ์์
example_root = os.path.join(os.path.dirname(__file__), "examples") if "__file__" in globals() else "./examples"
if os.path.exists(example_root):
gr.Examples(
examples=[
os.path.join(example_root, _) for _ in os.listdir(example_root)
if _.endswith("pdf")
],
inputs=file_ocr
)
else:
gr.Markdown("์์ ํด๋๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค.")
# ์ค๋ฅธ์ชฝ ํจ๋
with gr.Column(variant='panel', scale=5):
output_file_ocr = gr.File(
label="๋ณํ ๊ฒฐ๊ณผ",
interactive=False
)
with gr.Tabs():
with gr.Tab("๋งํฌ๋ค์ด ๋ ๋๋ง"):
md_ocr = gr.Markdown(
label="๋งํฌ๋ค์ด ๋ ๋๋ง",
height=1100,
show_copy_button=True,
latex_delimiters=latex_delimiters,
line_breaks=True
)
with gr.Tab("๋งํฌ๋ค์ด ํ
์คํธ"):
md_text_ocr = gr.TextArea(
lines=45,
show_copy_button=True
)
# ์ด๋ฒคํธ ํธ๋ค๋ฌ (OCR FLEX)
file_ocr.change(
fn=to_pdf,
inputs=file_ocr,
outputs=pdf_show_ocr
)
def run_ocr_flex(*args):
return to_markdown_ocr_flex(*args)
change_bu_ocr.click(
fn=run_ocr_flex,
inputs=[
file_ocr,
max_pages_ocr,
is_ocr_ocr,
layout_mode_ocr,
formula_enable_ocr,
table_enable_ocr,
language_ocr
],
outputs=[
md_ocr,
md_text_ocr,
output_file_ocr,
pdf_show_ocr
]
)
clear_bu_ocr.add(
[file_ocr, md_ocr, pdf_show_ocr, md_text_ocr, output_file_ocr, is_ocr_ocr]
)
# ์ ์ฒด ์ฑ ์คํ
demo.launch(server_name="0.0.0.0", server_port=7860, debug=True, ssr_mode=True)
|