Raphaël Bournhonesque commited on
Commit
bbd081e
·
1 Parent(s): ca0297e

first commit

Browse files
Files changed (1) hide show
  1. app.py +83 -0
app.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import streamlit as st
3
+ from annotated_text import annotated_text
4
+
5
+
6
+ @st.cache_data
7
+ def send_autocomplete_request(q: str, lang: str, taxonomy_names: list[str], size: int):
8
+ return requests.get(
9
+ "http://localhost:8000/autocomplete",
10
+ params={
11
+ "q": q,
12
+ "lang": lang,
13
+ "taxonomy_names": ",".join(taxonomy_names),
14
+ "size": size,
15
+ },
16
+ ).json()
17
+
18
+
19
+ def get_product(barcode: str):
20
+ r = requests.get(f"https://world.openfoodfacts.org/api/v2/product/{barcode}")
21
+
22
+ if r.status_code == 404:
23
+ return None
24
+
25
+ return r.json()["product"]
26
+
27
+
28
+ def display_ner_tags(text: str, entities: list[dict]):
29
+ spans = []
30
+ previous_idx = 0
31
+ for entity in entities:
32
+ score = entity["score"]
33
+ lang = entity["lang"]["lang"]
34
+ start_idx = entity["start"]
35
+ end_idx = entity["end"]
36
+ spans.append(text[previous_idx:start_idx])
37
+ spans.append((text[start_idx:end_idx], f"score={score:.3f} | lang={lang}"))
38
+ previous_idx = end_idx
39
+ spans.append(text[previous_idx:])
40
+ annotated_text(spans)
41
+
42
+
43
+ def run(
44
+ query: str,
45
+ taxonomy_names: list[str],
46
+ lang: str,
47
+ size: int,
48
+ ):
49
+ response = send_autocomplete_request(query, lang, taxonomy_names, size)
50
+ took = response["took"]
51
+ timed_out = response["timed_out"]
52
+ st.markdown(f"Took: {took} ms")
53
+
54
+ if timed_out:
55
+ st.warning("Request timed out!")
56
+
57
+ options = response["options"]
58
+ options = [
59
+ {"text": o["text"], "id": o["id"], "taxonomy": o["taxonomy_name"]}
60
+ for o in options
61
+ ]
62
+ st.table(options)
63
+
64
+ st.write(response["debug"])
65
+
66
+
67
+ st.title("Search autocomplete demo")
68
+ st.markdown(
69
+ "This is a demo of the search autocomplete feature, that searches in the taxonomy names and synonyms."
70
+ )
71
+ query = st.text_input("query", help="Query to search for", value="chocolate").strip()
72
+ taxonomy_names = st.multiselect(
73
+ "taxonomy names",
74
+ ["category", "label", "ingredient", "allergen", "brand"],
75
+ default=["category", "label", "ingredient", "brand"],
76
+ )
77
+ lang = st.selectbox("language", ["en", "fr", "it", "es", "nl", "de"], index=0)
78
+ size = st.number_input(
79
+ "number of results", value=10, min_value=1, max_value=500, step=1
80
+ )
81
+
82
+ if query:
83
+ run(query, taxonomy_names, lang, size)