openfree's picture
Update app.py
f82f1ef verified
raw
history blame
25.7 kB
import base64
import json
import os
import time
import zipfile
from pathlib import Path
import re
import uuid
import pymupdf
# ์ด๋ฏธ์ง€ ์ „์ฒ˜๋ฆฌ์— ํ•„์š”ํ•œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ
import cv2
import numpy as np
###############################
# ํ™˜๊ฒฝ ์„ค์ •
###############################
os.system('pip uninstall -y magic-pdf')
os.system('pip install git+https://github.com/opendatalab/MinerU.git@dev')
# โ˜… OpenCV ์„ค์น˜ (headless ๋ฒ„์ „)
os.system('pip install opencv-python-headless')
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"![{relative_path}](data:image/jpeg;base64,{base64_image})"
return re.sub(pattern, replace, markdown_text)
###############################
# ์ด๋ฏธ์ง€ ์ „์ฒ˜๋ฆฌ ํ•จ์ˆ˜ (Grayscale/Binarization + Deskew)
###############################
def preprocess_image(image_path):
"""
1) Grayscale + Binarization(OTSU)
2) Deskew(๊ธฐ์šธ์ž„ ๋ณด์ •)
์ „์ฒ˜๋ฆฌ๋œ ์ด๋ฏธ์ง€๋ฅผ ์ž„์‹œ ๊ฒฝ๋กœ์— ์ €์žฅ ํ›„ ํ•ด๋‹น ๊ฒฝ๋กœ๋ฅผ ๋ฐ˜ํ™˜
"""
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if img is None:
# ์ด๋ฏธ์ง€ ํŒŒ์ผ์ด ์•„๋‹Œ ๊ฒฝ์šฐ ํ˜น์€ ๋กœ๋”ฉ ์‹คํŒจ ์‹œ ์›๋ณธ ๊ฒฝ๋กœ ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜
return image_path
# (a) ์ด์ง„ํ™”(binarization)
_, img_bin = cv2.threshold(img, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY)
# (b) ๊ธฐ์šธ์ž„ ๋ณด์ •(deskew)
coords = np.column_stack(np.where(img_bin > 0))
angle = cv2.minAreaRect(coords)[-1]
# OpenCV๋Š” ํšŒ์ „ ๊ฐ๋„๋ฅผ [-90, 0)๋กœ ๋ฐ˜ํ™˜ํ•  ๋•Œ๊ฐ€ ๋งŽ์œผ๋ฏ€๋กœ ๋ณด์ •
if angle < -45:
angle = -(90 + angle)
else:
angle = -angle
(h, w) = img_bin.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
img_rotated = cv2.warpAffine(
img_bin,
M,
(w, h),
flags=cv2.INTER_CUBIC,
borderMode=cv2.BORDER_CONSTANT,
borderValue=255
)
# ์ž„์‹œ ํŒŒ์ผ๋กœ ์ €์žฅ
preprocessed_path = image_path + "_preprocessed.png"
cv2.imwrite(preprocessed_path, img_rotated)
return preprocessed_path
def to_pdf(file_path):
"""
์ด๋ฏธ์ง€(JPG/PNG ๋“ฑ)๋ฅผ PDF๋กœ ์ปจ๋ฒ„ํŒ…ํ•˜๋˜,
์ด๋ฏธ์ง€์ผ ๊ฒฝ์šฐ ์ „์ฒ˜๋ฆฌ(Grayscale/Binarization + Deskew)๋ฅผ ๋จผ์ € ์ ์šฉ
"""
with pymupdf.open(file_path) as f:
if f.is_pdf:
return file_path
else:
# ์ด๋ฏธ์ง€ ํŒŒ์ผ์ธ ๊ฒฝ์šฐ, ์ „์ฒ˜๋ฆฌ ์ˆ˜ํ–‰ ํ›„ PDF ์ƒ์„ฑ
f.close()
preprocessed_path = preprocess_image(file_path)
# ์ „์ฒ˜๋ฆฌ๋œ ์ด๋ฏธ์ง€๋ฅผ ๋‹ค์‹œ PyMuPDF๋กœ ์—ด์–ด์„œ PDF ๋ณ€ํ™˜
with pymupdf.open(preprocessed_path) as img_doc:
pdf_bytes = img_doc.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 ๋ณ€ํ™˜ -> ๋งˆํฌ๋‹ค์šด ๋ณ€ํ™˜
(๋งˆํฌ๋‹ค์šด ๋ Œ๋”๋ง / ๋งˆํฌ๋‹ค์šด ํ…์ŠคํŠธ / ์••์ถ•ํŒŒ์ผ / 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"]
)
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("๋ณ€ํ™˜")
# โ˜… ClearButton ์ˆ˜์ • โ˜…
# ์ฒซ ๋ฒˆ์งธ ์ธ์ž -> clearํ•  ๋Œ€์ƒ(์ปดํฌ๋„ŒํŠธ),
# ๋ฒ„ํŠผ์— ํ‘œ์‹œ๋  ํ…์ŠคํŠธ๋Š” value="์ดˆ๊ธฐํ™”"
clear_bu_ocr = gr.ClearButton(
components=[file_ocr, max_pages_ocr, layout_mode_ocr, language_ocr,
formula_enable_ocr, is_ocr_ocr, table_enable_ocr],
value="์ดˆ๊ธฐํ™”"
)
pdf_show_ocr = PDF(
label='PDF ๋ฏธ๋ฆฌ๋ณด๊ธฐ',
interactive=False,
visible=True,
height=800
)
# ์˜ˆ์ œ ํด๋”๊ฐ€ ์žˆ๋‹ค๋ฉด ์‚ฌ์šฉ (์‹ค์ œ ์‹คํ–‰ํ™˜๊ฒฝ์— ๋”ฐ๋ผ ์ฃผ์˜)
with gr.Accordion("์˜ˆ์ œ:", open=False):
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
]
)
# ์ „์ฒด ์•ฑ ์‹คํ–‰
demo.launch(server_name="0.0.0.0", server_port=7860, debug=True, ssr_mode=True)