File size: 2,246 Bytes
ec5bfd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import gradio as gr
import torch
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
from PIL import Image
from byaldi import RAGMultiModalModel
from qwen_vl_utils import process_vision_info

# Model and processor names
RAG_MODEL = "vidore/colpali"
QWN_MODEL = "Qwen/Qwen2-VL-7B-Instruct"

def load_models():
    RAG = RAGMultiModalModel.from_pretrained(RAG_MODEL)
    
    model = Qwen2VLForConditionalGeneration.from_pretrained(
        QWN_MODEL,
        torch_dtype=torch.bfloat16,
        attn_implementation="flash_attention_2",
        device_map="auto",
        trust_remote_code=True
    ).eval()
    
    processor = AutoProcessor.from_pretrained(QWN_MODEL, trust_remote_code=True)
    
    return RAG, model, processor

RAG, model, processor = load_models()

def document_rag(image, text_query):
    messages = [
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "image": image,
                },
                {"type": "text", "text": text_query},
            ],
        }
    ]
    text = processor.apply_chat_template(
        messages, tokenize=False, add_generation_prompt=True
    )
    image_inputs, video_inputs = process_vision_info(messages)
    inputs = processor(
        text=[text],
        images=image_inputs,
        videos=video_inputs,
        padding=True,
        return_tensors="pt",
    )
    inputs = inputs.to(model.device)
    generated_ids = model.generate(**inputs, max_new_tokens=50)
    generated_ids_trimmed = [
        out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
    ]
    output_text = processor.batch_decode(
        generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
    )
    return output_text[0]

# Define the Gradio interface
iface = gr.Interface(
    fn=document_rag,
    inputs=[
        gr.Image(type="pil", label="Upload an image"),
        gr.Textbox(label="Enter your text query")
    ],
    outputs=gr.Textbox(label="Result"),
    title="Document Processor",
    description="Upload an image and enter a text query to process the document.",
)

# Launch the app
if __name__ == "__main__":
    iface.launch()