File size: 6,707 Bytes
59ff001
 
 
 
3658a99
59ff001
 
6a0411c
59ff001
 
 
 
6a0411c
4366a57
 
5827499
c7e3ff4
70fe98e
8be5494
59ff001
 
 
 
 
 
 
 
e9af7f8
bd2cd53
 
 
 
59ff001
 
 
5827499
bd2cd53
 
 
 
 
 
c7e3ff4
e9af7f8
6a0411c
59ff001
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a0411c
59ff001
 
 
c7e3ff4
59ff001
 
 
 
 
 
 
 
 
 
 
c7e3ff4
 
 
 
 
 
59ff001
 
 
 
 
 
 
 
 
70fe98e
bd2cd53
e9af7f8
 
 
 
 
 
 
 
 
 
bd2cd53
 
 
 
 
 
 
 
 
 
 
5827499
59ff001
e9af7f8
6a0411c
bd2cd53
70fe98e
 
 
 
 
e9af7f8
 
70fe98e
e9af7f8
 
70fe98e
 
e9af7f8
 
70fe98e
e9af7f8
 
70fe98e
e9af7f8
70fe98e
 
 
e9af7f8
 
822eba7
6a0411c
59ff001
6a0411c
e9af7f8
59ff001
 
e9af7f8
59ff001
 
e9af7f8
 
 
59ff001
6a0411c
d45f3e7
 
6a0411c
 
 
 
 
 
 
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
import gradio as gr
import torch
import base64
import fitz  # PyMuPDF
import tempfile
from io import BytesIO
from PIL import Image
from pathlib import Path
from transformers import AutoProcessor, Qwen2VLForConditionalGeneration

from olmocr.data.renderpdf import render_pdf_to_base64png
from olmocr.prompts.anchor import get_anchor_text

from mathml_utils import convert_inline_and_block_latex_to_mathml

from ebooklib import epub
import json
import html

# Load model and processor
model = Qwen2VLForConditionalGeneration.from_pretrained(
    "allenai/olmOCR-7B-0225-preview", torch_dtype=torch.bfloat16
).eval()
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)

def process_pdf_to_html(pdf_file, title, author):
    import re
    import markdown2
    from latex2mathml.converter import convert as latex_to_mathml

    pdf_path = pdf_file.name
    doc = fitz.open(pdf_path)
    num_pages = len(doc)

    # Extract TOC as a dict: {page_number: [(level, title), ...]}
    toc_entries = doc.get_toc()
    toc_by_page = {}
    for level, title, page in toc_entries:
        toc_by_page.setdefault(page, []).append((level, title))

    all_text = ""
    cover_img_html = ""

    for i in range(num_pages):
        page_num = i + 1
        print(f"Processing page {page_num}...")

        try:
            image_base64 = render_pdf_to_base64png(pdf_path, page_num, target_longest_image_dim=1024)
            anchor_text = get_anchor_text(pdf_path, page_num, pdf_engine="pdfreport", target_length=4000)

            prompt = (
                "Below is the image of one page of a document, as well as some raw textual content that was previously "
                "extracted for it. Just return the plain text representation of this document as if you were reading it naturally.\n"
                "Do not hallucinate.\n"
                "RAW_TEXT_START\n"
                f"{anchor_text}\n"
                "RAW_TEXT_END"
            )

            messages = [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": prompt},
                        {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_base64}"}},
                    ],
                }
            ]
            text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
            image = Image.open(BytesIO(base64.b64decode(image_base64)))

            inputs = processor(
                text=[text],
                images=[image],
                padding=True,
                return_tensors="pt",
            )
            inputs = {k: v.to(device) for k, v in inputs.items()}

            output = model.generate(
                **inputs,
                temperature=0.8,
                max_new_tokens=5096,
                num_return_sequences=1,
                do_sample=True,
            )

            prompt_length = inputs["input_ids"].shape[1]
            new_tokens = output[:, prompt_length:].detach().cpu()

            decoded = "[No output generated]"
            if new_tokens is not None and new_tokens.shape[1] > 0:
                try:
                    decoded_list = processor.tokenizer.batch_decode(new_tokens, skip_special_tokens=True)
                    raw_output = decoded_list[0].strip() if decoded_list else "[No output generated]"
                    try:
                        parsed = json.loads(raw_output)
                        decoded = parsed.get("natural_text", raw_output)
                    except json.JSONDecodeError:
                        decoded = raw_output
                except Exception as decode_error:
                    decoded = f"[Decoding error on page {page_num}: {str(decode_error)}]"
            else:
                decoded = "[Model returned no new tokens]"

        except Exception as processing_error:
            decoded = f"[Processing error on page {page_num}: {str(processing_error)}]"

        print(f"Decoded content for page {page_num}: {decoded}")

        # Convert inline and block LaTeX math to MathML
        def convert_latex(text):
            def replacer(match):
                try:
                    return f"<math>{latex_to_mathml(match.group(1))}</math>"
                except:
                    return html.escape(match.group(0))
            text = re.sub(r'\\\((.*?)\\\)', replacer, text)
            text = re.sub(r'\\\[(.*?)\\\]', replacer, text)
            return text

        math_converted = convert_latex(decoded)
        markdown_converted = markdown2.markdown(math_converted)
        html_page = markdown_converted.replace("\n", "<br>")

        # Add TOC-derived headers if present on this page
        if page_num in toc_by_page:
            for level, header in toc_by_page[page_num]:
                tag = f"h{min(level, 6)}"  # Limit to h6
                html_page = f"<{tag}>{html.escape(header)}</{tag}>\n" + html_page

        all_text += f"<div>{html_page}</div>\n"

        if page_num == 1:
            cover_img_html = f'<img src="data:image/png;base64,{image_base64}" alt="cover" style="max-width:100%; height:auto;"><hr>'

    # MathJax fallback in case MathML fails (some browsers prefer it)
    mathjax_script = """
    <script type="text/javascript" id="MathJax-script" async
      src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
    </script>
    """

    full_html = f"""<!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>{html.escape(title)}</title>
        {mathjax_script}
    </head>
    <body>
        <h1>{html.escape(title)}</h1>
        <h3>{html.escape(author)}</h3>
        {cover_img_html}
        {all_text}
    </body>
    </html>
    """

    with tempfile.NamedTemporaryFile(delete=False, suffix=".html", dir="/tmp", mode="w", encoding="utf-8") as tmp:
        tmp.write(full_html)
        return tmp.name

# Gradio Interface
iface = gr.Interface(
    fn=process_pdf_to_html,  # NEW FUNCTION
    inputs=[
        gr.File(label="Upload PDF", file_types=[".pdf"]),
        gr.Textbox(label="HTML Title"),
        gr.Textbox(label="Author(s)")
    ],
    outputs=gr.File(label="Download HTML"),
    title="PDF to HTML Converter (for Calibre/Kindle)",
    description="Uploads a PDF, extracts text via vision+prompt, embeds it in a styled HTML file with math support. Ready for Calibre.",
    allow_flagging="never"
)

if __name__ == "__main__":
    iface.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True,
        debug=True,
        allowed_paths=["/tmp"]
    )