Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -63,7 +63,7 @@ def extract_markdown_from_image(image, idx):
|
|
| 63 |
print(e)
|
| 64 |
return idx, f"Error processing page {idx}: {e}"
|
| 65 |
|
| 66 |
-
def
|
| 67 |
# Save uploaded file to a temp path if needed
|
| 68 |
if hasattr(pdf_file, "name"):
|
| 69 |
pdf_path = pdf_file.name
|
|
@@ -75,19 +75,24 @@ def pdf_to_json_and_md_zip_with_progress(pdf_file, model_choice="openai", progre
|
|
| 75 |
# OpenAI processing
|
| 76 |
images = convert_from_path(pdf_path)
|
| 77 |
num_pages = len(images)
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 81 |
futures = []
|
| 82 |
-
for i in
|
| 83 |
-
futures.append(executor.submit(extract_markdown_from_image,
|
| 84 |
for idx, future in enumerate(concurrent.futures.as_completed(futures)):
|
| 85 |
idx_result, content = future.result()
|
| 86 |
results[idx_result] = content.replace("```markdown", "").replace("```", "")
|
| 87 |
-
progress((idx + 1) /
|
| 88 |
|
| 89 |
output_json = [
|
| 90 |
-
{"page": idx + 1, "markdown": content}
|
| 91 |
for idx, content in enumerate(results)
|
| 92 |
]
|
| 93 |
else:
|
|
@@ -106,63 +111,126 @@ def pdf_to_json_and_md_zip_with_progress(pdf_file, model_choice="openai", progre
|
|
| 106 |
"document_url": f"data:application/pdf;base64,{base64_pdf}"
|
| 107 |
}
|
| 108 |
)
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
progress(0.5, desc="Processing Mistral API response")
|
| 111 |
results = []
|
| 112 |
-
for page in
|
| 113 |
results.append(page.markdown)
|
| 114 |
|
| 115 |
output_json = [
|
| 116 |
-
{"page": idx + 1, "markdown": content}
|
| 117 |
for idx, content in enumerate(results)
|
| 118 |
]
|
| 119 |
progress(0.8, desc="Preparing output files")
|
| 120 |
|
| 121 |
-
#
|
| 122 |
temp_dir = tempfile.mkdtemp()
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
with open(md_path, "w", encoding="utf-8") as f:
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
for file in files:
|
| 145 |
-
file_path = os.path.join(root, file)
|
| 146 |
-
arcname = os.path.relpath(file_path, temp_dir)
|
| 147 |
-
zipf.write(file_path, arcname=arcname)
|
| 148 |
-
|
| 149 |
-
return zip_path
|
| 150 |
|
| 151 |
with gr.Blocks() as demo:
|
| 152 |
-
gr.Markdown(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
pdf_input = gr.File(label="Upload PDF", file_types=[".pdf"])
|
| 154 |
model_choice = gr.Radio(["openai", "mistral"], label="OCR Model", value="openai")
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
outputs=[zip_output]
|
| 166 |
)
|
| 167 |
|
| 168 |
demo.launch()
|
|
|
|
| 63 |
print(e)
|
| 64 |
return idx, f"Error processing page {idx}: {e}"
|
| 65 |
|
| 66 |
+
def pdf_to_outputs_with_progress(pdf_file, model_choice="openai", output_type="zip", page_from=1, page_to=None, progress=gr.Progress(track_tqdm=True)):
|
| 67 |
# Save uploaded file to a temp path if needed
|
| 68 |
if hasattr(pdf_file, "name"):
|
| 69 |
pdf_path = pdf_file.name
|
|
|
|
| 75 |
# OpenAI processing
|
| 76 |
images = convert_from_path(pdf_path)
|
| 77 |
num_pages = len(images)
|
| 78 |
+
# Clamp page_from and page_to
|
| 79 |
+
page_from = max(1, min(page_from, num_pages))
|
| 80 |
+
page_to = num_pages if page_to is None else max(page_from, min(page_to, num_pages))
|
| 81 |
+
selected_images = images[page_from-1:page_to]
|
| 82 |
+
selected_indices = list(range(page_from-1, page_to))
|
| 83 |
+
results = [None] * (page_to - page_from + 1)
|
| 84 |
|
| 85 |
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 86 |
futures = []
|
| 87 |
+
for i, img in enumerate(selected_images):
|
| 88 |
+
futures.append(executor.submit(extract_markdown_from_image, img, i))
|
| 89 |
for idx, future in enumerate(concurrent.futures.as_completed(futures)):
|
| 90 |
idx_result, content = future.result()
|
| 91 |
results[idx_result] = content.replace("```markdown", "").replace("```", "")
|
| 92 |
+
progress((idx + 1) / len(selected_images), desc=f"Processing page {selected_indices[idx_result] + 1} of {num_pages}")
|
| 93 |
|
| 94 |
output_json = [
|
| 95 |
+
{"page": selected_indices[idx] + 1, "markdown": content}
|
| 96 |
for idx, content in enumerate(results)
|
| 97 |
]
|
| 98 |
else:
|
|
|
|
| 111 |
"document_url": f"data:application/pdf;base64,{base64_pdf}"
|
| 112 |
}
|
| 113 |
)
|
| 114 |
+
num_pages = len(ocr_response.pages)
|
| 115 |
+
page_from = max(1, min(page_from, num_pages))
|
| 116 |
+
page_to = num_pages if page_to is None else max(page_from, min(page_to, num_pages))
|
| 117 |
+
selected_pages = ocr_response.pages[page_from-1:page_to]
|
| 118 |
+
selected_indices = list(range(page_from-1, page_to))
|
| 119 |
+
|
| 120 |
progress(0.5, desc="Processing Mistral API response")
|
| 121 |
results = []
|
| 122 |
+
for page in selected_pages:
|
| 123 |
results.append(page.markdown)
|
| 124 |
|
| 125 |
output_json = [
|
| 126 |
+
{"page": selected_indices[idx] + 1, "markdown": content}
|
| 127 |
for idx, content in enumerate(results)
|
| 128 |
]
|
| 129 |
progress(0.8, desc="Preparing output files")
|
| 130 |
|
| 131 |
+
# Now handle output_type: "zip", "markdown", "json"
|
| 132 |
temp_dir = tempfile.mkdtemp()
|
| 133 |
+
output_paths = {}
|
| 134 |
+
|
| 135 |
+
if output_type == "zip":
|
| 136 |
+
md_folder = os.path.join(temp_dir, "pages")
|
| 137 |
+
os.makedirs(md_folder, exist_ok=True)
|
| 138 |
+
|
| 139 |
+
# Write each page as a separate .md file
|
| 140 |
+
for idx, content in enumerate(results):
|
| 141 |
+
md_path = os.path.join(md_folder, f"page_{selected_indices[idx]+1}.md")
|
| 142 |
+
with open(md_path, "w", encoding="utf-8") as f:
|
| 143 |
+
f.write(content.strip())
|
| 144 |
+
|
| 145 |
+
# Write the JSON file
|
| 146 |
+
output_json_path = os.path.join(temp_dir, "ocr_output.json")
|
| 147 |
+
with open(output_json_path, "w", encoding="utf-8") as f:
|
| 148 |
+
json.dump(output_json, f, ensure_ascii=False, indent=2)
|
| 149 |
+
|
| 150 |
+
# Create a zip file containing the folder with md files and the json
|
| 151 |
+
zip_path = os.path.join(temp_dir, "ocr_output.zip")
|
| 152 |
+
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
|
| 153 |
+
# Add the JSON file
|
| 154 |
+
zipf.write(output_json_path, arcname="ocr_output.json")
|
| 155 |
+
# Add the md files folder and its contents
|
| 156 |
+
for root, dirs, files in os.walk(md_folder):
|
| 157 |
+
for file in files:
|
| 158 |
+
file_path = os.path.join(root, file)
|
| 159 |
+
arcname = os.path.relpath(file_path, temp_dir)
|
| 160 |
+
zipf.write(file_path, arcname=arcname)
|
| 161 |
+
output_paths["zip"] = zip_path
|
| 162 |
+
|
| 163 |
+
if output_type == "markdown":
|
| 164 |
+
# Write all markdown into one file
|
| 165 |
+
md_path = os.path.join(temp_dir, "ocr_output.md")
|
| 166 |
with open(md_path, "w", encoding="utf-8") as f:
|
| 167 |
+
for idx, content in enumerate(results):
|
| 168 |
+
f.write(f"\n\n# Page {selected_indices[idx]+1}\n\n")
|
| 169 |
+
f.write(content.strip())
|
| 170 |
+
f.write("\n")
|
| 171 |
+
output_paths["markdown"] = md_path
|
| 172 |
+
|
| 173 |
+
if output_type == "json":
|
| 174 |
+
# Write the JSON file
|
| 175 |
+
output_json_path = os.path.join(temp_dir, "ocr_output.json")
|
| 176 |
+
with open(output_json_path, "w", encoding="utf-8") as f:
|
| 177 |
+
json.dump(output_json, f, ensure_ascii=False, indent=2)
|
| 178 |
+
output_paths["json"] = output_json_path
|
| 179 |
+
|
| 180 |
+
return output_paths, temp_dir
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
with gr.Blocks() as demo:
|
| 183 |
+
gr.Markdown(
|
| 184 |
+
"# PDF to Markdown & JSON OCR (OpenAI Vision)\n"
|
| 185 |
+
"Upload 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.\n\n"
|
| 186 |
+
"You can also choose to download all results as a single markdown file or a single JSON file.\n\n"
|
| 187 |
+
"**You can also select a range of pages to process.**"
|
| 188 |
+
)
|
| 189 |
pdf_input = gr.File(label="Upload PDF", file_types=[".pdf"])
|
| 190 |
model_choice = gr.Radio(["openai", "mistral"], label="OCR Model", value="openai")
|
| 191 |
+
# Add page range selectors
|
| 192 |
+
page_from = gr.Number(label="Page From", value=1, precision=0, minimum=1)
|
| 193 |
+
page_to = gr.Number(label="Page To (leave blank for last page)", value=None, precision=0, minimum=1)
|
| 194 |
+
output_type = gr.Radio(
|
| 195 |
+
["zip", "markdown", "json"],
|
| 196 |
+
label="Output Format",
|
| 197 |
+
value="zip",
|
| 198 |
+
info="Choose output: ZIP (md files + JSON), single Markdown file, or single JSON file"
|
| 199 |
+
)
|
| 200 |
+
zip_output = gr.File(label="Download ZIP (md files + JSON)", interactive=False, visible=True)
|
| 201 |
+
md_output = gr.File(label="Download Markdown", interactive=False, visible=False)
|
| 202 |
+
json_output = gr.File(label="Download JSON", interactive=False, visible=False)
|
| 203 |
+
|
| 204 |
+
def process_and_return_outputs(pdf_file, model_choice, output_type, page_from, page_to, progress=gr.Progress(track_tqdm=True)):
|
| 205 |
+
# If page_to is None or blank, treat as last page
|
| 206 |
+
page_from = int(page_from) if page_from is not None else 1
|
| 207 |
+
page_to_val = int(page_to) if page_to not in (None, "") else None
|
| 208 |
+
output_paths, temp_dir = pdf_to_outputs_with_progress(pdf_file, model_choice, output_type, page_from, page_to_val, progress=progress)
|
| 209 |
+
# Return only the selected output, others as None
|
| 210 |
+
zip_path = output_paths.get("zip") if output_type == "zip" else None
|
| 211 |
+
md_path = output_paths.get("markdown") if output_type == "markdown" else None
|
| 212 |
+
json_path = output_paths.get("json") if output_type == "json" else None
|
| 213 |
+
return zip_path, md_path, json_path
|
| 214 |
+
|
| 215 |
+
process_btn = gr.Button("Convert PDF")
|
| 216 |
+
process_btn.click(
|
| 217 |
+
process_and_return_outputs,
|
| 218 |
+
inputs=[pdf_input, model_choice, output_type, page_from, page_to],
|
| 219 |
+
outputs=[zip_output, md_output, json_output]
|
| 220 |
+
)
|
| 221 |
|
| 222 |
+
# Dynamically show/hide outputs based on output_type
|
| 223 |
+
def update_output_visibility(output_type):
|
| 224 |
+
return (
|
| 225 |
+
gr.update(visible=(output_type == "zip")),
|
| 226 |
+
gr.update(visible=(output_type == "markdown")),
|
| 227 |
+
gr.update(visible=(output_type == "json")),
|
| 228 |
+
)
|
| 229 |
|
| 230 |
+
output_type.change(
|
| 231 |
+
update_output_visibility,
|
| 232 |
+
inputs=[output_type],
|
| 233 |
+
outputs=[zip_output, md_output, json_output]
|
|
|
|
| 234 |
)
|
| 235 |
|
| 236 |
demo.launch()
|