File size: 3,315 Bytes
f9c5a74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import spaces
import gradio as gr
from pdf2image import convert_from_path
from byaldi import RAGMultiModalModel
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info
import torch
import subprocess

# Install flash-attn if not already installed
subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)

# Load the RAG Model and the Qwen2-VL-2B-Instruct model
RAG = RAGMultiModalModel.from_pretrained("vidore/colpali")
model = Qwen2VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-2B-Instruct",
                                                        trust_remote_code=True, torch_dtype=torch.bfloat16).cuda().eval()
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", trust_remote_code=True)

@spaces.GPU()
def process_pdf_and_query(pdf_file, user_query):
    # Convert the PDF to images
    images = convert_from_path(pdf_file.name)  # pdf_file.name gives the file path
    num_images = len(images)

    # Indexing the PDF in RAG
    RAG.index(
        input_path=pdf_file.name,
        index_name="image_index",  # index will be saved at index_root/index_name/
        store_collection_with_index=False,
        overwrite=True
    )

    # Search the query in the RAG model
    results = RAG.search(user_query, k=1)
    if not results:
        return "No results found.", num_images

    # Retrieve the page number and process image
    image_index = results[0]["page_num"] - 1
    messages = [
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "image": images[image_index],
                },
                {"type": "text", "text": user_query},
            ],
        }
    ]

    # Generate text with the Qwen model
    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("cuda")
    
    # Generate the output response
    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], num_images

# Define the Gradio Interface
pdf_input = gr.File(label="Upload PDF")  # Single PDF file input
query_input = gr.Textbox(label="Enter your query", placeholder="Ask a question about the PDF")  # User query input
output_text = gr.Textbox(label="Model Answer")  # Output for the model's answer
output_images = gr.Textbox(label="Number of Images in PDF")  # Output for number of images

# Launch the Gradio app
demo = gr.Interface(
    fn=process_pdf_and_query, 
    inputs=[pdf_input, query_input],  # List of inputs
    outputs=[output_text, output_images],  # List of outputs
    title="Multimodal RAG with Image Query - By Pejman Ebrahimi"
)

demo.launch(debug=True)  # Start the interface