|
import io |
|
import os |
|
import tempfile |
|
import time |
|
import uuid |
|
|
|
import cv2 |
|
import gradio as gr |
|
import pymupdf |
|
import spaces |
|
import torch |
|
from gradio_pdf import PDF |
|
from loguru import logger |
|
from PIL import Image |
|
from transformers import AutoProcessor, VisionEncoderDecoderModel |
|
|
|
from utils.utils import prepare_image, parse_layout_string, process_coordinates, ImageDimensions |
|
from utils.markdown_utils import MarkdownConverter |
|
|
|
|
|
def load_css(): |
|
css_path = os.path.join(os.path.dirname(__file__), "static", "styles.css") |
|
if os.path.exists(css_path): |
|
with open(css_path, "r", encoding="utf-8") as f: |
|
return f.read() |
|
return "" |
|
|
|
|
|
model = None |
|
processor = None |
|
tokenizer = None |
|
|
|
|
|
@spaces.GPU |
|
def initialize_model(): |
|
"""初始化 Hugging Face 模型""" |
|
global model, processor, tokenizer |
|
|
|
if model is None: |
|
logger.info("Loading DOLPHIN model...") |
|
model_id = "ByteDance/Dolphin" |
|
|
|
|
|
processor = AutoProcessor.from_pretrained(model_id) |
|
model = VisionEncoderDecoderModel.from_pretrained(model_id) |
|
model.eval() |
|
|
|
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
model.to(device) |
|
model = model.half() |
|
|
|
|
|
tokenizer = processor.tokenizer |
|
|
|
logger.info(f"Model loaded successfully on {device}") |
|
|
|
return "Model ready" |
|
|
|
|
|
logger.info("Initializing model at startup...") |
|
try: |
|
initialize_model() |
|
logger.info("Model initialization completed") |
|
except Exception as e: |
|
logger.error(f"Model initialization failed: {e}") |
|
|
|
|
|
|
|
@spaces.GPU |
|
def model_chat(prompt, image): |
|
"""使用模型进行推理""" |
|
global model, processor, tokenizer |
|
|
|
|
|
if model is None: |
|
initialize_model() |
|
|
|
|
|
is_batch = isinstance(image, list) |
|
|
|
if not is_batch: |
|
images = [image] |
|
prompts = [prompt] |
|
else: |
|
images = image |
|
prompts = prompt if isinstance(prompt, list) else [prompt] * len(images) |
|
|
|
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
batch_inputs = processor(images, return_tensors="pt", padding=True) |
|
batch_pixel_values = batch_inputs.pixel_values.half().to(device) |
|
|
|
|
|
prompts = [f"<s>{p} <Answer/>" for p in prompts] |
|
batch_prompt_inputs = tokenizer( |
|
prompts, |
|
add_special_tokens=False, |
|
return_tensors="pt" |
|
) |
|
|
|
batch_prompt_ids = batch_prompt_inputs.input_ids.to(device) |
|
batch_attention_mask = batch_prompt_inputs.attention_mask.to(device) |
|
|
|
|
|
outputs = model.generate( |
|
pixel_values=batch_pixel_values, |
|
decoder_input_ids=batch_prompt_ids, |
|
decoder_attention_mask=batch_attention_mask, |
|
min_length=1, |
|
max_length=4096, |
|
pad_token_id=tokenizer.pad_token_id, |
|
eos_token_id=tokenizer.eos_token_id, |
|
use_cache=True, |
|
bad_words_ids=[[tokenizer.unk_token_id]], |
|
return_dict_in_generate=True, |
|
do_sample=False, |
|
num_beams=1, |
|
repetition_penalty=1.1 |
|
) |
|
|
|
|
|
sequences = tokenizer.batch_decode(outputs.sequences, skip_special_tokens=False) |
|
|
|
|
|
results = [] |
|
for i, sequence in enumerate(sequences): |
|
cleaned = sequence.replace(prompts[i], "").replace("<pad>", "").replace("</s>", "").strip() |
|
results.append(cleaned) |
|
|
|
|
|
if not is_batch: |
|
return results[0] |
|
return results |
|
|
|
|
|
@spaces.GPU |
|
def process_element_batch(elements, prompt, max_batch_size=16): |
|
"""处理同类型元素的批次""" |
|
results = [] |
|
|
|
|
|
batch_size = min(len(elements), max_batch_size) |
|
|
|
|
|
for i in range(0, len(elements), batch_size): |
|
batch_elements = elements[i:i+batch_size] |
|
crops_list = [elem["crop"] for elem in batch_elements] |
|
|
|
|
|
prompts_list = [prompt] * len(crops_list) |
|
|
|
|
|
batch_results = model_chat(prompts_list, crops_list) |
|
|
|
|
|
for j, result in enumerate(batch_results): |
|
elem = batch_elements[j] |
|
results.append({ |
|
"label": elem["label"], |
|
"bbox": elem["bbox"], |
|
"text": result.strip(), |
|
"reading_order": elem["reading_order"], |
|
}) |
|
|
|
return results |
|
|
|
|
|
def cleanup_temp_file(file_path): |
|
"""安全地删除临时文件""" |
|
try: |
|
if file_path and os.path.exists(file_path): |
|
os.unlink(file_path) |
|
except Exception as e: |
|
logger.warning(f"Failed to cleanup temp file {file_path}: {e}") |
|
|
|
def convert_to_image(file_path, target_size=896, page_num=0): |
|
"""将输入文件转换为图像格式,长边调整到指定尺寸""" |
|
if file_path is None: |
|
return None |
|
|
|
try: |
|
|
|
file_ext = os.path.splitext(file_path)[1].lower() |
|
|
|
if file_ext == '.pdf': |
|
|
|
logger.info(f"Converting PDF page {page_num} to image: {file_path}") |
|
doc = pymupdf.open(file_path) |
|
|
|
|
|
if page_num >= len(doc): |
|
page_num = 0 |
|
|
|
page = doc[page_num] |
|
|
|
|
|
rect = page.rect |
|
scale = target_size / max(rect.width, rect.height) |
|
|
|
|
|
mat = pymupdf.Matrix(scale, scale) |
|
pix = page.get_pixmap(matrix=mat) |
|
|
|
|
|
img_data = pix.tobytes("png") |
|
pil_image = Image.open(io.BytesIO(img_data)) |
|
|
|
|
|
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_file: |
|
pil_image.save(tmp_file.name, "PNG") |
|
doc.close() |
|
return tmp_file.name |
|
|
|
else: |
|
|
|
logger.info(f"Resizing image: {file_path}") |
|
pil_image = Image.open(file_path).convert("RGB") |
|
|
|
|
|
w, h = pil_image.size |
|
if max(w, h) > target_size: |
|
if w > h: |
|
new_w, new_h = target_size, int(h * target_size / w) |
|
else: |
|
new_w, new_h = int(w * target_size / h), target_size |
|
|
|
pil_image = pil_image.resize((new_w, new_h), Image.Resampling.LANCZOS) |
|
|
|
|
|
if max(w, h) <= target_size: |
|
return file_path |
|
|
|
|
|
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_file: |
|
pil_image.save(tmp_file.name, "PNG") |
|
return tmp_file.name |
|
|
|
except Exception as e: |
|
logger.error(f"Error converting file to image: {e}") |
|
return file_path |
|
|
|
def get_pdf_page_count(file_path): |
|
"""获取PDF文件的页数""" |
|
try: |
|
if file_path and file_path.lower().endswith('.pdf'): |
|
doc = pymupdf.open(file_path) |
|
page_count = len(doc) |
|
doc.close() |
|
return page_count |
|
else: |
|
return 1 |
|
except Exception as e: |
|
logger.error(f"Error getting PDF page count: {e}") |
|
return 1 |
|
|
|
def convert_all_pdf_pages_to_images(file_path, target_size=896): |
|
"""将PDF的所有页面转换为图像列表""" |
|
if file_path is None: |
|
return [] |
|
|
|
try: |
|
file_ext = os.path.splitext(file_path)[1].lower() |
|
|
|
if file_ext == '.pdf': |
|
doc = pymupdf.open(file_path) |
|
image_paths = [] |
|
|
|
for page_num in range(len(doc)): |
|
page = doc[page_num] |
|
|
|
|
|
rect = page.rect |
|
scale = target_size / max(rect.width, rect.height) |
|
|
|
|
|
mat = pymupdf.Matrix(scale, scale) |
|
pix = page.get_pixmap(matrix=mat) |
|
|
|
|
|
img_data = pix.tobytes("png") |
|
pil_image = Image.open(io.BytesIO(img_data)) |
|
|
|
|
|
with tempfile.NamedTemporaryFile(suffix=f"_page_{page_num}.png", delete=False) as tmp_file: |
|
pil_image.save(tmp_file.name, "PNG") |
|
image_paths.append(tmp_file.name) |
|
|
|
doc.close() |
|
return image_paths |
|
else: |
|
|
|
converted_path = convert_to_image(file_path, target_size) |
|
return [converted_path] if converted_path else [] |
|
|
|
except Exception as e: |
|
logger.error(f"Error converting PDF pages to images: {e}") |
|
return [] |
|
|
|
def to_pdf(file_path): |
|
"""为了兼容性保留的函数,现在调用convert_to_image""" |
|
return convert_to_image(file_path) |
|
|
|
@spaces.GPU(duration=120) |
|
def process_document(file_path): |
|
"""处理文档的主要函数 - 支持多页PDF处理""" |
|
if file_path is None: |
|
return "", "", [] |
|
|
|
start_time = time.time() |
|
original_file_path = file_path |
|
|
|
|
|
if model is None: |
|
initialize_model() |
|
|
|
try: |
|
|
|
page_count = get_pdf_page_count(file_path) |
|
logger.info(f"Document has {page_count} page(s)") |
|
|
|
|
|
image_paths = convert_all_pdf_pages_to_images(file_path) |
|
if not image_paths: |
|
raise Exception("Failed to convert document to images") |
|
|
|
|
|
temp_files_created = [] |
|
file_ext = os.path.splitext(file_path)[1].lower() |
|
if file_ext == '.pdf': |
|
temp_files_created.extend(image_paths) |
|
elif len(image_paths) == 1 and image_paths[0] != original_file_path: |
|
temp_files_created.append(image_paths[0]) |
|
|
|
all_results = [] |
|
md_contents = [] |
|
|
|
|
|
for page_idx, image_path in enumerate(image_paths): |
|
logger.info(f"Processing page {page_idx + 1}/{len(image_paths)}") |
|
|
|
|
|
recognition_results = process_page(image_path) |
|
|
|
|
|
page_md_content = generate_markdown(recognition_results) |
|
|
|
md_contents.append(page_md_content) |
|
|
|
|
|
page_data = { |
|
"page": page_idx + 1, |
|
"elements": recognition_results, |
|
"total_elements": len(recognition_results) |
|
} |
|
all_results.append(page_data) |
|
|
|
|
|
processing_time = time.time() - start_time |
|
|
|
|
|
if len(md_contents) > 1: |
|
final_md_content = "\n\n---\n\n".join(md_contents) |
|
else: |
|
final_md_content = md_contents[0] if md_contents else "" |
|
|
|
|
|
summary_data = { |
|
"summary": True, |
|
"total_pages": len(image_paths), |
|
"total_elements": sum(len(page["elements"]) for page in all_results), |
|
"processing_time": f"{processing_time:.2f}s", |
|
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S") |
|
} |
|
all_results.append(summary_data) |
|
|
|
logger.info(f"Document processed successfully in {processing_time:.2f}s - {len(image_paths)} page(s)") |
|
return final_md_content, final_md_content, all_results |
|
|
|
except Exception as e: |
|
logger.error(f"Error processing document: {str(e)}") |
|
error_data = [{ |
|
"error": True, |
|
"message": str(e), |
|
"original_file": original_file_path, |
|
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S") |
|
}] |
|
return f"# 处理错误\n\n处理文档时发生错误: {str(e)}", "", error_data |
|
|
|
finally: |
|
|
|
if 'temp_files_created' in locals(): |
|
for temp_file in temp_files_created: |
|
if temp_file and os.path.exists(temp_file): |
|
cleanup_temp_file(temp_file) |
|
|
|
def process_page(image_path): |
|
"""处理单页文档""" |
|
|
|
pil_image = Image.open(image_path).convert("RGB") |
|
layout_output = model_chat("Parse the reading order of this document.", pil_image) |
|
|
|
|
|
padded_image, dims = prepare_image(pil_image) |
|
recognition_results = process_elements(layout_output, padded_image, dims) |
|
|
|
return recognition_results |
|
|
|
def process_elements(layout_results, padded_image, dims, max_batch_size=16): |
|
"""解析所有文档元素""" |
|
layout_results = parse_layout_string(layout_results) |
|
|
|
|
|
text_elements = [] |
|
table_elements = [] |
|
figure_results = [] |
|
previous_box = None |
|
reading_order = 0 |
|
|
|
|
|
for bbox, label in layout_results: |
|
try: |
|
|
|
x1, y1, x2, y2, orig_x1, orig_y1, orig_x2, orig_y2, previous_box = process_coordinates( |
|
bbox, padded_image, dims, previous_box |
|
) |
|
|
|
|
|
cropped = padded_image[y1:y2, x1:x2] |
|
if cropped.size > 0: |
|
if label == "fig": |
|
|
|
try: |
|
|
|
pil_crop = Image.fromarray(cv2.cvtColor(cropped, cv2.COLOR_BGR2RGB)) |
|
|
|
|
|
import io |
|
import base64 |
|
buffered = io.BytesIO() |
|
pil_crop.save(buffered, format="PNG") |
|
img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8') |
|
|
|
figure_results.append( |
|
{ |
|
"label": label, |
|
"bbox": [orig_x1, orig_y1, orig_x2, orig_y2], |
|
"text": img_base64, |
|
"reading_order": reading_order, |
|
} |
|
) |
|
except Exception as e: |
|
logger.error(f"Error encoding figure to base64: {e}") |
|
figure_results.append( |
|
{ |
|
"label": label, |
|
"bbox": [orig_x1, orig_y1, orig_x2, orig_y2], |
|
"text": "", |
|
"reading_order": reading_order, |
|
} |
|
) |
|
else: |
|
|
|
pil_crop = Image.fromarray(cv2.cvtColor(cropped, cv2.COLOR_BGR2RGB)) |
|
element_info = { |
|
"crop": pil_crop, |
|
"label": label, |
|
"bbox": [orig_x1, orig_y1, orig_x2, orig_y2], |
|
"reading_order": reading_order, |
|
} |
|
|
|
|
|
if label == "tab": |
|
table_elements.append(element_info) |
|
else: |
|
text_elements.append(element_info) |
|
|
|
reading_order += 1 |
|
|
|
except Exception as e: |
|
logger.error(f"Error processing bbox with label {label}: {str(e)}") |
|
continue |
|
|
|
|
|
recognition_results = figure_results.copy() |
|
|
|
|
|
if text_elements: |
|
text_results = process_element_batch(text_elements, "Read text in the image.", max_batch_size) |
|
recognition_results.extend(text_results) |
|
|
|
|
|
if table_elements: |
|
table_results = process_element_batch(table_elements, "Parse the table in the image.", max_batch_size) |
|
recognition_results.extend(table_results) |
|
|
|
|
|
recognition_results.sort(key=lambda x: x.get("reading_order", 0)) |
|
|
|
return recognition_results |
|
|
|
def generate_markdown(recognition_results): |
|
"""从识别结果生成Markdown内容""" |
|
|
|
converter = MarkdownConverter() |
|
return converter.convert(recognition_results) |
|
|
|
|
|
latex_delimiters = [ |
|
{"left": "$$", "right": "$$", "display": True}, |
|
{"left": "$", "right": "$", "display": False}, |
|
{"left": "\\[", "right": "\\]", "display": True}, |
|
{"left": "\\(", "right": "\\)", "display": False}, |
|
] |
|
|
|
|
|
custom_css = load_css() |
|
|
|
|
|
with open("header.html", "r", encoding="utf-8") as file: |
|
header = file.read() |
|
|
|
|
|
with gr.Blocks(css=custom_css, title="Dolphin Document Parser") as demo: |
|
gr.HTML(header) |
|
|
|
with gr.Row(): |
|
|
|
with gr.Column(scale=1, elem_classes="sidebar"): |
|
|
|
file = gr.File( |
|
label="Choose PDF or image file", |
|
file_types=[".pdf", ".png", ".jpeg", ".jpg"], |
|
elem_id="file-upload" |
|
) |
|
|
|
with gr.Row(elem_classes="action-buttons"): |
|
submit_btn = gr.Button("提交/Submit", variant="primary") |
|
clear_btn = gr.ClearButton(value="清空/Clear") |
|
|
|
|
|
example_root = os.path.join(os.path.dirname(__file__), "examples") |
|
if os.path.exists(example_root): |
|
gr.HTML("示例文件/Example Files") |
|
example_files = [ |
|
os.path.join(example_root, f) |
|
for f in os.listdir(example_root) |
|
if not f.endswith(".py") |
|
] |
|
|
|
examples = gr.Examples( |
|
examples=example_files, |
|
inputs=file, |
|
examples_per_page=10, |
|
elem_id="example-files" |
|
) |
|
|
|
|
|
with gr.Column(scale=7): |
|
with gr.Row(elem_classes="main-content"): |
|
|
|
with gr.Column(scale=1, elem_classes="preview-panel"): |
|
gr.HTML("文件预览/Preview") |
|
pdf_show = PDF(label="", interactive=False, visible=True, height=600) |
|
|
|
|
|
with gr.Column(scale=1, elem_classes="output-panel"): |
|
with gr.Tabs(): |
|
with gr.Tab("Markdown [Render]"): |
|
md_render = gr.Markdown( |
|
label="", |
|
height=700, |
|
show_copy_button=True, |
|
latex_delimiters=latex_delimiters, |
|
line_breaks=True, |
|
) |
|
with gr.Tab("Markdown [Content]"): |
|
md_content = gr.TextArea(lines=30, show_copy_button=True) |
|
with gr.Tab("Json [Content]"): |
|
json_output = gr.JSON(label="", height=700) |
|
|
|
|
|
def preview_file(file_path): |
|
"""预览上传的文件,对图像先调整尺寸再转换为PDF格式""" |
|
if file_path is None: |
|
return None |
|
|
|
try: |
|
file_ext = os.path.splitext(file_path)[1].lower() |
|
|
|
if file_ext == '.pdf': |
|
|
|
return file_path |
|
else: |
|
|
|
logger.info(f"Resizing image for preview: {file_path}") |
|
|
|
|
|
pil_image = Image.open(file_path).convert("RGB") |
|
w, h = pil_image.size |
|
|
|
|
|
max_preview_size = 896 |
|
if max(w, h) > max_preview_size: |
|
if w > h: |
|
new_w, new_h = max_preview_size, int(h * max_preview_size / w) |
|
else: |
|
new_w, new_h = int(w * max_preview_size / h), max_preview_size |
|
|
|
pil_image = pil_image.resize((new_w, new_h), Image.Resampling.LANCZOS) |
|
logger.info(f"Resized from {w}x{h} to {new_w}x{new_h} for preview") |
|
|
|
|
|
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp_file: |
|
pil_image.save(tmp_file.name, "PDF") |
|
return tmp_file.name |
|
|
|
except Exception as e: |
|
logger.error(f"Error creating preview: {e}") |
|
|
|
try: |
|
with pymupdf.open(file_path) as f: |
|
if f.is_pdf: |
|
return file_path |
|
else: |
|
pdf_bytes = f.convert_to_pdf() |
|
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp_file: |
|
tmp_file.write(pdf_bytes) |
|
return tmp_file.name |
|
except Exception as e2: |
|
logger.error(f"Fallback preview method also failed: {e2}") |
|
return None |
|
|
|
file.change(fn=preview_file, inputs=file, outputs=pdf_show) |
|
|
|
|
|
def process_with_status(file_path): |
|
"""处理文档并更新状态""" |
|
if file_path is None: |
|
return "", "", [] |
|
|
|
|
|
md_render_result, md_content_result, json_result = process_document(file_path) |
|
|
|
return md_render_result, md_content_result, json_result |
|
|
|
submit_btn.click( |
|
fn=process_with_status, |
|
inputs=[file], |
|
outputs=[md_render, md_content, json_output], |
|
) |
|
|
|
|
|
def reset_all(): |
|
return None, None, "", "", [] |
|
|
|
clear_btn.click( |
|
fn=reset_all, |
|
inputs=[], |
|
outputs=[file, pdf_show, md_render, md_content, json_output] |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
demo.launch() |