awacke1 commited on
Commit
ce6a7eb
·
1 Parent(s): cb44f7e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +283 -0
app.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import http.client as http_client
2
+ import json
3
+ import logging
4
+ import os
5
+ import re
6
+ import string
7
+ import traceback
8
+
9
+ import gradio as gr
10
+ import requests
11
+ from huggingface_hub import HfApi
12
+
13
+ hf_api = HfApi()
14
+ roots_datasets = {dset.id.split("/")[-1]:dset for dset in hf_api.list_datasets(author="bigscience-data", use_auth_token=os.environ.get("bigscience_data_token"))}
15
+
16
+ def get_docid_html(docid):
17
+ data_org, dataset, docid = docid.split("/")
18
+ metadata = roots_datasets[dataset]
19
+ if metadata.private:
20
+ docid_html = (
21
+ f"<a "
22
+ f'class="underline-on-hover"'
23
+ f'title="This dataset is private. See the introductory text for more information"'
24
+ f'style="color:#AA4A44;"'
25
+ f'href="https://huggingface.co/datasets/bigscience-data/{dataset}"'
26
+ f'target="_blank"><b>🔒{dataset}</b></a><span style="color: #7978FF;">/{docid}</span>'
27
+ )
28
+ else:
29
+ docid_html = (
30
+ f"<a "
31
+ f'class="underline-on-hover"'
32
+ f'title="This dataset is licensed {metadata.tags[0].split(":")[-1]}"'
33
+ f'style="color:#2D31FA;"'
34
+ f'href="https://huggingface.co/datasets/bigscience-data/{dataset}"'
35
+ f'target="_blank"><b>{dataset}</b></a><span style="color: #7978FF;">/{docid}</span>'
36
+ )
37
+ return docid_html
38
+
39
+
40
+ PII_TAGS = {"KEY", "EMAIL", "USER", "IP_ADDRESS", "ID", "IPv4", "IPv6"}
41
+ PII_PREFIX = "PI:"
42
+
43
+
44
+ def process_pii(text):
45
+ for tag in PII_TAGS:
46
+ text = text.replace(
47
+ PII_PREFIX + tag,
48
+ """<b><mark style="background: Fuchsia; color: Lime;">REDACTED {}</mark></b>""".format(tag),
49
+ )
50
+ return text
51
+
52
+
53
+ def process_results(results, highlight_terms):
54
+ if len(results) == 0:
55
+ return """<br><p style='font-family: Arial; color:Silver; text-align: center;'>
56
+ No results retrieved.</p><br><hr>"""
57
+
58
+ results_html = ""
59
+ for result in results:
60
+ tokens = result["text"].split()
61
+ tokens_html = []
62
+ for token in tokens:
63
+ if token in highlight_terms:
64
+ tokens_html.append("<b>{}</b>".format(token))
65
+ else:
66
+ tokens_html.append(token)
67
+ tokens_html = " ".join(tokens_html)
68
+ tokens_html = process_pii(tokens_html)
69
+ meta_html = (
70
+ """
71
+ <p class='underline-on-hover' style='font-size:12px; font-family: Arial; color:#585858; text-align: left;'>
72
+ <a href='{}' target='_blank'>{}</a></p>""".format(
73
+ result["meta"]["url"], result["meta"]["url"]
74
+ )
75
+ if "meta" in result and result["meta"] is not None and "url" in result["meta"]
76
+ else ""
77
+ )
78
+ docid_html = get_docid_html(result["docid"])
79
+ results_html += """{}
80
+ <p style='font-size:14px; font-family: Arial; color:#7978FF; text-align: left;'>Document ID: {}</p>
81
+ <p style='font-size:12px; font-family: Arial; color:MediumAquaMarine'>Language: {}</p>
82
+ <p style='font-family: Arial;'>{}</p>
83
+ <br>
84
+ """.format(
85
+ meta_html, docid_html, result["lang"], tokens_html
86
+ )
87
+ return results_html + "<hr>"
88
+
89
+
90
+ def scisearch(query, language, num_results=10):
91
+ try:
92
+ query = " ".join(query.split())
93
+ if query == "" or query is None:
94
+ return ""
95
+
96
+ post_data = {"query": query, "k": num_results}
97
+ if language != "detect_language":
98
+ post_data["lang"] = language
99
+
100
+ output = requests.post(
101
+ os.environ.get("address"),
102
+ headers={"Content-type": "application/json"},
103
+ data=json.dumps(post_data),
104
+ timeout=60,
105
+ )
106
+
107
+ payload = json.loads(output.text)
108
+
109
+ if "err" in payload:
110
+ if payload["err"]["type"] == "unsupported_lang":
111
+ detected_lang = payload["err"]["meta"]["detected_lang"]
112
+ return f"""
113
+ <p style='font-size:18px; font-family: Arial; color:MediumVioletRed; text-align: center;'>
114
+ Detected language <b>{detected_lang}</b> is not supported.<br>
115
+ Please choose a language from the dropdown or type another query.
116
+ </p><br><hr><br>"""
117
+
118
+ results = payload["results"]
119
+ highlight_terms = payload["highlight_terms"]
120
+
121
+ if language == "detect_language":
122
+ results = list(results.values())[0]
123
+ return (
124
+ (
125
+ f"""<p style='font-family: Arial; color:MediumAquaMarine; text-align: center; line-height: 3em'>
126
+ Detected language: <b>{results[0]["lang"]}</b></p><br><hr><br>"""
127
+ if len(results) > 0 and language == "detect_language"
128
+ else ""
129
+ )
130
+ + process_results(results, highlight_terms)
131
+ )
132
+
133
+ if language == "all":
134
+ results_html = ""
135
+ for lang, results_for_lang in results.items():
136
+ if len(results_for_lang) == 0:
137
+ results_html += f"""<p style='font-family: Arial; color:Silver; text-align: left; line-height: 3em'>
138
+ No results for language: <b>{lang}</b><hr></p>"""
139
+ continue
140
+
141
+ collapsible_results = f"""
142
+ <details>
143
+ <summary style='font-family: Arial; color:MediumAquaMarine; text-align: left; line-height: 3em'>
144
+ Results for language: <b>{lang}</b><hr>
145
+ </summary>
146
+ {process_results(results_for_lang, highlight_terms)}
147
+ </details>"""
148
+ results_html += collapsible_results
149
+ return results_html
150
+
151
+ results = list(results.values())[0]
152
+ return process_results(results, highlight_terms)
153
+
154
+ except Exception as e:
155
+ results_html = f"""
156
+ <p style='font-size:18px; font-family: Arial; color:MediumVioletRed; text-align: center;'>
157
+ Raised {type(e).__name__}</p>
158
+ <p style='font-size:14px; font-family: Arial; '>
159
+ Check if a relevant discussion already exists in the Community tab. If not, please open a discussion.
160
+ </p>
161
+ """
162
+ print(e)
163
+ print(traceback.format_exc())
164
+
165
+ return results_html
166
+
167
+
168
+ def flag(query, language, num_results, issue_description):
169
+ try:
170
+ post_data = {"query": query, "k": num_results, "flag": True, "description": issue_description}
171
+ if language != "detect_language":
172
+ post_data["lang"] = language
173
+
174
+ output = requests.post(
175
+ os.environ.get("address"),
176
+ headers={"Content-type": "application/json"},
177
+ data=json.dumps(post_data),
178
+ timeout=120,
179
+ )
180
+
181
+ results = json.loads(output.text)
182
+ except:
183
+ print("Error flagging")
184
+ return ""
185
+
186
+
187
+ description = """# <p style="text-align: center;"> 🌸 🔎 Bloom Searcher 🔍 🌸 </p>
188
+ Tool design for Roots: [URL](https://huggingface.co/spaces/bigscience-data/scisearch/blob/main/roots_search_tool_specs.pdf).
189
+ Bloom on Wikipedia: [URL](https://en.wikipedia.org/wiki/BLOOM_(language_model)).
190
+ Bloom Video Playlist: [URL](https://www.youtube.com/playlist?list=PLHgX2IExbFouqnsIqziThlPCX_miiDq14).
191
+ Access full corpus check [URL](https://forms.gle/qyYswbEL5kA23Wu99).
192
+
193
+ Big Science - How to get started
194
+ Big Science is a 176B parameter new ML model that was trained on a set of datasets for Natural Language processing, and many other tasks that are not yet explored.. Below is the set of the papers, models, links, and datasets around big science which promises to be the best, most recent large model of its kind benefitting all science pursuits.
195
+
196
+ Model: https://huggingface.co/bigscience/bloom
197
+ Papers:
198
+ BLOOM: A 176B-Parameter Open-Access Multilingual Language Model https://arxiv.org/abs/2211.05100
199
+ Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism https://arxiv.org/abs/1909.08053
200
+ 8-bit Optimizers via Block-wise Quantization https://arxiv.org/abs/2110.02861
201
+ Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation https://arxiv.org/abs/2108.12409
202
+ https://huggingface.co/models?other=doi:10.57967/hf/0003
203
+ 217 Other Models optimizing use of bloom via specialization: https://huggingface.co/models?other=bloom
204
+ Datasets
205
+ Universal Dependencies: https://paperswithcode.com/dataset/universal-dependencies
206
+ WMT 2014: https://paperswithcode.com/dataset/wmt-2014
207
+ The Pile: https://paperswithcode.com/dataset/the-pile
208
+ HumanEval: https://paperswithcode.com/dataset/humaneval
209
+ FLORES-101: https://paperswithcode.com/dataset/flores-101
210
+ CrowS-Pairs: https://paperswithcode.com/dataset/crows-pairs
211
+ WikiLingua: https://paperswithcode.com/dataset/wikilingua
212
+ MTEB: https://paperswithcode.com/dataset/mteb
213
+ xP3: https://paperswithcode.com/dataset/xp3
214
+ DiaBLa: https://paperswithcode.com/dataset/diabla
215
+
216
+ """
217
+
218
+
219
+ if __name__ == "__main__":
220
+ demo = gr.Blocks(
221
+ css=".underline-on-hover:hover { text-decoration: underline; } .flagging { font-size:12px; color:Silver; }"
222
+ )
223
+
224
+ with demo:
225
+ with gr.Row():
226
+ gr.Markdown(value=description)
227
+ with gr.Row():
228
+ query = gr.Textbox(lines=1, max_lines=1, placeholder="Type your query here...", label="Query")
229
+ with gr.Row():
230
+ lang = gr.Dropdown(
231
+ choices=[
232
+ "ar",
233
+ "ca",
234
+ "code",
235
+ "en",
236
+ "es",
237
+ "eu",
238
+ "fr",
239
+ "id",
240
+ "indic",
241
+ "nigercongo",
242
+ "pt",
243
+ "vi",
244
+ "zh",
245
+ "detect_language",
246
+ "all",
247
+ ],
248
+ value="en",
249
+ label="Language",
250
+ )
251
+ with gr.Row():
252
+ k = gr.Slider(1, 100, value=10, step=1, label="Max Results")
253
+ with gr.Row():
254
+ submit_btn = gr.Button("Submit")
255
+ with gr.Row():
256
+ results = gr.HTML(label="Results")
257
+ flag_description = """
258
+ <p class='flagging'>
259
+ If you choose to flag your search, we will save the query, language and the number of results you requested.
260
+ Please consider adding any additional context in the box on the right.</p>"""
261
+ with gr.Column(visible=False) as flagging_form:
262
+ flag_txt = gr.Textbox(
263
+ lines=1,
264
+ placeholder="Type here...",
265
+ label="""If you choose to flag your search, we will save the query, language and the number of results
266
+ you requested. Please consider adding relevant additional context below:""",
267
+ )
268
+ flag_btn = gr.Button("Flag Results")
269
+ flag_btn.click(flag, inputs=[query, lang, k, flag_txt], outputs=[flag_txt])
270
+
271
+ def submit(query, lang, k):
272
+ query = query.strip()
273
+ if query is None or query == "":
274
+ return "", ""
275
+ return {
276
+ results: scisearch(query, lang, k),
277
+ flagging_form: gr.update(visible=True),
278
+ }
279
+
280
+ query.submit(fn=submit, inputs=[query, lang, k], outputs=[results, flagging_form])
281
+ submit_btn.click(submit, inputs=[query, lang, k], outputs=[results, flagging_form])
282
+
283
+ demo.launch(enable_queue=True, debug=True)