Mofe commited on
Commit
8cad083
·
verified ·
1 Parent(s): bba8d9d

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -1,35 +1,5 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ index/**/* filter=lfs diff=lfs merge=lfs -text
2
+ sparse_index/_0.fdt filter=lfs diff=lfs merge=lfs -text
3
+ sparse_index/_0_Lucene90_0.doc filter=lfs diff=lfs merge=lfs -text
4
+ sparse_index/_0_Lucene90_0.pos filter=lfs diff=lfs merge=lfs -text
5
+ sparse_index/_0_Lucene90_0.tim filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,10 +1,13 @@
1
  ---
2
- title: Xsumcli
3
- emoji: 🐢
4
- colorFrom: gray
5
- colorTo: purple
6
- sdk: static
 
 
7
  pinned: false
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: None
3
+ emoji: 🚀
4
+ colorFrom: blue
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 3.12.0
8
+ app_file: app.py
9
  pinned: false
10
+ license: apache-2.0
11
  ---
12
 
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, NewType, Optional, Union
2
+
3
+ import gradio as gr
4
+
5
+ from spacerini_utils.index import fetch_index_stats
6
+ from spacerini_utils.search import _search, init_searcher, SearchResult
7
+
8
+ HTML = NewType('HTML', str)
9
+
10
+ searcher = init_searcher(sparse_index_path="sparse_index")
11
+
12
+ def get_docid_html(docid: Union[int, str]) -> HTML:
13
+ docid_html = (
14
+ f"<a "
15
+ f'class="underline-on-hover"'
16
+ 'title="This dataset is licensed apache-2.0"'
17
+ f'style="color:#2D31FA;"'
18
+ 'href="https://huggingface.co/datasets/🚀"'
19
+ 'target="_blank"><b>🔒xsum</b></a><span style="color: #7978FF;">/'+f'{docid}</span>'
20
+ )
21
+
22
+ return docid_html
23
+
24
+
25
+ def process_results(results: List[SearchResult], language: str, highlight_terms: Optional[List[str]] = None) -> HTML:
26
+ if len(results) == 0:
27
+ return """<br><p style='font-family: Arial; color:Silver; text-align: center;'>
28
+ No results retrieved.</p><br><hr>"""
29
+
30
+ results_html = ""
31
+ for result in results:
32
+ tokens = result["text"].split()
33
+
34
+ tokens_html = []
35
+ if highlight_terms:
36
+ for token in tokens:
37
+ if token in highlight_terms:
38
+ tokens_html.append("<b>{}</b>".format(token))
39
+ else:
40
+ tokens_html.append(token)
41
+
42
+ tokens_html = " ".join(tokens_html)
43
+ meta_html = (
44
+ """
45
+ <p class='underline-on-hover' style='font-size:12px; font-family: Arial; color:#585858; text-align: left;'>
46
+ """
47
+ )
48
+ docid_html = get_docid_html(result["docid"])
49
+ results_html += """{}
50
+ <p style='font-size:20px; font-family: Arial; color:#7978FF; text-align: left;'>Document ID: {}</p>
51
+ <p style='font-size:14px; font-family: Arial; color:#7978FF; text-align: left;'>Score: {}</p>
52
+ <p style='font-size:12px; font-family: Arial; color:MediumAquaMarine'>Language: {}</p>
53
+ <p style='font-family: Arial;font-size:15px;'>{}</p>
54
+ <br>
55
+ """.format(
56
+ meta_html, docid_html, result["score"], language, tokens_html
57
+ )
58
+ return results_html + "<hr>"
59
+
60
+
61
+ def search(query: str, language: str, num_results: int = 10) -> HTML:
62
+ results_dict = _search(searcher, query, num_results=num_results)
63
+ return process_results(results_dict, language)
64
+
65
+
66
+ stats = fetch_index_stats('sparse_index/')
67
+
68
+ description = f"""# <h2 style="text-align: center;"> 🚀 🔎 None 🔍 🚀 </h2>
69
+ <p style="text-align: center;font-size:15px;">None</p>
70
+ <p style="text-align: center;font-size:20px;">Dataset Statistics: Total Number of Documents = <b>{stats["documents"]}</b>, Number of Terms = <b>{stats["total_terms"]}</b> </p>"""
71
+
72
+ demo = gr.Blocks(
73
+ css=".underline-on-hover:hover { text-decoration: underline; } .flagging { font-size:12px; color:Silver; }"
74
+ )
75
+
76
+ with demo:
77
+ with gr.Row():
78
+ gr.Markdown(value=description)
79
+ with gr.Row():
80
+ query = gr.Textbox(lines=1, max_lines=1, placeholder="Type your query here...", label="Query")
81
+ with gr.Row():
82
+ lang = gr.Dropdown(
83
+ choices=[
84
+ "en",
85
+ "detect_language",
86
+ "all",
87
+ ],
88
+ value="en",
89
+ label="Language",
90
+ )
91
+ with gr.Row():
92
+ k = gr.Slider(1, 100, value=10, step=1, label="Max Results")
93
+ with gr.Row():
94
+ submit_btn = gr.Button("Submit")
95
+ with gr.Row():
96
+ results = gr.HTML(label="Results")
97
+
98
+
99
+ def submit(query: str, lang: str, k: int):
100
+ query = query.strip()
101
+ if query is None or query == "":
102
+ return "", ""
103
+ return {
104
+ results: search(query, lang, k),
105
+ }
106
+
107
+ query.submit(fn=submit, inputs=[query, lang, k], outputs=[results])
108
+ submit_btn.click(submit, inputs=[query, lang, k], outputs=[results])
109
+
110
+ demo.launch(enable_queue=True, debug=True)
index/.gitkeep ADDED
File without changes
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ default-jdk
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ pyserini
2
+ datasets
3
+ faiss-cpu
4
+ torch
spacerini_utils/__init__.py ADDED
File without changes
spacerini_utils/index.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Any
3
+ from typing import Dict
4
+
5
+ from pyserini.index.lucene import IndexReader
6
+
7
+
8
+ def fetch_index_stats(index_path: str) -> Dict[str, Any]:
9
+ """
10
+ Fetch index statistics
11
+ index_path : str
12
+ Path to index directory
13
+ Returns
14
+ -------
15
+ Dictionary of index statistics
16
+ Dictionary Keys ==> total_terms, documents, unique_terms
17
+ """
18
+ assert os.path.exists(index_path), f"Index path {index_path} does not exist"
19
+ index_reader = IndexReader(index_path)
20
+ return index_reader.stats()
spacerini_utils/search.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from typing import List, Literal, Protocol, Tuple, TypedDict, Union
3
+
4
+ from pyserini.analysis import get_lucene_analyzer
5
+ from pyserini.index import IndexReader
6
+ from pyserini.search import DenseSearchResult, JLuceneSearcherResult
7
+ from pyserini.search.faiss.__main__ import init_query_encoder
8
+ from pyserini.search.faiss import FaissSearcher
9
+ from pyserini.search.hybrid import HybridSearcher
10
+ from pyserini.search.lucene import LuceneSearcher
11
+
12
+ EncoderClass = Literal["dkrr", "dpr", "tct_colbert", "ance", "sentence", "contriever", "auto"]
13
+
14
+
15
+ class AnalyzerArgs(TypedDict):
16
+ language: str
17
+ stemming: bool
18
+ stemmer: str
19
+ stopwords: bool
20
+ huggingFaceTokenizer: str
21
+
22
+
23
+ class SearchResult(TypedDict):
24
+ docid: str
25
+ text: str
26
+ score: float
27
+ language: str
28
+
29
+
30
+ class Searcher(Protocol):
31
+ def search(self, query: str, **kwargs) -> List[Union[DenseSearchResult, JLuceneSearcherResult]]:
32
+ ...
33
+
34
+
35
+ def init_searcher_and_reader(
36
+ sparse_index_path: str = None,
37
+ bm25_k1: float = None,
38
+ bm25_b: float = None,
39
+ analyzer_args: AnalyzerArgs = None,
40
+ dense_index_path: str = None,
41
+ encoder_name_or_path: str = None,
42
+ encoder_class: EncoderClass = None,
43
+ tokenizer_name: str = None,
44
+ device: str = None,
45
+ prefix: str = None
46
+ ) -> Tuple[Union[FaissSearcher, HybridSearcher, LuceneSearcher], IndexReader]:
47
+ """
48
+ Initialize and return an approapriate searcher
49
+
50
+ Parameters
51
+ ----------
52
+ sparse_index_path: str
53
+ Path to sparse index
54
+ dense_index_path: str
55
+ Path to dense index
56
+ encoder_name_or_path: str
57
+ Path to query encoder checkpoint or encoder name
58
+ encoder_class: str
59
+ Query encoder class to use. If None, infer from `encoder`
60
+ tokenizer_name: str
61
+ Tokenizer name or path
62
+ device: str
63
+ Device to load Query encoder on.
64
+ prefix: str
65
+ Query prefix if exists
66
+
67
+ Returns
68
+ -------
69
+ Searcher: FaissSearcher | HybridSearcher | LuceneSearcher
70
+ A sparse, dense or hybrid searcher
71
+ """
72
+ reader = None
73
+ if sparse_index_path:
74
+ ssearcher = LuceneSearcher(sparse_index_path)
75
+ if analyzer_args:
76
+ analyzer = get_lucene_analyzer(**analyzer_args)
77
+ ssearcher.set_analyzer(analyzer)
78
+ if bm25_k1 and bm25_b:
79
+ ssearcher.set_bm25(bm25_k1, bm25_b)
80
+
81
+ if dense_index_path:
82
+ encoder = init_query_encoder(
83
+ encoder=encoder_name_or_path,
84
+ encoder_class=encoder_class,
85
+ tokenizer_name=tokenizer_name,
86
+ topics_name=None,
87
+ encoded_queries=None,
88
+ device=device,
89
+ prefix=prefix
90
+ )
91
+
92
+ reader = IndexReader(sparse_index_path)
93
+ dsearcher = FaissSearcher(dense_index_path, encoder)
94
+
95
+ if sparse_index_path:
96
+ hsearcher = HybridSearcher(dense_searcher=dsearcher, sparse_searcher=ssearcher)
97
+ return hsearcher, reader
98
+ else:
99
+ return dsearcher, reader
100
+
101
+ return ssearcher, reader
102
+
103
+
104
+ def _search(searcher: Searcher, reader: IndexReader, query: str, num_results: int = 10) -> List[SearchResult]:
105
+ """
106
+ Parameters:
107
+ -----------
108
+ searcher: FaissSearcher | HybridSearcher | LuceneSearcher
109
+ A sparse, dense or hybrid searcher
110
+ query: str
111
+ Query for which to retrieve results
112
+ num_results: int
113
+ Maximum number of results to retrieve
114
+
115
+ Returns:
116
+ --------
117
+ Dict:
118
+ """
119
+ def _get_dict(r: Union[DenseSearchResult, JLuceneSearcherResult]):
120
+ if isinstance(r, JLuceneSearcherResult):
121
+ return json.loads(r.raw)
122
+ elif isinstance(r, DenseSearchResult):
123
+ # Get document from sparse_index using index reader
124
+ return json.loads(reader.doc(r.docid).raw())
125
+
126
+ search_results = searcher.search(query, k=num_results)
127
+ all_results = [
128
+ SearchResult(
129
+ docid=result["id"],
130
+ text=result["contents"],
131
+ score=search_results[idx].score
132
+ ) for idx, result in enumerate(map(lambda r: _get_dict(r), search_results))
133
+ ]
134
+
135
+ return all_results
sparse_index/_0.fdm ADDED
Binary file (158 Bytes). View file
 
sparse_index/_0.fdt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a9653b671af279f143c0dd3a61f4b162688f24048df7f79577cc7a620ef06bd2
3
+ size 25713651
sparse_index/_0.fdx ADDED
Binary file (2.17 kB). View file
 
sparse_index/_0.fnm ADDED
Binary file (343 Bytes). View file
 
sparse_index/_0.nvd ADDED
Binary file (11.4 kB). View file
 
sparse_index/_0.nvm ADDED
Binary file (103 Bytes). View file
 
sparse_index/_0.si ADDED
Binary file (480 Bytes). View file
 
sparse_index/_0_Lucene90_0.doc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3565da3ce3e8c08edf7c6a1af79f74f2c5256aab8649d7aeb57a6ebb78441970
3
+ size 2539833
sparse_index/_0_Lucene90_0.dvd ADDED
Binary file (90.7 kB). View file
 
sparse_index/_0_Lucene90_0.dvm ADDED
Binary file (133 Bytes). View file
 
sparse_index/_0_Lucene90_0.pos ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7af63495f7ed503de8060d9d034f20867f6efd55c03e3446804772b997c9a84
3
+ size 3890273
sparse_index/_0_Lucene90_0.tim ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:311a4a8d73261eac691ce45614c02f1510ff1e672e35bae7ff03676f66e8bbf8
3
+ size 660334
sparse_index/_0_Lucene90_0.tip ADDED
Binary file (16.9 kB). View file
 
sparse_index/_0_Lucene90_0.tmd ADDED
Binary file (271 Bytes). View file
 
sparse_index/segments_1 ADDED
Binary file (154 Bytes). View file
 
sparse_index/write.lock ADDED
File without changes