aikacl commited on
Commit
48dfdaf
·
verified ·
1 Parent(s): bfa3971

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -62
app.py CHANGED
@@ -1,30 +1,26 @@
1
  import spaces
2
  import os
3
  from typing import List
4
-
5
  import gradio as gr
6
-
7
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
8
-
9
  from kalm_reranker import KaLMReranker
10
-
11
-
12
  MODEL_ID = "KaLM-Embedding/KaLM-Reranker-V1-Nano"
13
-
14
  DEFAULT_INSTRUCTION = "Given a query, retrieve documents that answer the query."
15
-
16
  MAX_DOCS = 20
17
  MAX_DOC_CHARS = 4000
18
-
19
-
20
- def load_model():
21
- """
22
- Load KaLM-Reranker once when the Space starts.
23
-
24
- device=None and dtype=None allow the official wrapper to choose:
25
- - BF16 on CUDA
26
- - FP32 on CPU
27
- """
 
28
  reranker = KaLMReranker(
29
  MODEL_ID,
30
  device=None,
@@ -34,78 +30,49 @@ def load_model():
34
  max_length=1024,
35
  chunk_size=4,
36
  )
37
- return reranker
38
-
39
-
40
- reranker = load_model()
41
-
42
-
43
- def parse_documents(text: str) -> List[str]:
44
- """
45
- Split documents by blank lines.
46
- Each candidate document should be separated by one empty line.
47
- """
48
- docs = [doc.strip() for doc in text.split("\n\n") if doc.strip()]
49
- docs = docs[:MAX_DOCS]
50
- docs = [doc[:MAX_DOC_CHARS] for doc in docs]
51
- return docs
52
-
53
-
54
- def rerank(query: str, documents: str, instruction: str):
55
  query = query.strip()
56
  instruction = instruction.strip() or DEFAULT_INSTRUCTION
57
  docs = parse_documents(documents)
58
-
59
  if not query:
60
  return [], "Please input a query."
61
-
62
  if not docs:
63
  return [], "Please input at least one candidate document."
64
-
65
  try:
66
  rankings = reranker.rank(
67
  query=query,
68
  documents=docs,
69
  instruction=instruction,
70
  )
71
-
72
  table = []
73
  for rank_idx, item in enumerate(rankings, start=1):
74
  corpus_id = item["corpus_id"]
75
  score = float(item["score"])
76
  doc = docs[corpus_id]
77
- table.append(
78
- [
79
- rank_idx,
80
- corpus_id,
81
- round(score, 6),
82
- doc,
83
- ]
84
- )
85
-
86
  summary = (
87
  f"Reranked {len(docs)} documents with "
88
  f"`{MODEL_ID}`. Higher score means more relevant."
89
  )
90
  return table, summary
91
-
92
  except Exception as error:
93
  return [], f"Error during reranking: {repr(error)}"
94
-
95
-
96
  with gr.Blocks(title="KaLM-Reranker-V1 Demo") as demo:
97
  gr.Markdown(
98
  """
99
  # KaLM-Reranker-V1 Demo
100
-
101
  **KaLM-Reranker-V1** is a fast but not late-interaction reranker for compressed document reranking.
102
-
103
  Input a query and several candidate documents. The demo returns relevance scores and reranked results.
104
-
105
  **Document format:** separate candidate documents with one blank line.
106
  """
107
  )
108
-
109
  with gr.Row():
110
  with gr.Column(scale=1):
111
  query = gr.Textbox(
@@ -113,13 +80,11 @@ Input a query and several candidate documents. The demo returns relevance scores
113
  value="What is the capital of China?",
114
  lines=3,
115
  )
116
-
117
  instruction = gr.Textbox(
118
  label="Instruction",
119
  value=DEFAULT_INSTRUCTION,
120
  lines=2,
121
  )
122
-
123
  documents = gr.Textbox(
124
  label="Candidate Documents",
125
  value=(
@@ -130,9 +95,8 @@ Input a query and several candidate documents. The demo returns relevance scores
130
  ),
131
  lines=14,
132
  )
133
-
134
  submit = gr.Button("Rerank", variant="primary")
135
-
136
  with gr.Column(scale=1):
137
  output_table = gr.Dataframe(
138
  headers=["Rank", "Corpus ID", "Score", "Document"],
@@ -140,13 +104,13 @@ Input a query and several candidate documents. The demo returns relevance scores
140
  wrap=True,
141
  )
142
  output_summary = gr.Markdown()
143
-
144
  submit.click(
145
  fn=rerank,
146
  inputs=[query, documents, instruction],
147
  outputs=[output_table, output_summary],
148
  )
149
-
150
  gr.Examples(
151
  examples=[
152
  [
@@ -179,7 +143,7 @@ Input a query and several candidate documents. The demo returns relevance scores
179
  ],
180
  inputs=[query, documents, instruction],
181
  )
182
-
183
  gr.Markdown(
184
  """
185
  ## Citation
 
1
  import spaces
2
  import os
3
  from typing import List
 
4
  import gradio as gr
5
+
6
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
 
7
  from kalm_reranker import KaLMReranker
8
+
 
9
  MODEL_ID = "KaLM-Embedding/KaLM-Reranker-V1-Nano"
 
10
  DEFAULT_INSTRUCTION = "Given a query, retrieve documents that answer the query."
 
11
  MAX_DOCS = 20
12
  MAX_DOC_CHARS = 4000
13
+
14
+
15
+ def parse_documents(text: str) -> List[str]:
16
+ docs = [doc.strip() for doc in text.split("\n\n") if doc.strip()]
17
+ docs = docs[:MAX_DOCS]
18
+ docs = [doc[:MAX_DOC_CHARS] for doc in docs]
19
+ return docs
20
+
21
+
22
+ @spaces.GPU
23
+ def rerank(query: str, documents: str, instruction: str):
24
  reranker = KaLMReranker(
25
  MODEL_ID,
26
  device=None,
 
30
  max_length=1024,
31
  chunk_size=4,
32
  )
33
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  query = query.strip()
35
  instruction = instruction.strip() or DEFAULT_INSTRUCTION
36
  docs = parse_documents(documents)
37
+
38
  if not query:
39
  return [], "Please input a query."
 
40
  if not docs:
41
  return [], "Please input at least one candidate document."
42
+
43
  try:
44
  rankings = reranker.rank(
45
  query=query,
46
  documents=docs,
47
  instruction=instruction,
48
  )
49
+
50
  table = []
51
  for rank_idx, item in enumerate(rankings, start=1):
52
  corpus_id = item["corpus_id"]
53
  score = float(item["score"])
54
  doc = docs[corpus_id]
55
+ table.append([rank_idx, corpus_id, round(score, 6), doc])
56
+
 
 
 
 
 
 
 
57
  summary = (
58
  f"Reranked {len(docs)} documents with "
59
  f"`{MODEL_ID}`. Higher score means more relevant."
60
  )
61
  return table, summary
 
62
  except Exception as error:
63
  return [], f"Error during reranking: {repr(error)}"
64
+
65
+
66
  with gr.Blocks(title="KaLM-Reranker-V1 Demo") as demo:
67
  gr.Markdown(
68
  """
69
  # KaLM-Reranker-V1 Demo
 
70
  **KaLM-Reranker-V1** is a fast but not late-interaction reranker for compressed document reranking.
 
71
  Input a query and several candidate documents. The demo returns relevance scores and reranked results.
 
72
  **Document format:** separate candidate documents with one blank line.
73
  """
74
  )
75
+
76
  with gr.Row():
77
  with gr.Column(scale=1):
78
  query = gr.Textbox(
 
80
  value="What is the capital of China?",
81
  lines=3,
82
  )
 
83
  instruction = gr.Textbox(
84
  label="Instruction",
85
  value=DEFAULT_INSTRUCTION,
86
  lines=2,
87
  )
 
88
  documents = gr.Textbox(
89
  label="Candidate Documents",
90
  value=(
 
95
  ),
96
  lines=14,
97
  )
 
98
  submit = gr.Button("Rerank", variant="primary")
99
+
100
  with gr.Column(scale=1):
101
  output_table = gr.Dataframe(
102
  headers=["Rank", "Corpus ID", "Score", "Document"],
 
104
  wrap=True,
105
  )
106
  output_summary = gr.Markdown()
107
+
108
  submit.click(
109
  fn=rerank,
110
  inputs=[query, documents, instruction],
111
  outputs=[output_table, output_summary],
112
  )
113
+
114
  gr.Examples(
115
  examples=[
116
  [
 
143
  ],
144
  inputs=[query, documents, instruction],
145
  )
146
+
147
  gr.Markdown(
148
  """
149
  ## Citation