Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import fitz
|
3 |
+
from PIL import Image
|
4 |
+
import io
|
5 |
+
|
6 |
+
def pdf_page_to_image(pdf_path, page_number):
|
7 |
+
# Open the PDF file
|
8 |
+
doc = fitz.open(pdf_path)
|
9 |
+
page_number -= 1
|
10 |
+
|
11 |
+
# Check if the page number is valid
|
12 |
+
if page_number < 0 or page_number >= len(doc):
|
13 |
+
raise gr.Error("Page number out of range")
|
14 |
+
|
15 |
+
# Select the specified page
|
16 |
+
page = doc.load_page(page_number)
|
17 |
+
|
18 |
+
# Render the page to an image
|
19 |
+
pix = page.get_pixmap()
|
20 |
+
|
21 |
+
# Convert the image to a PIL Image
|
22 |
+
img_data = pix.tobytes("png") # Get the PNG image data
|
23 |
+
img = Image.open(io.BytesIO(img_data))
|
24 |
+
|
25 |
+
# Close the PDF document
|
26 |
+
doc.close()
|
27 |
+
|
28 |
+
return img
|
29 |
+
|
30 |
+
def get_pdf_length(pdf_path):
|
31 |
+
return len(fitz.open(pdf_path))
|
32 |
+
|
33 |
+
def update_number(pdf_path):
|
34 |
+
num_pages = get_pdf_length(pdf_path)
|
35 |
+
return gr.Number(info=f"Enter a number between 1 and {num_pages}", maximum=num_pages)
|
36 |
+
|
37 |
+
with gr.Blocks() as demo:
|
38 |
+
with gr.Row():
|
39 |
+
with gr.Column():
|
40 |
+
f = gr.File(label="Upload files", file_types=[".pdf"])
|
41 |
+
n = gr.Number(1, minimum=1, label="Page number")
|
42 |
+
b = gr.Button("Submit", variant="primary")
|
43 |
+
|
44 |
+
with gr.Column():
|
45 |
+
i = gr.Image()
|
46 |
+
o = gr.Textbox(label="Prediction")
|
47 |
+
e = gr.Textbox(label="Edited prediction")
|
48 |
+
|
49 |
+
f.upload(update_number, f, n)
|
50 |
+
n.submit(pdf_page_to_image, [f, n], i)
|
51 |
+
b.click(pdf_page_to_image, [f, n], i)
|
52 |
+
|
53 |
+
demo.launch()
|