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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import time
|
| 3 |
+
from typing import List, Tuple, Optional
|
| 4 |
+
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import torch
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import fitz # PyMuPDF
|
| 9 |
+
from transformers import (
|
| 10 |
+
AutoProcessor,
|
| 11 |
+
AutoModelForVision2Seq,
|
| 12 |
+
TextIteratorStreamer,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
MODEL_ID = "HuggingFaceTB/SmolVLM-Instruct-250M" # 250M instruct variant
|
| 16 |
+
# If you ever need to swap models (e.g., 256M/500M), just change the ID.
|
| 17 |
+
|
| 18 |
+
# Load once at startup
|
| 19 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 20 |
+
dtype = torch.float16 if device == "cuda" else torch.float32
|
| 21 |
+
|
| 22 |
+
processor = AutoProcessor.from_pretrained(MODEL_ID)
|
| 23 |
+
model = AutoModelForVision2Seq.from_pretrained(MODEL_ID, torch_dtype=dtype)
|
| 24 |
+
model.to(device)
|
| 25 |
+
model.eval()
|
| 26 |
+
|
| 27 |
+
SYSTEM_PROMPT = (
|
| 28 |
+
"You are an invoice assistant. Answer strictly based on the uploaded document. "
|
| 29 |
+
"If asked for fields (invoice number, date, totals, etc.), extract them from the image."
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
def pdf_to_images(pdf_bytes: bytes, max_pages: int = 5, dpi: int = 216) -> List[Image.Image]:
|
| 33 |
+
"""
|
| 34 |
+
Render first N pages of a PDF to PIL images (RGB).
|
| 35 |
+
"""
|
| 36 |
+
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
|
| 37 |
+
images = []
|
| 38 |
+
for i, page in enumerate(doc):
|
| 39 |
+
if i >= max_pages:
|
| 40 |
+
break
|
| 41 |
+
# Render page
|
| 42 |
+
pix = page.get_pixmap(matrix=fitz.Matrix(dpi/72, dpi/72))
|
| 43 |
+
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
|
| 44 |
+
images.append(img)
|
| 45 |
+
return images
|
| 46 |
+
|
| 47 |
+
def ensure_images(file: Optional[gr.File]) -> List[Image.Image]:
|
| 48 |
+
"""
|
| 49 |
+
Accepts a PDF/PNG/JPEG and returns a list of PIL images.
|
| 50 |
+
- PDF => multiple images (page picker will handle selection)
|
| 51 |
+
- PNG/JPG => single image
|
| 52 |
+
"""
|
| 53 |
+
if file is None:
|
| 54 |
+
return []
|
| 55 |
+
mime = file.mime_type or ""
|
| 56 |
+
data = file.read()
|
| 57 |
+
|
| 58 |
+
if "pdf" in mime or (file.name and file.name.lower().endswith(".pdf")):
|
| 59 |
+
return pdf_to_images(data, max_pages=8)
|
| 60 |
+
# Image path
|
| 61 |
+
img = Image.open(io.BytesIO(data)).convert("RGB")
|
| 62 |
+
return [img]
|
| 63 |
+
|
| 64 |
+
def generate_reply(images: List[Image.Image], user_text: str, chat_history: List[Tuple[str, str]]):
|
| 65 |
+
"""
|
| 66 |
+
Stream a reply grounded on chosen image(s) + chat history.
|
| 67 |
+
We only keep a compact history to stay lean on memory.
|
| 68 |
+
"""
|
| 69 |
+
# Build multimodal messages per transformers' chat template
|
| 70 |
+
# Format: [{"role":"system","content":...}, {"role":"user","content":[text, image, ...]}, ...]
|
| 71 |
+
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 72 |
+
|
| 73 |
+
# Keep only last 4 exchanges to avoid context bloat
|
| 74 |
+
trimmed = chat_history[-4:] if chat_history else []
|
| 75 |
+
|
| 76 |
+
for u, a in trimmed:
|
| 77 |
+
messages.append({"role": "user", "content": u})
|
| 78 |
+
messages.append({"role": "assistant", "content": a})
|
| 79 |
+
|
| 80 |
+
# Add the current turn with images
|
| 81 |
+
multimodal_content = []
|
| 82 |
+
if images:
|
| 83 |
+
# SmolVLM supports multiple images; push them before the text question
|
| 84 |
+
for im in images:
|
| 85 |
+
multimodal_content.append(im)
|
| 86 |
+
if user_text.strip():
|
| 87 |
+
multimodal_content.append(user_text.strip())
|
| 88 |
+
|
| 89 |
+
messages.append({"role": "user", "content": multimodal_content})
|
| 90 |
+
|
| 91 |
+
# Tokenize with chat template
|
| 92 |
+
inputs = processor.apply_chat_template(
|
| 93 |
+
messages,
|
| 94 |
+
add_generation_prompt=True,
|
| 95 |
+
tokenize=True,
|
| 96 |
+
return_tensors="pt"
|
| 97 |
+
).to(device)
|
| 98 |
+
|
| 99 |
+
# Vision inputs: processor handles images separately
|
| 100 |
+
vision_inputs = processor(images=images, return_tensors="pt").to(device)
|
| 101 |
+
|
| 102 |
+
# Merge text & vision inputs
|
| 103 |
+
model_inputs = {**inputs, **vision_inputs}
|
| 104 |
+
|
| 105 |
+
streamer = TextIteratorStreamer(processor.tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 106 |
+
gen_kwargs = dict(
|
| 107 |
+
**model_inputs,
|
| 108 |
+
streamer=streamer,
|
| 109 |
+
max_new_tokens=512,
|
| 110 |
+
do_sample=False,
|
| 111 |
+
temperature=0.0,
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
# Non-blocking generation
|
| 115 |
+
import threading
|
| 116 |
+
thread = threading.Thread(target=model.generate, kwargs=gen_kwargs)
|
| 117 |
+
thread.start()
|
| 118 |
+
|
| 119 |
+
partial = ""
|
| 120 |
+
for token in streamer:
|
| 121 |
+
partial += token
|
| 122 |
+
yield partial
|
| 123 |
+
|
| 124 |
+
def start_chat(file, page_index):
|
| 125 |
+
# Convert to images and preselect a page
|
| 126 |
+
imgs = ensure_images(file)
|
| 127 |
+
if not imgs:
|
| 128 |
+
return gr.update(choices=[], value=None), None, "No file loaded yet."
|
| 129 |
+
|
| 130 |
+
choices = [f"Page {i+1}" for i in range(len(imgs))]
|
| 131 |
+
value = choices[min(page_index, len(imgs)-1)] if page_index is not None else choices[0]
|
| 132 |
+
return gr.update(choices=choices, value=value), imgs, "Document ready. Select a page and ask questions."
|
| 133 |
+
|
| 134 |
+
def page_picker_changed(pages_dropdown, images_state):
|
| 135 |
+
if not images_state:
|
| 136 |
+
return None
|
| 137 |
+
idx = max(0, int(pages_dropdown.split()[-1]) - 1)
|
| 138 |
+
return images_state[idx]
|
| 139 |
+
|
| 140 |
+
with gr.Blocks(title="Invoice Chat (SmolVLM-250M)") as demo:
|
| 141 |
+
gr.Markdown("# Invoice Chat • SmolVLM-Instruct-250M\nAsk questions grounded on your uploaded invoice.")
|
| 142 |
+
with gr.Row():
|
| 143 |
+
with gr.Column(scale=1):
|
| 144 |
+
file = gr.File(label="Upload invoice (PDF/PNG/JPEG)")
|
| 145 |
+
pages = gr.Dropdown(label="Select page (for PDFs)", choices=[], value=None)
|
| 146 |
+
load_btn = gr.Button("Prepare Document")
|
| 147 |
+
with gr.Column(scale=2):
|
| 148 |
+
image_view = gr.Image(label="Current page/image", interactive=False)
|
| 149 |
+
chatbot = gr.Chatbot(height=380)
|
| 150 |
+
user_box = gr.Textbox(label="Your question", placeholder="e.g., What is the invoice number and total?")
|
| 151 |
+
ask_btn = gr.Button("Ask")
|
| 152 |
+
|
| 153 |
+
# Hidden states
|
| 154 |
+
images_state = gr.State([])
|
| 155 |
+
selected_img_state = gr.State(None)
|
| 156 |
+
|
| 157 |
+
# Wire events
|
| 158 |
+
load_btn.click(
|
| 159 |
+
start_chat,
|
| 160 |
+
inputs=[file, gr.State(0)],
|
| 161 |
+
outputs=[pages, images_state, gr.Textbox(visible=False)]
|
| 162 |
+
)
|
| 163 |
+
pages.change(page_picker_changed, inputs=[pages, images_state], outputs=[image_view])
|
| 164 |
+
|
| 165 |
+
def chat(user_text, history, images_state, image_view):
|
| 166 |
+
if not user_text.strip():
|
| 167 |
+
return gr.update(), history
|
| 168 |
+
# Choose the selected image; if none, fall back to first
|
| 169 |
+
sel_img = None
|
| 170 |
+
if image_view is not None and isinstance(image_view, dict) and image_view.get("image"):
|
| 171 |
+
# gr.Image returns a dict in some contexts; handle robustly
|
| 172 |
+
sel_img = Image.open(image_view["image"]).convert("RGB")
|
| 173 |
+
elif images_state:
|
| 174 |
+
sel_img = images_state[0]
|
| 175 |
+
|
| 176 |
+
if sel_img is None:
|
| 177 |
+
history = history + [(user_text, "Please upload a document first.")]
|
| 178 |
+
return gr.update(value=history), history
|
| 179 |
+
|
| 180 |
+
stream = generate_reply([sel_img], user_text, history)
|
| 181 |
+
acc = ""
|
| 182 |
+
for chunk in stream:
|
| 183 |
+
acc = chunk
|
| 184 |
+
yield history + [(user_text, acc)], history + [(user_text, acc)]
|
| 185 |
+
|
| 186 |
+
ask_btn.click(
|
| 187 |
+
chat,
|
| 188 |
+
inputs=[user_box, chatbot, images_state, image_view],
|
| 189 |
+
outputs=[chatbot, chatbot]
|
| 190 |
+
)
|
| 191 |
+
user_box.submit(
|
| 192 |
+
chat,
|
| 193 |
+
inputs=[user_box, chatbot, images_state, image_view],
|
| 194 |
+
outputs=[chatbot, chatbot]
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
if __name__ == "__main__":
|
| 198 |
+
demo.launch()
|