File size: 1,964 Bytes
bbd081e
 
 
 
6303e05
 
 
 
 
 
 
 
 
 
 
bbd081e
 
 
6303e05
bbd081e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6303e05
 
bbd081e
 
 
 
 
 
 
 
 
 
6303e05
bbd081e
 
6303e05
bbd081e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
import streamlit as st


ENV = "staging"

if ENV == "dev":
    AUTOCOMPLETE_BASE_URL = "http://localhost:8000"
elif ENV == "staging":
    AUTOCOMPLETE_BASE_URL = "https://off:off@search.openfoodfacts.net"
else:
    AUTOCOMPLETE_BASE_URL = "https://search.openfoodfacts.org"

AUTOCOMPLETE_URL = f"{AUTOCOMPLETE_BASE_URL}/autocomplete"

@st.cache_data
def send_autocomplete_request(q: str, lang: str, taxonomy_names: list[str], size: int):
    return requests.get(
        AUTOCOMPLETE_URL,
        params={
            "q": q,
            "lang": lang,
            "taxonomy_names": ",".join(taxonomy_names),
            "size": size,
        },
    ).json()


def run(
    query: str,
    taxonomy_names: list[str],
    lang: str,
    size: int,
):
    response = send_autocomplete_request(query, lang, taxonomy_names, size)
    took = response["took"]
    timed_out = response["timed_out"]

    st.markdown("---")
    st.markdown(f"Took: {took} ms")

    if timed_out:
        st.warning("Request timed out!")

    options = response["options"]
    options = [
        {"text": o["text"], "id": o["id"], "taxonomy": o["taxonomy_name"]}
        for o in options
    ]
    st.markdown("### Results")
    st.table(options)

    st.markdown("### Debug information")
    st.write(response["debug"])


st.title("Search autocomplete demo")
st.markdown(
    "This is a demo of the search autocomplete feature, that searches in the taxonomy names and synonyms."
)
query = st.text_input("query", help="Query to search for", value="chocolate").strip()
taxonomy_names = st.multiselect(
    "taxonomy names",
    ["category", "label", "ingredient", "allergen", "brand"],
    default=["category", "label", "ingredient", "brand"],
)
lang = st.selectbox("language", ["en", "fr", "it", "es", "nl", "de"], index=0)
size = st.number_input(
    "number of results", value=10, min_value=1, max_value=500, step=1
)

if query:
    run(query, taxonomy_names, lang, size)