File size: 2,245 Bytes
15b0ad3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aeede6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15b0ad3
 
 
 
 
 
 
 
 
 
 
 
 
aeede6a
15b0ad3
 
 
 
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
import sys
import os
import gradio as gr
import requests
from config import BACKEND_HOST, BACKEND_PORT, FRONTEND_PORT, APP_NAME


# Add the project root directory to the Python path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
API_URL = f"http://{BACKEND_HOST}:{BACKEND_PORT}/search"


def search_prompt(query: str, n: int) -> list:
    """
    Query the backend search API and format the results.
    Args:
        query: The search query.
        n: The number of results to return.
    Returns:
        list: A list of formatted results, or an error message
    """
    try:
        response = requests.get(API_URL, params={"query": query, "n": n})
        response.raise_for_status()
        data = response.json()

        # Extract and sort results
        results = data["results"]
        sorted_results = sorted(results, key=lambda x: x[0], reverse=True)

        # Format results in a table
        tabular_results = [[result[1], f"{result[0]:.4f}"] for result in sorted_results]
        return tabular_results

    except Exception as e:
        return [["Error", str(e)]]


def validate_and_search(query: str, n: int) -> list:
    """
    Validate inputs and perform the search if inputs are valid.
    Args:
        query: The search query.
        n: The number of results to return.
    Returns:
        list: A list of results or an error message.
    """
    if not query.strip():
        return [["Error", "Your input is empty, please enter a query."]]
    if n <= 0 or not isinstance(n, int):
        return [["Error", "Invalid number of top results. Please enter a positive number."]]
    # Call the backend search function
    return search_prompt(query, n)

with gr.Blocks() as demo:
    gr.Markdown(f"# {APP_NAME}")

    query = gr.Textbox(label="Enter your query:")
    n = gr.Number(label="Number of top results", value=5, precision=0)
    output = gr.Dataframe(
        headers=["Prompt", "Similarity"],
        datatype=["str", "str"],
        interactive=False,
        label=f"Top results"
    )

    search_button = gr.Button("Search")
    search_button.click(validate_and_search, inputs=[query, n], outputs=[output])


demo.launch(server_name="0.0.0.0", server_port=FRONTEND_PORT)