Update app.py
Browse files
app.py
CHANGED
|
@@ -5,24 +5,36 @@ from PIL import Image
|
|
| 5 |
from pdf2image import convert_from_path
|
| 6 |
import os
|
| 7 |
|
| 8 |
-
#
|
| 9 |
-
|
| 10 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
def process_textbook(pdf_file, start_page, end_page):
|
| 28 |
if pdf_file is None:
|
|
@@ -34,16 +46,16 @@ def process_textbook(pdf_file, start_page, end_page):
|
|
| 34 |
pdf_file.name,
|
| 35 |
first_page=int(start_page),
|
| 36 |
last_page=int(end_page),
|
| 37 |
-
dpi=150
|
| 38 |
)
|
| 39 |
|
| 40 |
extracted_text = []
|
| 41 |
|
| 42 |
for i, page_image in enumerate(images):
|
| 43 |
page_num = int(start_page) + i
|
|
|
|
| 44 |
|
| 45 |
-
# 3.
|
| 46 |
-
# NuMarkdown expects a standard user/assistant chat format
|
| 47 |
conversation = [
|
| 48 |
{
|
| 49 |
"role": "user",
|
|
@@ -54,27 +66,31 @@ def process_textbook(pdf_file, start_page, end_page):
|
|
| 54 |
}
|
| 55 |
]
|
| 56 |
|
| 57 |
-
# Apply
|
| 58 |
text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
|
| 59 |
|
| 60 |
-
#
|
| 61 |
inputs = processor(
|
| 62 |
text=[text_prompt],
|
| 63 |
images=[page_image],
|
| 64 |
-
padding=True,
|
| 65 |
return_tensors="pt"
|
| 66 |
-
).to(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
-
# 4.
|
| 69 |
with torch.no_grad():
|
| 70 |
generated_ids = model.generate(
|
| 71 |
**inputs,
|
| 72 |
-
max_new_tokens=4096,
|
| 73 |
-
do_sample=False
|
| 74 |
)
|
| 75 |
-
|
| 76 |
-
# 5.
|
| 77 |
-
# We slice the output to remove the input prompts from the result
|
| 78 |
input_len = inputs.input_ids.shape[1]
|
| 79 |
generated_ids_trimmed = generated_ids[:, input_len:]
|
| 80 |
|
|
@@ -89,12 +105,17 @@ def process_textbook(pdf_file, start_page, end_page):
|
|
| 89 |
return "\n\n---\n\n".join(extracted_text)
|
| 90 |
|
| 91 |
except Exception as e:
|
| 92 |
-
|
| 93 |
-
|
|
|
|
| 94 |
|
| 95 |
-
#
|
| 96 |
with gr.Blocks() as demo:
|
| 97 |
-
gr.Markdown("## π
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
with gr.Row():
|
| 99 |
with gr.Column():
|
| 100 |
file_input = gr.File(label="Upload Textbook PDF")
|
|
|
|
| 5 |
from pdf2image import convert_from_path
|
| 6 |
import os
|
| 7 |
|
| 8 |
+
# --- CONFIGURATION ---
|
| 9 |
+
MODEL_ID = "numind/NuMarkdown-8B-Thinking"
|
|
|
|
| 10 |
|
| 11 |
+
# 1. Hardware Detection
|
| 12 |
+
# We explicitly check for CUDA. If not found, we default to CPU with float32.
|
| 13 |
+
if torch.cuda.is_available():
|
| 14 |
+
device = "cuda"
|
| 15 |
+
dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
|
| 16 |
+
print(f"π Running on GPU ({torch.cuda.get_device_name(0)}) with {dtype}")
|
| 17 |
+
else:
|
| 18 |
+
device = "cpu"
|
| 19 |
+
dtype = torch.float32 # CPU must use float32 to avoid "Layer not implemented" errors
|
| 20 |
+
print("β οΈ Running on CPU. This will be SLOW (2-5 mins per page). Requires ~32GB RAM.")
|
| 21 |
|
| 22 |
+
# 2. Load Model & Processor
|
| 23 |
+
print("Loading model... (This may take a while)")
|
| 24 |
+
try:
|
| 25 |
+
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
|
| 26 |
+
model = AutoModelForImageTextToText.from_pretrained(
|
| 27 |
+
MODEL_ID,
|
| 28 |
+
torch_dtype=dtype,
|
| 29 |
+
trust_remote_code=True,
|
| 30 |
+
low_cpu_mem_usage=True # optimized loading
|
| 31 |
+
).to(device)
|
| 32 |
+
model.eval()
|
| 33 |
+
print("β
Model loaded successfully.")
|
| 34 |
+
except ValueError as e:
|
| 35 |
+
print("\nπ CRITICAL ERROR: Transformers version is too old.")
|
| 36 |
+
print("You MUST install from source: pip install git+https://github.com/huggingface/transformers.git\n")
|
| 37 |
+
raise e
|
| 38 |
|
| 39 |
def process_textbook(pdf_file, start_page, end_page):
|
| 40 |
if pdf_file is None:
|
|
|
|
| 46 |
pdf_file.name,
|
| 47 |
first_page=int(start_page),
|
| 48 |
last_page=int(end_page),
|
| 49 |
+
dpi=150
|
| 50 |
)
|
| 51 |
|
| 52 |
extracted_text = []
|
| 53 |
|
| 54 |
for i, page_image in enumerate(images):
|
| 55 |
page_num = int(start_page) + i
|
| 56 |
+
print(f"Processing page {page_num}...")
|
| 57 |
|
| 58 |
+
# 3. Construct Qwen2.5-VL / NuMarkdown Prompt
|
|
|
|
| 59 |
conversation = [
|
| 60 |
{
|
| 61 |
"role": "user",
|
|
|
|
| 66 |
}
|
| 67 |
]
|
| 68 |
|
| 69 |
+
# Apply chat template
|
| 70 |
text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
|
| 71 |
|
| 72 |
+
# Prepare Inputs
|
| 73 |
inputs = processor(
|
| 74 |
text=[text_prompt],
|
| 75 |
images=[page_image],
|
|
|
|
| 76 |
return_tensors="pt"
|
| 77 |
+
).to(device)
|
| 78 |
+
|
| 79 |
+
# Cast inputs to correct dtype if on CPU (processor usually returns float32, but good to be safe)
|
| 80 |
+
if device == "cpu":
|
| 81 |
+
inputs["pixel_values"] = inputs["pixel_values"].to(torch.float32)
|
| 82 |
+
else:
|
| 83 |
+
inputs["pixel_values"] = inputs["pixel_values"].to(dtype)
|
| 84 |
|
| 85 |
+
# 4. Generate
|
| 86 |
with torch.no_grad():
|
| 87 |
generated_ids = model.generate(
|
| 88 |
**inputs,
|
| 89 |
+
max_new_tokens=4096,
|
| 90 |
+
do_sample=False
|
| 91 |
)
|
| 92 |
+
|
| 93 |
+
# 5. Decode (Slice off the prompt)
|
|
|
|
| 94 |
input_len = inputs.input_ids.shape[1]
|
| 95 |
generated_ids_trimmed = generated_ids[:, input_len:]
|
| 96 |
|
|
|
|
| 105 |
return "\n\n---\n\n".join(extracted_text)
|
| 106 |
|
| 107 |
except Exception as e:
|
| 108 |
+
import traceback
|
| 109 |
+
traceback.print_exc()
|
| 110 |
+
return f"Error processing file: {str(e)}\n\n(If on CPU, check if you ran out of RAM. You need ~32GB for this model.)"
|
| 111 |
|
| 112 |
+
# 3. UI Layout
|
| 113 |
with gr.Blocks() as demo:
|
| 114 |
+
gr.Markdown("## π NuMarkdown-8B OCR (Qwen2.5-VL Architecture)")
|
| 115 |
+
|
| 116 |
+
if device == "cpu":
|
| 117 |
+
gr.Markdown("β οΈ **WARNING: Running on CPU.** Expect very slow performance (minutes per page).")
|
| 118 |
+
|
| 119 |
with gr.Row():
|
| 120 |
with gr.Column():
|
| 121 |
file_input = gr.File(label="Upload Textbook PDF")
|