"""Chat with a PDF, using Granite Embedding Vision R2 for retrieval and Granite Vision + Granite to answer.""" import spaces # isort: skip (must be imported before torch) import sys import time import uuid from collections import OrderedDict from pathlib import Path from typing import NamedTuple import gradio as gr sys.path.insert(0, str(Path(__file__).parent)) import generation import progress import retrieval import views from themes.research_monochrome import theme ROOT = Path(__file__).parent.parent SRC = Path(__file__).parent # name -> (pdf, first-page thumbnail, subtitle, tags). Tags describe the content for the card only. EXAMPLES = { "Granite Vision paper": ( ROOT / "examples" / "granite_vision_paper.pdf", ROOT / "examples" / "thumbs" / "granite_vision_paper.png", "26 pages · multimodal model", ["Tables", "Charts", "Text"], ), "Granite Embedding paper": ( ROOT / "examples" / "granite_embedding_paper.pdf", ROOT / "examples" / "thumbs" / "granite_embedding_paper.png", "19 pages · embedding models", ["Tables", "Text"], ), } # Example questions per document as (kind of content, question), so a suggestion never refers to a paper that is # not the indexed one. The kind is shown as a colored tag on the suggestion. DOC_QUESTIONS = { "Granite Vision paper": [ ("Text", "What data was DocFM built from?"), ("Table", "What DocVQA and ChartQA scores did Granite Vision get in the small-model comparison?"), ("Figure", "What is the total order price on the receipt in Figure 1?"), ("Multilingual", "¿Cuántos parámetros tiene Granite Vision?"), ], "Granite Embedding paper": [ ("Text", "Why were the models not trained on MS-MARCO?"), ( "Table", "How long does granite-embedding-30m-english take per query compared with granite-embedding-125m-english?", ), ("Chart", "Which model has the highest average score in Figure 1?"), ("Multilingual", "¿Qué idiomas admiten los modelos multilingües de Granite Embedding?"), ], } GENERIC_QUESTIONS = [ ("Text", "Summarize this document."), ("Table", "What tables or charts does this document contain, and what do they show?"), ("Chart", "What are the key numbers in this document?"), ("Text", "Which page has the most important result?"), ] TOP_K = 2 COMPARE_TOP_K = 3 MAX_CACHED_DOCS = 8 # Indexes are kept server-side (embeddings are large); sessions only hold a key into this cache. # On ZeroGPU, @spaces.GPU functions run in a forked worker process, so they must never read or write these caches: # writes would be lost and reads could be stale. Pass data in as arguments and send results back by yielding them. _indexes: OrderedDict[str, retrieval.DocIndex] = OrderedDict() # Vision notes per (doc key, page, question) so repeated questions skip the vision model. _notes_cache: dict[tuple[str, int, str], str] = {} def light_only(base: gr.themes.Base) -> gr.themes.Base: """Give every dark-mode theme value its light value: the layout is designed for light mode only.""" for name in vars(base): if name.endswith("_dark") and hasattr(base, name[: -len("_dark")]): setattr(base, name, getattr(base, name[: -len("_dark")])) return base class Step(NamedTuple): """One update from `_answer_gpu`.""" stage: str # searching | retrieved | reading | read | answering | done hits: list text: str # the answer so far context: str # the vision model's notes, which the language model answers from bar: str # progress bar html search_ms: float notes_read: dict[int, str] | None = None # new vision notes per page, for the caller to cache (set on "read") def _remember(key: str, index: retrieval.DocIndex) -> None: _indexes[key] = index _indexes.move_to_end(key) while len(_indexes) > MAX_CACHED_DOCS: evicted, _ = _indexes.popitem(last=False) for stale in [k for k in _notes_cache if k[0] == evicted]: del _notes_cache[stale] @spaces.GPU(duration=120) def _index_gpu(name: str, pdf_path: str): # noqa: ANN202 """Render and embed a PDF, yielding (index so far, total pages) after each batch.""" images = retrieval.render_pages(pdf_path) total = len(images) for index in retrieval.index_pages(name, images): yield index, total def _screen( stage: str, key: str | None = None, name: str = "", total: int = 0, index: retrieval.DocIndex | None = None, questions: list[tuple[str, str]] | None = None, ) -> list: """Updates for `screen_outputs`, which every stage of the left panel and the empty chat area depend on.""" landing, ready = stage == "landing", stage == "ready" placeholder = { "landing": "Index a document to start", "indexing": "Available once indexing finishes", "ready": f"Ask about {name}…", }[stage] question_update = gr.update(placeholder=placeholder, value="", interactive=ready) return [ key, gr.update(visible=landing), gr.update(value="" if landing else views.index_view(name, total, index, finished=ready), visible=not landing), gr.update(value="" if landing else views.index_log(index, finished=ready), visible=not landing), gr.update(visible=stage == "indexing"), gr.update(value="", visible=False), views.doc_tag(name, total) if not landing else "", gr.update(value=views.welcome_html(stage), visible=True), views.suggestions_html(questions or [], stage), question_update, gr.update(interactive=ready), ] def start_indexing(example: str | None, upload: str | None): # noqa: ANN201 """Index the chosen example or uploaded PDF, streaming progress to the UI.""" if upload: pdf_path, name = upload, Path(upload).name key, uploaded = f"upload-{uuid.uuid4().hex}", True elif example: pdf_path, name = str(EXAMPLES[example][0]), example key, uploaded = f"example-{example}", False else: raise gr.Error("Pick an example document or upload a PDF.") pages = retrieval.page_count(pdf_path) if pages > retrieval.MAX_PAGES: raise gr.Error(f"This PDF has {pages} pages; the limit is {retrieval.MAX_PAGES}.") questions = GENERIC_QUESTIONS if uploaded else DOC_QUESTIONS[name] if key in _indexes and len(_indexes[key]) == pages: yield _screen("ready", key, name, pages, _indexes[key], questions) return yield _screen("indexing", key, name, pages, None, questions) for index, total in _index_gpu(name, pdf_path): _remember(key, index) yield _screen("indexing", key, name, total, index, questions) yield _screen("ready", key, name, pages, _indexes[key], questions) def start_over() -> list: """Return every panel to the landing state.""" return [ *_screen("landing"), None, # upload gr.update(value=[], visible=False), # chat history "", # progress bar gr.update(visible=False), # notes accordion views.compare_empty(), # compare output ] def _plan(pages: int) -> list[progress.Stage]: """The stages a question goes through: search, read each page, write the answer.""" stages = [progress.Stage("search", "Finding pages")] stages += [progress.Stage("read", f"Reading page {n + 1} of {pages}") for n in range(pages)] stages.append(progress.Stage("answer_notes", "Writing answer from notes")) return stages @spaces.GPU(duration=120) def _answer_gpu(index: retrieval.DocIndex, question: str, method: str, cached: dict[int, str]): # noqa: ANN202 """Retrieve pages, read them with the vision model, then answer with the language model, yielding `Step`s. `cached` holds vision notes already written for this question, per page; new ones come back in `notes_read`. """ tracker = progress.Tracker(_plan(TOP_K)) yield Step("searching", [], "", "", tracker.render(), 0.0) began = time.perf_counter() hits = retrieval.search(index, question, top_k=TOP_K, method=method) search_ms = (time.perf_counter() - began) * 1000 tracker.set_stages(_plan(len(hits))) tracker.advance() yield Step("retrieved", hits, "", "", tracker.render(), search_ms) notes, read = "", {} for hit in hits: if hit.page not in cached: partial = "" for partial, tokens in generation.read_page(question, index.images[hit.page]): tracker.update(tokens) yield Step("reading", hits, "", f"{notes}[Page {hit.page + 1}] {partial}", tracker.render(), search_ms) read[hit.page] = partial tracker.advance() notes += f"[Page {hit.page + 1}] {cached.get(hit.page, read.get(hit.page))}\n\n" yield Step("read", hits, "", notes, tracker.render(), search_ms, read) answer = "" for answer, tokens in generation.answer_from_notes(question, notes): tracker.update(tokens) yield Step("answering", hits, answer, notes, tracker.render(), search_ms) tracker.advance() yield Step("done", hits, answer, notes, tracker.render(finished=True), search_ms) def chat(question: str, history: list, key: str | None, method: str): # noqa: ANN201 """Handle one chat turn, streaming updates for `chat_outputs`.""" if not key or key not in _indexes or not len(_indexes[key]): raise gr.Error("Index a document first.") if not question.strip(): raise gr.Error("Type a question.") index = _indexes[key] history = [*history, {"role": "user", "content": question}] hidden = gr.update(visible=False) yield gr.update(value=history, visible=True), hidden, gr.update(), gr.update(), "", "", hidden, hidden left, context = gr.update(), "" cached = {page: notes for (k, page, q), notes in _notes_cache.items() if k == key and q == question} for step in _answer_gpu(index, question, method, cached): for page, notes in (step.notes_read or {}).items(): _notes_cache[(key, page, question)] = notes # Send the retrieved pages once: re-sending them on every token would reset the heatmap the user is exploring. results = gr.update() if step.stage == "retrieved": left = hidden results = gr.update(value=views.results_view(index, step.hits, method, step.search_ms), visible=True) context = step.context or context bar = "" if step.stage == "done" else step.bar message = views.answer_message(step.stage, step.text, step.hits) yield ( [*history, {"role": "assistant", "content": message}], hidden, left, results, bar, context, gr.update(visible=bool(context)), left, ) @spaces.GPU(duration=60) def _compare_gpu(index: retrieval.DocIndex, question: str, methods: list[str]): # noqa: ANN202 return retrieval.compare(index, question, methods, top_k=COMPARE_TOP_K) def run_compare(question: str, key: str | None, methods: list[str]) -> str: """Rank the same question with several search methods and show them side by side.""" if not key or key not in _indexes or not len(_indexes[key]): raise gr.Error("Index a document first.") if not question.strip(): raise gr.Error("Type a question to compare.") if not methods: raise gr.Error("Pick at least one search method.") ordered = [m for m in retrieval.SEARCH_METHODS if m in methods] index = _indexes[key] results, encode_ms = _compare_gpu(index, question, ordered) return views.compare_view(index, results, encode_ms) HEAD = ( '' '' ) # Suggestion chips are plain HTML buttons; a click fires the component's click event with the chip's question. PICK_JS = """ element.addEventListener('click', (event) => { const chip = event.target.closest('.q-chip'); if (chip && !chip.disabled) trigger('click', {question: chip.dataset.q}); }); """ def picked_question(event: gr.EventData) -> str: """The question on the suggestion chip that was clicked.""" return event.question with gr.Blocks(title="Granite Embedding Vision Demo", fill_width=True, analytics_enabled=False) as demo: index_key = gr.State(None) doc_questions = gr.State([]) with gr.Row(elem_id="topbar", equal_height=True): gr.HTML(views.brand_html(), elem_id="brand") info_btn = gr.Button("", elem_id="info-btn", scale=0, min_width=28, icon=str(SRC / "assets" / "info.svg")) over_btn = gr.Button( "Start over", elem_id="over-btn", scale=0, min_width=120, icon=str(SRC / "assets" / "restart.svg") ) with gr.Column(visible=False, elem_id="info-modal") as info_modal: gr.HTML(views.INFO_HTML) close_btn = gr.Button("", elem_id="info-close", scale=0, min_width=28, icon=str(SRC / "assets" / "close.svg")) with gr.Row(elem_id="main", equal_height=True): with gr.Column(scale=1, elem_classes="panel", elem_id="left"): with gr.Column(elem_id="landing") as landing: with gr.Column(elem_id="drop-wrap"): upload = gr.File( show_label=False, file_types=[".pdf"], height=420, elem_id="dropzone", container=False ) gr.HTML(views.landing_art(), elem_id="drop-art") gr.HTML(views.examples_head(), elem_id="examples-head") with gr.Row(elem_id="examples"): cards = [ gr.HTML( views.example_card_html(name, sub, thumb, tags, selected=i == 0), js_on_load="element.addEventListener('click', () => trigger('click'))", elem_classes="example-wrap", ) for i, (name, (_pdf, thumb, sub, tags)) in enumerate(EXAMPLES.items()) ] index_html = gr.HTML(visible=False, elem_id="index-html") cancel_btn = gr.Button( "Cancel", visible=False, elem_id="cancel", scale=0, icon=str(SRC / "assets" / "close.svg") ) log_html = gr.HTML(visible=False, elem_id="log-html") results_html = gr.HTML(visible=False, elem_id="results-html", js_on_load=views.HEATMAP_JS) with gr.Accordion( "What the answering model was given", open=False, visible=False, elem_id="notes" ) as notes_box: notes = gr.Textbox(show_label=False, lines=8, interactive=False) with gr.Column(scale=1, elem_classes="panel", elem_id="right"): with gr.Row(elem_id="canvas-head"): right_title = gr.HTML(views.panel_title("chat"), elem_id="chat-title") doc_chip = gr.HTML(elem_id="doc-chip") view = gr.Radio( ["Chat", "Compare retrieval"], value="Chat", show_label=False, container=False, elem_id="view" ) with gr.Column(elem_id="chat-view") as chat_view: with gr.Row(elem_id="tiles", equal_height=True): with gr.Column(elem_classes="tile", min_width=200): gr.HTML(views.embed_tile()) with gr.Column(elem_classes="tile", min_width=200): gr.HTML(views.method_head()) method = gr.Radio( retrieval.SEARCH_METHODS, value=retrieval.MULTI, show_label=False, container=False, elem_id="method", ) method_help = gr.HTML(views.method_help(retrieval.MULTI)) welcome = gr.HTML(views.welcome_html("landing"), elem_id="welcome") chatbot = gr.Chatbot( show_label=False, visible=False, elem_id="chatbot", sanitize_html=False, buttons=["copy"], layout="bubble", ) progress_bar = gr.HTML(elem_id="progress") suggestions = gr.HTML(elem_id="suggest", js_on_load=PICK_JS) with gr.Row(elem_id="ask-row"): question = gr.Textbox( show_label=False, container=False, placeholder="Index a document to start", interactive=False, scale=1, lines=1, max_lines=3, elem_id="question", ) ask_btn = gr.Button( "", elem_id="send", scale=0, min_width=32, interactive=False, icon=str(SRC / "assets" / "send.svg"), ) with gr.Column(elem_id="compare-view", visible=False) as compare_view: with gr.Column(elem_classes="qbox"): gr.HTML("
Same question, both search methods
") cmp_question = gr.Textbox( show_label=False, container=False, placeholder="Which page answers this?", lines=2, elem_id="cmp-q", ) cmp_suggest = gr.HTML(elem_id="cmp-suggest", js_on_load=PICK_JS) with gr.Row(elem_id="cmp-controls"): cmp_methods = gr.CheckboxGroup( retrieval.SEARCH_METHODS, value=retrieval.SEARCH_METHODS, show_label=False, container=False, elem_id="cmp-methods", ) cmp_btn = gr.Button("Compare", elem_id="cmp-btn", scale=0, min_width=110) cmp_out = gr.HTML(views.compare_empty(), elem_id="cmp-out") # Components every screen change updates (see `_screen`). screen_outputs = [ index_key, landing, index_html, log_html, cancel_btn, results_html, doc_chip, welcome, suggestions, question, ask_btn, ] def _starter(name: str | None): # noqa: ANN202 def run(path: str | None = None): # noqa: ANN202 for update in start_indexing(name, path): questions = GENERIC_QUESTIONS if name is None else DOC_QUESTIONS[name] yield [*update, questions, views.suggestions_html(questions, "ready")] return run started_outputs = [*screen_outputs, doc_questions, cmp_suggest] started = [ card.click(_starter(name), outputs=started_outputs, show_progress="hidden") for card, name in zip(cards, EXAMPLES, strict=True) ] started.append(upload.upload(_starter(None), inputs=upload, outputs=started_outputs, show_progress="hidden")) reset_outputs = [*screen_outputs, upload, chatbot, progress_bar, notes_box, cmp_out] over_btn.click(start_over, outputs=reset_outputs, cancels=started).then(lambda: "", outputs=cmp_suggest) cancel_btn.click(start_over, outputs=reset_outputs, cancels=started).then(lambda: "", outputs=cmp_suggest) info_btn.click(lambda: gr.update(visible=True), outputs=info_modal) close_btn.click(lambda: gr.update(visible=False), outputs=info_modal) chat_outputs = [chatbot, welcome, index_html, results_html, progress_bar, notes, notes_box, log_html] asked = gr.on( triggers=[question.submit, ask_btn.click], fn=chat, inputs=[question, chatbot, index_key, method], outputs=chat_outputs, show_progress="hidden", ) asked.then(lambda: "", outputs=question) suggestions.click(picked_question, outputs=question, show_progress="hidden").then( chat, inputs=[question, chatbot, index_key, method], outputs=chat_outputs, show_progress="hidden" ).then(lambda: "", outputs=question) cmp_suggest.click(picked_question, outputs=cmp_question, show_progress="hidden").then( run_compare, inputs=[cmp_question, index_key, cmp_methods], outputs=cmp_out ) method.change(views.method_help, inputs=method, outputs=method_help) view.change( lambda v: (gr.update(visible=v == "Chat"), gr.update(visible=v != "Chat"), views.panel_title(v)), inputs=view, outputs=[chat_view, compare_view, right_title], show_progress="hidden", ) cmp_btn.click(run_compare, inputs=[cmp_question, index_key, cmp_methods], outputs=cmp_out) cmp_question.submit(run_compare, inputs=[cmp_question, index_key, cmp_methods], outputs=cmp_out) if __name__ == "__main__": demo.queue().launch( show_error=True, theme=light_only(theme), css=(SRC / "app.css").read_text(), head=HEAD, allowed_paths=[str(SRC / "assets")], # Spaces turns on server-side rendering, which inlines app.css without the `.gradio-container` prefix # the browser adds, so Gradio's own rules win (the logo grows to full width). Render in the browser. ssr_mode=False, )