File size: 10,436 Bytes
53afb32 |
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 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 |
import gradio as gr
import random
import time
from utils import load_model_util, load_corpus_util, build_index_util, search_util
model = None
corpus = None
faiss_index = None
data_dir = '/share/chaofan/code/bge_demo/data'
index_dir = '/share/chaofan/code/bge_demo/emb'
lang = 'en'
avaliable_queries = []
# Simulate loading a model
def load_model(model_name):
global model
"""
Function to load a model and provide status updates with a custom loading type.
"""
# 定义 HTML 样式
loading_style = "<span style='color:#ffc107; font-weight:bold'>⏳</span>" # 自定义加载中图标
success_style = "<span style='color:#28a745; font-weight:bold'>✔</span>" # 成功图标
error_style = "<span style='color:#dc3545; font-weight:bold'>✗</span>" # 错误图标
try:
yield f"{loading_style} Loading model <b>{model_name}</b>..."
model = load_model_util(model, model_name)
yield f"{success_style} Model <b>{model_name}</b> has been successfully loaded!"
except Exception as e:
yield f"{error_style} Failed to load model <b>{model_name}</b>: {str(e)}"
# Simulate selecting a language
def choose_language(language):
global lang
lang = language
language_full = {
"zh": "Chinese",
"en": "English",
"ar": "Arabic",
"bn": "Bengali",
"es": "Spanish",
"fa": "Persian",
"fi": "Finnish",
"fr": "French",
"hi": "Hindi",
"id": "Indonesian",
"ja": "Japanese",
"ko": "Korean",
"ru": "Russian",
"sw": "Swahili",
"te": "Telugu",
"th": "Thai",
"de": "German",
"yo": "Yoruba"
}.get(language, language)
return f"<span style='color:#0d6efd; font-weight:bold'>⚡</span> Current Language: <b>{language_full}</b> ({language})"
# Simulate loading a corpus
def load_corpus(language):
global data_dir, corpus, avaliable_queries
# Initial loading status
corpus_name = f"miracl.{language}"
yield f"""<span style='color:#ffc107; font-weight:bold'>⏳</span> Loading corpus <b>{corpus_name}</b> ..."""
# Simulate loading process
print(f"Loading corpus: {corpus_name}")
corpus, avaliable_queries = load_corpus_util(data_dir, language)
yield f"""<span style='color:#28a745; font-weight:bold'>✔</span> Corpus <b>{corpus_name}</b> has been successfully loaded!"""
def update_query_input(value):
global avaliable_queries
return gr.Dropdown(
label="Search Query",
choices=avaliable_queries, # 预定义的选项
value="", # 默认值
allow_custom_value=True, # 允许用户输入自定义值
# placeholder="Select or enter search keywords..."
)
# Simulate building an index
def build_index(language):
# Simulate progressive building process
global model, corpus, index_dir, faiss_index, lang
# 定义 HTML 样式
loading_style = "<span style='color:#ffc107; font-weight:bold'>⏳</span>" # 自定义加载中图标
success_style = "<span style='color:#28a745; font-weight:bold'>✔</span>" # 成功图标
error_style = "<span style='color:#dc3545; font-weight:bold'>✗</span>" # 错误图标
if model is None:
yield f"{error_style} You need to load the model before building index!"
elif corpus is None:
yield f"{error_style} You need to load the corpus before building index!"
else:
try:
yield f"{loading_style} Building index..."
faiss_index = build_index_util(index_dir, lang, model, corpus)
yield f"{success_style} Index building complete!"
except Exception as e:
yield f"{error_style} Failed to build index: {str(e)}"
# Simulate retrieving results
def retrieve_results(query, language, top_k):
global model, corpus, faiss_index
yield f"""<div style='background:#f8f9fa; padding:10px; border-left:4px solid #17a2b8; border-radius:4px'>
<span style='color:orange'>⏳ Start to search ...</span>
</div>"""
error_style = "<span style='color:#dc3545; font-weight:bold'>✗</span>" # 错误图标
try:
scores, data = search_util(model, query, corpus, faiss_index, top_k)
# print(scores)
# print(data)
# Generate random results
results = []
for score, d in zip(scores, data):
doc_id = d['id']
title = d['title']
content = d['text']
results.append((float(score), doc_id, title, content))
# # Sort by score
# results.sort(reverse=True)
# Generate HTML display
html_result = f"""<div style='background:#f8f9fa; padding:15px; border-radius:8px'>
<h3>Search Results: <span style='color:#0d6efd'>{top_k}</span> items</h3>
<p>Query: <b>"{query}"</b> | Language: <b>{language}</b></p>
<div style='margin-top:15px'>"""
for i, (score, doc_id, title, content) in enumerate(results):
# Set gradient color
color = f"hsl({min(120, int(score*120))}, 80%, 40%)"
html_result += f"""<div style='margin-bottom:5px; padding:10px; border-left:4px solid {color}; background:white; border-radius:4px'>
<div style='display:flex; justify-content:space-between'>
<span style='font-weight:bold'>Result {i+1}</span>
</div>
<div style='color:#666; font-size:1.0em'>Title: {title}</div>
<div style='margin-top:5px'>{content}</div>
</div>"""
html_result += "</div></div>"
yield html_result
except Exception as e:
yield f"{error_style} Failed to build index: {str(e)}"
# Custom CSS
custom_css = """
.main-header {
background: linear-gradient(135deg, #6964DE, #FCA6E9);
color: white;
padding: 20px;
border-radius: 10px;
margin-bottom: 20px;
text-align: center;
}
.step-header {
color: #333;
margin-top: 5px;
margin-bottom: 10px;
font-weight: bold;
display: flex;
align-items: center;
justify-content: center;
}
.step-header span {
background: #6964DE;
color: white;
width: 28px;
height: 28px;
border-radius: 50%;
display: inline-flex;
align-items: center;
justify-content: center;
margin-right: 10px;
}
.step-card {
background: white;
border-radius: 10px;
padding: 15px;
margin-bottom: 15px;
box-shadow: 0 4px 6px rgba(0,0,0,0.05);
text-align: center;
}
button {
background-color: #0d6efd !important;
color: white !important;
border: none !important;
padding: 5px 15px !important; /* Adjust button size */
border-radius: 5px !important;
font-size: 0.9em !important; /* Adjust font size */
cursor: pointer !important;
}
button:hover {
background-color: #0056b3 !important;
}
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px; /* Control spacing between components */
}
footer {visibility: hidden}
"""
# Define Gradio interface
with gr.Blocks(css=custom_css) as interface:
# Top header
gr.HTML("""
<div class="main-header">
<h1 style="margin:0; font-size:2.5em;">🔎 Multilingual Retrieval System</h1>
</div>
""")
with gr.Row(elem_classes="row"): # Use Row to place components in the same row
# Step 1: Load model
with gr.Group(elem_classes="step-card"):
gr.HTML('<div class="step-header"><span>1</span>Load Model</div>')
model_name = gr.Textbox(value="BAAI/bge-multilingual-gemma2", label="Model Name", interactive=True)
load_model_button = gr.Button("Load Model")
model_status = gr.HTML(label="Status")
load_model_button.click(load_model, inputs=[model_name], outputs=[model_status])
# Step 2: Select language
with gr.Group(elem_classes="step-card"):
gr.HTML('<div class="step-header"><span>2</span>Select Language</div>')
language_input = gr.Dropdown(choices=['en', 'zh', 'ar', 'bn', 'es', 'fa', 'fi', 'fr', 'hi', 'id', 'ja', 'ko', 'ru', 'sw', 'te', 'th', 'de', 'yo'], value="en", label="Select Language", interactive=True)
choose_language_button = gr.Button("Confirm Language") # Button in the same row
language_status = gr.HTML(label="Current Language")
choose_language_button.click(choose_language, inputs=[language_input], outputs=[language_status])
with gr.Row(elem_classes="row"): # Use Row to place components in the same row
# Step 3: Load corpus
with gr.Group(elem_classes="step-card"):
gr.HTML('<div class="step-header"><span>3</span>Load Corpus</div>')
load_corpus_button = gr.Button("Load Corpus", scale=1)
corpus_status = gr.HTML(label="Corpus Information")
# Step 4: Build index
with gr.Group(elem_classes="step-card"):
gr.HTML('<div class="step-header"><span>4</span>Build Corpus Index</div>')
build_index_button = gr.Button("Build Index", scale=1)
index_status = gr.HTML(label="Index Status")
build_index_button.click(build_index, inputs=[language_input], outputs=[index_status])
# Step 5: Retrieve results
with gr.Group(elem_classes="step-card"):
gr.HTML('<div class="step-header"><span>5</span>Retrieve Results</div>')
# query_input = gr.Textbox(label="Search Query", placeholder="Enter search keywords...")
query_input = gr.Dropdown(
label="Search Query",
choices=avaliable_queries, # 预定义的选项
value="", # 默认值
allow_custom_value=True, # 允许用户输入自定义值
# placeholder="Select or enter search keywords..."
)
load_corpus_button.click(load_corpus, inputs=[language_input], outputs=[corpus_status]).then(update_query_input, inputs=[query_input], outputs=[query_input]) # 因为要让选项变化
top_k = gr.Slider(minimum=1, maximum=30, step=1, value=10, label="Number of Results (Top-K)")
retrieve_button = gr.Button("Start Search")
retrieval_results = gr.HTML(label="Search Results")
retrieve_button.click(retrieve_results, inputs=[query_input, language_input, top_k], outputs=[retrieval_results])
# Launch the interface
interface.launch(share=True)
|