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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import fitz # PyMuPDF
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import torch
|
| 4 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 5 |
+
|
| 6 |
+
# ----------------------------------------------------------------------
|
| 7 |
+
# Config
|
| 8 |
+
# ----------------------------------------------------------------------
|
| 9 |
+
MODEL_ID = "Qwen/Qwen3-Reranker-4B" # or "Qwen/Qwen3-Reranker-0.6B" / "-8B"
|
| 10 |
+
NUM_PAGES = 2 # how many pages from the start of each PDF to use
|
| 11 |
+
MAX_LENGTH = 3072 # max tokens per (query + pages) pair
|
| 12 |
+
BATCH_SIZE = 1 # lower this if you hit out-of-memory
|
| 13 |
+
DEFAULT_INSTRUCTION = (
|
| 14 |
+
"Given a web search query, retrieve relevant passages that answer the query"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# ----------------------------------------------------------------------
|
| 18 |
+
# Load model once (4-bit quantized)
|
| 19 |
+
# ----------------------------------------------------------------------
|
| 20 |
+
bnb_config = BitsAndBytesConfig(
|
| 21 |
+
load_in_4bit=True,
|
| 22 |
+
bnb_4bit_quant_type="nf4",
|
| 23 |
+
bnb_4bit_use_double_quant=True,
|
| 24 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
print(f"Loading {MODEL_ID} in 4-bit ...")
|
| 28 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, padding_side="left")
|
| 29 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 30 |
+
MODEL_ID,
|
| 31 |
+
quantization_config=bnb_config,
|
| 32 |
+
device_map="auto",
|
| 33 |
+
).eval()
|
| 34 |
+
print("Model loaded.")
|
| 35 |
+
|
| 36 |
+
token_true_id = tokenizer.convert_tokens_to_ids("yes")
|
| 37 |
+
token_false_id = tokenizer.convert_tokens_to_ids("no")
|
| 38 |
+
|
| 39 |
+
prefix = (
|
| 40 |
+
"<|im_start|>system\nJudge whether the Document meets the requirements based on "
|
| 41 |
+
"the Query and the Instruct provided. Note that the answer can only be "
|
| 42 |
+
'"yes" or "no".<|im_end|>\n<|im_start|>user\n'
|
| 43 |
+
)
|
| 44 |
+
suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
|
| 45 |
+
prefix_tokens = tokenizer.encode(prefix, add_special_tokens=False)
|
| 46 |
+
suffix_tokens = tokenizer.encode(suffix, add_special_tokens=False)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# ----------------------------------------------------------------------
|
| 50 |
+
# Reranker functions
|
| 51 |
+
# ----------------------------------------------------------------------
|
| 52 |
+
def _format(query, doc, instruction):
|
| 53 |
+
return f"<Instruct>: {instruction}\n<Query>: {query}\n<Document>: {doc}"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _tokenize(pairs):
|
| 57 |
+
inputs = tokenizer(
|
| 58 |
+
pairs,
|
| 59 |
+
padding=False,
|
| 60 |
+
truncation="longest_first",
|
| 61 |
+
return_attention_mask=False,
|
| 62 |
+
max_length=MAX_LENGTH - len(prefix_tokens) - len(suffix_tokens),
|
| 63 |
+
)
|
| 64 |
+
for i, ids in enumerate(inputs["input_ids"]):
|
| 65 |
+
inputs["input_ids"][i] = prefix_tokens + ids + suffix_tokens
|
| 66 |
+
inputs = tokenizer.pad(
|
| 67 |
+
inputs, padding=True, return_tensors="pt", max_length=MAX_LENGTH
|
| 68 |
+
)
|
| 69 |
+
return {k: v.to(model.device) for k, v in inputs.items()}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@torch.no_grad()
|
| 73 |
+
def _score(pairs):
|
| 74 |
+
inputs = _tokenize(pairs)
|
| 75 |
+
logits = model(**inputs).logits[:, -1, :]
|
| 76 |
+
two = torch.stack(
|
| 77 |
+
[logits[:, token_false_id], logits[:, token_true_id]], dim=1
|
| 78 |
+
)
|
| 79 |
+
probs = torch.nn.functional.log_softmax(two, dim=1)[:, 1].exp()
|
| 80 |
+
return probs.float().cpu().tolist()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def score_docs(query, doc_texts, instruction, progress=None):
|
| 84 |
+
"""Return a relevance score (0..1) for every document, in original order."""
|
| 85 |
+
pairs = [_format(query, d, instruction) for d in doc_texts]
|
| 86 |
+
|
| 87 |
+
# Sort by length so each batch has similar-length items (less padding waste)
|
| 88 |
+
order = sorted(range(len(pairs)), key=lambda i: len(pairs[i]))
|
| 89 |
+
scores = [0.0] * len(pairs)
|
| 90 |
+
|
| 91 |
+
for start in range(0, len(order), BATCH_SIZE):
|
| 92 |
+
idx = order[start:start + BATCH_SIZE]
|
| 93 |
+
batch_scores = _score([pairs[i] for i in idx])
|
| 94 |
+
for i, s in zip(idx, batch_scores):
|
| 95 |
+
scores[i] = s
|
| 96 |
+
if progress is not None:
|
| 97 |
+
progress(min(start + BATCH_SIZE, len(order)) / len(order),
|
| 98 |
+
desc="Reranking")
|
| 99 |
+
return scores
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# ----------------------------------------------------------------------
|
| 103 |
+
# PDF handling: first NUM_PAGES pages only
|
| 104 |
+
# ----------------------------------------------------------------------
|
| 105 |
+
def extract_first_pages(pdf_path, num_pages=NUM_PAGES):
|
| 106 |
+
doc = fitz.open(pdf_path)
|
| 107 |
+
try:
|
| 108 |
+
parts = []
|
| 109 |
+
for i in range(min(num_pages, doc.page_count)):
|
| 110 |
+
parts.append(doc[i].get_text("text"))
|
| 111 |
+
return " ".join(" ".join(parts).split()) # clean whitespace
|
| 112 |
+
finally:
|
| 113 |
+
doc.close()
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# ----------------------------------------------------------------------
|
| 117 |
+
# Gradio callback
|
| 118 |
+
# ----------------------------------------------------------------------
|
| 119 |
+
def run_rerank(files, query, top_n, instruction, progress=gr.Progress()):
|
| 120 |
+
if not files:
|
| 121 |
+
raise gr.Error("Please upload at least one PDF.")
|
| 122 |
+
if not query or not query.strip():
|
| 123 |
+
raise gr.Error("Please enter a query.")
|
| 124 |
+
|
| 125 |
+
instruction = (instruction or "").strip() or DEFAULT_INSTRUCTION
|
| 126 |
+
|
| 127 |
+
docs, skipped = [], []
|
| 128 |
+
for f in files:
|
| 129 |
+
path = f if isinstance(f, str) else f.name # handles old/new Gradio
|
| 130 |
+
name = path.replace("\\", "/").split("/")[-1]
|
| 131 |
+
text = extract_first_pages(path)
|
| 132 |
+
if text:
|
| 133 |
+
docs.append({"file": name, "text": text})
|
| 134 |
+
else:
|
| 135 |
+
skipped.append(name)
|
| 136 |
+
|
| 137 |
+
if not docs:
|
| 138 |
+
raise gr.Error(
|
| 139 |
+
f"No text found in the first {NUM_PAGES} pages. These may be scanned PDFs "
|
| 140 |
+
"(images) - they need OCR first."
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
scores = score_docs(
|
| 144 |
+
query.strip(), [d["text"] for d in docs], instruction, progress
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
ranked = sorted(zip(docs, scores), key=lambda x: x[1], reverse=True)
|
| 148 |
+
ranked = ranked[: int(top_n)]
|
| 149 |
+
|
| 150 |
+
rows = [
|
| 151 |
+
[rank, round(score, 4), d["file"],
|
| 152 |
+
d["text"][:400] + ("..." if len(d["text"]) > 400 else "")]
|
| 153 |
+
for rank, (d, score) in enumerate(ranked, start=1)
|
| 154 |
+
]
|
| 155 |
+
|
| 156 |
+
status = f"Reranked {len(docs)} PDF(s) using their first {NUM_PAGES} pages."
|
| 157 |
+
if skipped:
|
| 158 |
+
status += f" Skipped (no text found): {', '.join(skipped)}"
|
| 159 |
+
return rows, status
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
# ----------------------------------------------------------------------
|
| 163 |
+
# UI
|
| 164 |
+
# ----------------------------------------------------------------------
|
| 165 |
+
with gr.Blocks(title="Qwen3 PDF Reranker") as demo:
|
| 166 |
+
gr.Markdown("# PDF Reranker (Qwen3-Reranker, 4-bit)\n"
|
| 167 |
+
"Upload PDFs and type a query. PDFs are ranked by relevance "
|
| 168 |
+
f"using only their **first {NUM_PAGES} pages**.")
|
| 169 |
+
|
| 170 |
+
with gr.Row():
|
| 171 |
+
with gr.Column():
|
| 172 |
+
files = gr.File(
|
| 173 |
+
label="Upload PDFs",
|
| 174 |
+
file_count="multiple",
|
| 175 |
+
file_types=[".pdf"],
|
| 176 |
+
)
|
| 177 |
+
query = gr.Textbox(label="Query", lines=2,
|
| 178 |
+
placeholder="What do you want to find?")
|
| 179 |
+
top_n = gr.Slider(1, 50, value=10, step=1, label="Top N results")
|
| 180 |
+
with gr.Accordion("Advanced", open=False):
|
| 181 |
+
instruction = gr.Textbox(
|
| 182 |
+
label="Task instruction",
|
| 183 |
+
value=DEFAULT_INSTRUCTION,
|
| 184 |
+
lines=2,
|
| 185 |
+
)
|
| 186 |
+
btn = gr.Button("Rerank", variant="primary")
|
| 187 |
+
|
| 188 |
+
with gr.Column():
|
| 189 |
+
status = gr.Markdown()
|
| 190 |
+
out = gr.Dataframe(
|
| 191 |
+
headers=["Rank", "Score", "File", "Text preview"],
|
| 192 |
+
datatype=["number", "number", "str", "str"],
|
| 193 |
+
wrap=True,
|
| 194 |
+
interactive=False,
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
btn.click(
|
| 198 |
+
run_rerank,
|
| 199 |
+
inputs=[files, query, top_n, instruction],
|
| 200 |
+
outputs=[out, status],
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
if __name__ == "__main__":
|
| 204 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
transformers>=4.51
|
| 3 |
+
accelerate
|
| 4 |
+
bitsandbytes
|
| 5 |
+
gradio
|
| 6 |
+
pymupdf
|