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 = "⏳" # 自定义加载中图标
success_style = "✔" # 成功图标
error_style = "✗" # 错误图标
try:
yield f"{loading_style} Loading model {model_name}..."
model = load_model_util(model, model_name)
yield f"{success_style} Model {model_name} has been successfully loaded!"
except Exception as e:
yield f"{error_style} Failed to load model {model_name}: {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"⚡ Current Language: {language_full} ({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"""⏳ Loading corpus {corpus_name} ..."""
# Simulate loading process
print(f"Loading corpus: {corpus_name}")
corpus, avaliable_queries = load_corpus_util(data_dir, language)
yield f"""✔ Corpus {corpus_name} 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 = "⏳" # 自定义加载中图标
success_style = "✔" # 成功图标
error_style = "✗" # 错误图标
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"""
⏳ Start to search ...
"""
error_style = "✗" # 错误图标
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"""
Search Results: {top_k} items
Query: "{query}" | Language: {language}
"""
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"""
Result {i+1}
Title: {title}
{content}
"""
html_result += "
"
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("""
🔎 Multilingual Retrieval System
""")
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('')
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('')
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('')
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('')
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('')
# 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)