Spaces:
Running
Running
Upload 2 files
Browse files- openai_app.py +122 -0
- requirements.txt +2 -0
openai_app.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from pdf2image import convert_from_path
|
| 3 |
+
import base64
|
| 4 |
+
from openai import OpenAI
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import concurrent.futures
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import zipfile
|
| 10 |
+
import tempfile
|
| 11 |
+
import shutil
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
if not os.environ.get("OPENAI_API_KEY"):
|
| 15 |
+
raise ValueError("OPENAI_API_KEY is not set")
|
| 16 |
+
|
| 17 |
+
client = OpenAI()
|
| 18 |
+
|
| 19 |
+
def encode_pil_image(pil_image):
|
| 20 |
+
buffered = BytesIO()
|
| 21 |
+
pil_image.save(buffered, format="JPEG")
|
| 22 |
+
return base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 23 |
+
|
| 24 |
+
def extract_markdown_from_image(image, idx):
|
| 25 |
+
base64_image = encode_pil_image(image)
|
| 26 |
+
try:
|
| 27 |
+
completion = client.chat.completions.create(
|
| 28 |
+
model="o4-mini",
|
| 29 |
+
messages=[
|
| 30 |
+
{
|
| 31 |
+
"role": "user",
|
| 32 |
+
"content": [
|
| 33 |
+
{ "type": "text", "text": "Extract the text from this page and return it as markdown, with the best possible quality and accuracy." },
|
| 34 |
+
{
|
| 35 |
+
"type": "image_url",
|
| 36 |
+
"image_url": {
|
| 37 |
+
"url": f"data:image/jpeg;base64,{base64_image}",
|
| 38 |
+
"detail": "high"
|
| 39 |
+
},
|
| 40 |
+
},
|
| 41 |
+
],
|
| 42 |
+
}
|
| 43 |
+
],
|
| 44 |
+
)
|
| 45 |
+
return idx, completion.choices[0].message.content
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(e)
|
| 48 |
+
return idx, f"Error processing page {idx}: {e}"
|
| 49 |
+
|
| 50 |
+
def pdf_to_json_and_md_zip_with_progress(pdf_file, progress=gr.Progress(track_tqdm=True)):
|
| 51 |
+
# Save uploaded file to a temp path if needed
|
| 52 |
+
if hasattr(pdf_file, "name"):
|
| 53 |
+
pdf_path = pdf_file.name
|
| 54 |
+
else:
|
| 55 |
+
# Gradio may pass a str path or a file object
|
| 56 |
+
pdf_path = pdf_file
|
| 57 |
+
|
| 58 |
+
images = convert_from_path(pdf_path)
|
| 59 |
+
num_pages = len(images)
|
| 60 |
+
results = [None] * num_pages
|
| 61 |
+
|
| 62 |
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 63 |
+
futures = []
|
| 64 |
+
for i in range(num_pages):
|
| 65 |
+
futures.append(executor.submit(extract_markdown_from_image, images[i], i))
|
| 66 |
+
for idx, future in enumerate(concurrent.futures.as_completed(futures)):
|
| 67 |
+
idx_result, content = future.result()
|
| 68 |
+
results[idx_result] = content.replace("```markdown", "").replace("```", "")
|
| 69 |
+
progress((idx + 1) / num_pages, desc=f"Processing page {idx_result + 1} of {num_pages}")
|
| 70 |
+
|
| 71 |
+
output_json = [
|
| 72 |
+
{"page": idx + 1, "markdown": content}
|
| 73 |
+
for idx, content in enumerate(results)
|
| 74 |
+
]
|
| 75 |
+
|
| 76 |
+
# Create a temporary directory to store md files and json
|
| 77 |
+
temp_dir = tempfile.mkdtemp()
|
| 78 |
+
md_folder = os.path.join(temp_dir, "pages")
|
| 79 |
+
os.makedirs(md_folder, exist_ok=True)
|
| 80 |
+
|
| 81 |
+
# Write each page as a separate .md file
|
| 82 |
+
for idx, content in enumerate(results):
|
| 83 |
+
md_path = os.path.join(md_folder, f"page_{idx+1}.md")
|
| 84 |
+
with open(md_path, "w", encoding="utf-8") as f:
|
| 85 |
+
f.write(content.strip())
|
| 86 |
+
|
| 87 |
+
# Write the JSON file
|
| 88 |
+
output_json_path = os.path.join(temp_dir, "ocr_output.json")
|
| 89 |
+
with open(output_json_path, "w", encoding="utf-8") as f:
|
| 90 |
+
json.dump(output_json, f, ensure_ascii=False, indent=2)
|
| 91 |
+
|
| 92 |
+
# Create a zip file containing the folder with md files and the json
|
| 93 |
+
zip_path = os.path.join(temp_dir, "ocr_output.zip")
|
| 94 |
+
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
|
| 95 |
+
# Add the JSON file
|
| 96 |
+
zipf.write(output_json_path, arcname="ocr_output.json")
|
| 97 |
+
# Add the md files folder and its contents
|
| 98 |
+
for root, dirs, files in os.walk(md_folder):
|
| 99 |
+
for file in files:
|
| 100 |
+
file_path = os.path.join(root, file)
|
| 101 |
+
arcname = os.path.relpath(file_path, temp_dir)
|
| 102 |
+
zipf.write(file_path, arcname=arcname)
|
| 103 |
+
|
| 104 |
+
return zip_path
|
| 105 |
+
|
| 106 |
+
with gr.Blocks() as demo:
|
| 107 |
+
gr.Markdown("# PDF to Markdown & JSON OCR (OpenAI Vision)\nUpload a PDF file. Each page will be processed and the extracted markdown will be saved as separate .md files in a folder, and all results will be zipped together with a JSON file.")
|
| 108 |
+
pdf_input = gr.File(label="Upload PDF", file_types=[".pdf"])
|
| 109 |
+
zip_output = gr.File(label="Download ZIP (md files + JSON)", interactive=False)
|
| 110 |
+
|
| 111 |
+
def process_and_return_zip(pdf_file, progress=gr.Progress(track_tqdm=True)):
|
| 112 |
+
zip_path = pdf_to_json_and_md_zip_with_progress(pdf_file, progress=progress)
|
| 113 |
+
return zip_path
|
| 114 |
+
|
| 115 |
+
process_btn = gr.Button("Convert PDF to ZIP")
|
| 116 |
+
process_btn.click(
|
| 117 |
+
process_and_return_zip,
|
| 118 |
+
inputs=[pdf_input],
|
| 119 |
+
outputs=[zip_output]
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pdf2image
|
| 2 |
+
openai
|