File size: 6,643 Bytes
2b9f3af
 
 
 
 
9766910
 
fa6b4a3
2b9f3af
fa6b4a3
9766910
fa6b4a3
9766910
2b9f3af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9766910
2b9f3af
 
 
 
 
9766910
 
 
 
 
 
 
 
 
2b9f3af
9766910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b9f3af
 
9766910
2b9f3af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9766910
 
b043c4b
9766910
 
601927a
c65aaa3
601927a
9766910
 
b043c4b
 
 
 
 
 
 
9766910
 
 
 
 
 
2b9f3af
9766910
2b9f3af
 
 
 
 
 
 
9766910
2b9f3af
 
 
 
9766910
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
import base64
from io import BytesIO
import json
import os
from openai import OpenAI
from dotenv import load_dotenv
from typhoon_ocr import prepare_ocr_messages
import gradio as gr
from PIL import Image

load_dotenv()

openai = OpenAI(base_url=os.getenv("TYPHOON_BASE_URL"), api_key=os.getenv("TYPHOON_API_KEY"))

theme = gr.themes.Soft(
    primary_hue=gr.themes.Color(
        c50="#f7f7fd",
        c100="#dfdef8",
        c200="#c4c1f2",
        c300="#a29eea",
        c400="#8f8ae6",
        c500="#756fe0",
        c600="#635cc1",
        c700="#4f4a9b",
        c800="#433f83",
        c900="#302d5e",
        c950="#302d5e",
    ),
    secondary_hue="rose",
    neutral_hue="stone",
)

def process_pdf(pdf_or_image_file, task_type, page_number):
    if pdf_or_image_file is None:
        return None, "No file uploaded"
    
    orig_filename = pdf_or_image_file.name
    
    try:
        # Use the new simplified function to prepare OCR messages with page number
        messages = prepare_ocr_messages(
            pdf_or_image_path=orig_filename,
            task_type=task_type,
            target_image_dim=1800,
            target_text_length=8000,
            page_num=page_number if page_number else 1
        )
        
        # Extract the image from the message content for display
        image_url = messages[0]["content"][1]["image_url"]["url"]
        image_base64 = image_url.replace("data:image/png;base64,", "")
        image_pil = Image.open(BytesIO(base64.b64decode(image_base64)))
        
        # Send messages to OpenAI compatible API
        response = openai.chat.completions.create(
            model=os.getenv("TYPHOON_OCR_MODEL"),
            messages=messages,
            max_tokens=16384,
            extra_body={
                "repetition_penalty": 1.2,
                "temperature": 0.1,
                "top_p": 0.6,
            },
        )
        text_output = response.choices[0].message.content
        
        # Try to parse the output assuming it is a Python dictionary containing 'natural_text'
        try:
            json_data = json.loads(text_output)
            markdown_out = json_data.get('natural_text', "").replace("<figure>", "").replace("</figure>", "")
        except Exception as e:
            markdown_out = f"⚠️ Could not extract `natural_text` from output.\nError: {str(e)}"
        
        return image_pil, markdown_out
    
    except Exception as e:
        return None, f"Error processing file: {str(e)}"


# Build the Gradio UI.
with gr.Blocks(theme=theme) as demo:
    title = gr.HTML("""
    <h1>Typhoon OCR</h1>
    <ul>
        <li>πŸ€— <b>Model weights</b>: <a href="https://huggingface.co/scb10x/typhoon-ocr-7b" target="_blank">https://huggingface.co/scb10x/typhoon-ocr-7b</a></li>
    </ul>
    <br />
    <details>
        <summary><strong>Disclaimer</strong></summary>
        The responses generated by this Artificial Intelligence (AI) system are autonomously constructed and do not necessarily reflect the views or positions of the developing organizations, their affiliates, or any of their employees. These AI-generated responses do not represent those of the organizations. The organizations do not endorse, support, sanction, encourage, verify, or agree with the comments, opinions, or statements generated by this AI. The information produced by this AI is not intended to malign any religion, ethnic group, club, organization, company, individual, anyone, or anything. It is not the intent of the organizations to malign any group or individual. The AI operates based on its programming and training data and its responses should not be interpreted as the explicit intent or opinion of the organizations.
    </details>
    <br />
    <details>
        <summary><strong>Terms of use</strong></summary>
        By using this service, users are required to agree to the following terms: The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. Vision language models are prone to hallucinations to a greater extent compared to text-only LLMs.
    </details>
    <br />
    <details>
        <summary><strong>License</strong></summary>
        This project utilizes certain datasets and checkpoints that are subject to their respective original licenses. Users must comply with all terms and conditions of these original licenses. The content of this project itself is licensed under the Apache license 2.0.
    </details>
""")
    with gr.Row():
        with gr.Column(scale=1):
            # Update file_types to accept PDF as well as common image formats.
            pdf_input = gr.File(label="πŸ“„ Upload Image file or PDF file", file_types=[".pdf", ".png", ".jpg", ".jpeg"])
            
            with gr.Group(elem_classes=["task-background"]):
                task_dropdown = gr.Radio(["default", "structure"], label="🎯 Select Task", value="default")
                gr.HTML("""
                <p><b>default</b>: This mode works for most cases and is recommended for files without a clear template such as infographics.</p>
                <p><b>structure</b>: This mode offers improved performance for complex layout documents such as those containing images, tables and forms.</p>
                <p>We recommend trying both and see which one works better for your use case.</p>
                """, elem_classes=["task-dropdown-info"])
                demo.css = """
                .task-background {
                    background: var(--block-background-fill) !important;
                    
                }
                .task-background > * {
                    background: var(--block-background-fill) !important;
                }
                .task-dropdown-info {
                    padding: 0 16px;
                    font-size: 12px;
                }
                """
            page_number = gr.Number(label="πŸ“„ Page Number (for PDFs only)", value=1, minimum=1, step=1)
            run_button = gr.Button("πŸš€ Run")
            image_output = gr.Image(label="πŸ“Έ Preview Image", type="pil")
        with gr.Column(scale=2):
            markdown_output = gr.Markdown(label='Markdown Result', show_label=True)

    
    # Connect the UI inputs to the processing function.
    run_button.click(
        fn=process_pdf,
        inputs=[pdf_input, task_dropdown, page_number],
        outputs=[image_output, markdown_output]
    )

# Launch the Gradio demo (temporary public share for 72 hours)
demo.launch(share=False)