File size: 7,662 Bytes
15e5a73 f3a85dd 15e5a73 f3a85dd 15e5a73 f3a85dd 4abdef5 f3a85dd 70385d3 15e5a73 f3a85dd 15e5a73 f3a85dd 15e5a73 f3a85dd 15e5a73 f3a85dd 15e5a73 f3a85dd 15e5a73 f3a85dd 15e5a73 f3a85dd 15e5a73 f3a85dd 15e5a73 f3a85dd 15e5a73 f3a85dd | 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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | import pymupdf # PyMuPDF (replaces the deprecated `import fitz`)
import gradio as gr
import spaces # Hugging Face ZeroGPU
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
# ----------------------------------------------------------------------
# Config
# ----------------------------------------------------------------------
MODEL_ID = "Qwen/Qwen3-Reranker-8B" # or "Qwen/Qwen3-Reranker-0.6B" / "-8B"
NUM_PAGES = 2 # how many pages from the start of each PDF to use
MAX_LENGTH = 8192 # max tokens per (query + pages) pair
BATCH_SIZE = 4 # ZeroGPU gives a big GPU; lower if you hit OOM
GPU_DURATION = 120 # max seconds of GPU time per click
DEFAULT_INSTRUCTION = (
"Given a web search query, retrieve relevant passages that answer the query"
)
# ----------------------------------------------------------------------
# Load model once at startup.
# On ZeroGPU, calling .to("cuda") at module level is the supported pattern:
# the real GPU is only attached while a @spaces.GPU function is running.
# (bitsandbytes 4-bit is not reliable on ZeroGPU, so we use fp16 instead;
# a 4B model is ~8 GB in fp16, which fits easily.)
# ----------------------------------------------------------------------
print(f"Loading {MODEL_ID} in fp16 ...")
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, padding_side="left")
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
torch_dtype=torch.float16,
)
model.to("cuda")
model.eval()
print("Model loaded.")
token_true_id = tokenizer.convert_tokens_to_ids("yes")
token_false_id = tokenizer.convert_tokens_to_ids("no")
prefix = (
"<|im_start|>system\nJudge whether the Document meets the requirements based on "
"the Query and the Instruct provided. Note that the answer can only be "
'"yes" or "no".<|im_end|>\n<|im_start|>user\n'
)
suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
prefix_tokens = tokenizer.encode(prefix, add_special_tokens=False)
suffix_tokens = tokenizer.encode(suffix, add_special_tokens=False)
# ----------------------------------------------------------------------
# Reranker functions
# ----------------------------------------------------------------------
def _format(query, doc, instruction):
return f"<Instruct>: {instruction}\n<Query>: {query}\n<Document>: {doc}"
def _tokenize(pairs):
inputs = tokenizer(
pairs,
padding=False,
truncation="longest_first",
return_attention_mask=False,
max_length=MAX_LENGTH - len(prefix_tokens) - len(suffix_tokens),
)
for i, ids in enumerate(inputs["input_ids"]):
inputs["input_ids"][i] = prefix_tokens + ids + suffix_tokens
inputs = tokenizer.pad(
inputs, padding=True, return_tensors="pt", max_length=MAX_LENGTH
)
return {k: v.to(model.device) for k, v in inputs.items()}
@torch.no_grad()
def _score(pairs):
inputs = _tokenize(pairs)
logits = model(**inputs).logits[:, -1, :]
two = torch.stack(
[logits[:, token_false_id], logits[:, token_true_id]], dim=1
)
probs = torch.nn.functional.log_softmax(two, dim=1)[:, 1].exp()
return probs.float().cpu().tolist()
@spaces.GPU(duration=GPU_DURATION)
def score_docs(query, doc_texts, instruction):
"""Return a relevance score (0..1) for every document, in original order.
This is the only function that touches the GPU, so it is the one
decorated with @spaces.GPU.
"""
pairs = [_format(query, d, instruction) for d in doc_texts]
# Sort by length so each batch has similar-length items (less padding waste)
order = sorted(range(len(pairs)), key=lambda i: len(pairs[i]))
scores = [0.0] * len(pairs)
for start in range(0, len(order), BATCH_SIZE):
idx = order[start:start + BATCH_SIZE]
batch_scores = _score([pairs[i] for i in idx])
for i, s in zip(idx, batch_scores):
scores[i] = s
return scores
# ----------------------------------------------------------------------
# PDF handling: first NUM_PAGES pages only (CPU work, outside the GPU call)
# ----------------------------------------------------------------------
def extract_first_pages(pdf_path, num_pages=NUM_PAGES):
doc = pymupdf.open(pdf_path)
try:
parts = []
for i in range(min(num_pages, doc.page_count)):
parts.append(doc[i].get_text("text"))
return " ".join(" ".join(parts).split()) # clean whitespace
finally:
doc.close()
# ----------------------------------------------------------------------
# Gradio callback
# ----------------------------------------------------------------------
def run_rerank(files, query, top_n, instruction):
if not files:
raise gr.Error("Please upload at least one PDF.")
if not query or not query.strip():
raise gr.Error("Please enter a query.")
instruction = (instruction or "").strip() or DEFAULT_INSTRUCTION
docs, skipped = [], []
for f in files:
path = f if isinstance(f, str) else f.name # handles old/new Gradio
name = path.replace("\\", "/").split("/")[-1]
text = extract_first_pages(path)
if text:
docs.append({"file": name, "text": text})
else:
skipped.append(name)
if not docs:
raise gr.Error(
f"No text found in the first {NUM_PAGES} pages. These may be scanned PDFs "
"(images) - they need OCR first."
)
scores = score_docs(query.strip(), [d["text"] for d in docs], instruction)
ranked = sorted(zip(docs, scores), key=lambda x: x[1], reverse=True)
ranked = ranked[: int(top_n)]
rows = [
[rank, round(score, 4), d["file"],
d["text"][:400] + ("..." if len(d["text"]) > 400 else "")]
for rank, (d, score) in enumerate(ranked, start=1)
]
status = f"Reranked {len(docs)} PDF(s) using their first {NUM_PAGES} pages."
if skipped:
status += f" Skipped (no text found): {', '.join(skipped)}"
return rows, status
# ----------------------------------------------------------------------
# UI
# ----------------------------------------------------------------------
with gr.Blocks(title="Qwen3 PDF Reranker") as demo:
gr.Markdown("# PDF Reranker (Qwen3-Reranker)\n"
"Upload PDFs and type a query. PDFs are ranked by relevance "
f"using only their **first {NUM_PAGES} pages**.")
with gr.Row():
with gr.Column():
files = gr.File(
label="Upload PDFs",
file_count="multiple",
file_types=[".pdf"],
)
query = gr.Textbox(label="Query", lines=2,
placeholder="What do you want to find?")
top_n = gr.Slider(1, 50, value=10, step=1, label="Top N results")
with gr.Accordion("Advanced", open=False):
instruction = gr.Textbox(
label="Task instruction",
value=DEFAULT_INSTRUCTION,
lines=2,
)
btn = gr.Button("Rerank", variant="primary")
with gr.Column():
status = gr.Markdown()
out = gr.Dataframe(
headers=["Rank", "Score", "File", "Text preview"],
datatype=["number", "number", "str", "str"],
wrap=True,
interactive=False,
)
btn.click(
run_rerank,
inputs=[files, query, top_n, instruction],
outputs=[out, status],
)
if __name__ == "__main__":
demo.launch() |