pankti07 commited on
Commit
3f44afb
Β·
verified Β·
1 Parent(s): c0eef89

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -33
app.py CHANGED
@@ -5,24 +5,36 @@ from PIL import Image
5
  from pdf2image import convert_from_path
6
  import os
7
 
8
- # 1. Hardware & Model Setup
9
- model_id = "numind/NuMarkdown-8B-Thinking"
10
- device = "cuda" if torch.cuda.is_available() else "cpu"
11
 
12
- # 8B models perform best in bfloat16 on Ampere+ GPUs, or float16 on older ones
13
- dtype = torch.bfloat16 if torch.cuda.is_available() and torch.cuda.is_bf16_supported() else torch.float16
 
 
 
 
 
 
 
 
14
 
15
- print(f"Loading {model_id} on {device} with {dtype}...")
16
-
17
- # 2. Loading Model & Processor
18
- # We use device_map="auto" to handle VRAM distribution automatically (Crucial for 8B models)
19
- processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
20
- model = AutoModelForImageTextToText.from_pretrained(
21
- model_id,
22
- torch_dtype=dtype,
23
- trust_remote_code=True,
24
- device_map="auto"
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 # 150 DPI is usually sufficient for 8B models
38
  )
39
 
40
  extracted_text = []
41
 
42
  for i, page_image in enumerate(images):
43
  page_num = int(start_page) + i
 
44
 
45
- # 3. CONSTRUCT PROMPT FOR NUMARKDOWN
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 the chat template to format the text prompt
58
  text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
59
 
60
- # Process inputs (Image + Text) -> Tensors
61
  inputs = processor(
62
  text=[text_prompt],
63
  images=[page_image],
64
- padding=True,
65
  return_tensors="pt"
66
- ).to(model.device)
 
 
 
 
 
 
67
 
68
- # 4. GENERATION
69
  with torch.no_grad():
70
  generated_ids = model.generate(
71
  **inputs,
72
- max_new_tokens=4096, # Increased limit for dense textbook pages
73
- do_sample=False # Deterministic output usually better for OCR
74
  )
75
-
76
- # 5. DECODING
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
- # Catch OOM or other processing errors
93
- return f"Processing Error: {str(e)}\n\n*Note: An 8B model requires ~16GB+ VRAM. If you have less, consider 4-bit quantization.*"
 
94
 
95
- # 4. UI Layout
96
  with gr.Blocks() as demo:
97
- gr.Markdown("## πŸ“š Textbook OCR Analysis (NuMarkdown-8B)")
 
 
 
 
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")