plaggy commited on
Commit
a5c096a
·
1 Parent(s): 35a9fba
Files changed (1) hide show
  1. app.py +225 -0
app.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import gradio as gr
3
+ import numpy as np
4
+ import time
5
+ import json
6
+ import os
7
+ import tempfile
8
+ import requests
9
+ import logging
10
+
11
+ from aiohttp import ClientSession
12
+ from langchain.text_splitter import SpacyTextSplitter
13
+ from datasets import Dataset, load_dataset
14
+ from tqdm import tqdm
15
+ from tqdm.asyncio import tqdm_asyncio
16
+
17
+ HF_TOKEN = os.getenv("HF_TOKEN")
18
+ SEMAPHORE_BOUND = os.getenv("SEMAPHORE_BOUND", "5")
19
+
20
+
21
+ logging.basicConfig(level=logging.INFO)
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ class Chunker:
26
+ def __init__(self, strategy, split_seq=".", chunk_len=512):
27
+ self.split_seq = split_seq
28
+ self.chunk_len = chunk_len
29
+ if strategy == "spacy":
30
+ self.split = SpacyTextSplitter().split_text
31
+ if strategy == "sequence":
32
+ self.split = self.seq_splitter
33
+ if strategy == "constant":
34
+ self.split = self.const_splitter
35
+
36
+ def seq_splitter(self, text):
37
+ return text.split(self.split_seq)
38
+
39
+ def const_splitter(self, text):
40
+ return [
41
+ text[i * self.chunk_len:(i + 1) * self.chunk_len]
42
+ for i in range(int(np.ceil(len(text) / self.chunk_len)))
43
+ ]
44
+
45
+
46
+ def generator(input_ds, input_text_col, chunker):
47
+ for i in tqdm(range(len(input_ds))):
48
+ chunks = chunker.split(input_ds[i][input_text_col])
49
+ for chunk in chunks:
50
+ if chunk:
51
+ yield {input_text_col: chunk}
52
+
53
+
54
+ def chunk(input_ds, input_splits, input_text_col, output_ds, strategy, split_seq, chunk_len, private):
55
+ input_splits = [spl.strip() for spl in input_splits.split(",") if spl]
56
+ input_ds = load_dataset(input_ds, split="+".join(input_splits))
57
+ chunker = Chunker(strategy, split_seq, chunk_len)
58
+
59
+ gen_kwargs = {
60
+ "input_ds": input_ds,
61
+ "input_text_col": input_text_col,
62
+ "chunker": chunker
63
+ }
64
+ dataset = Dataset.from_generator(generator, gen_kwargs=gen_kwargs)
65
+ dataset.push_to_hub(
66
+ output_ds,
67
+ private=private,
68
+ token=HF_TOKEN
69
+ )
70
+
71
+ logger.info("Done chunking")
72
+
73
+
74
+ async def embed_sent(sentence, embed_in_text_col, semaphore, tei_url, tmp_file):
75
+ async with semaphore:
76
+ payload = {
77
+ "inputs": sentence,
78
+ "truncate": True
79
+ }
80
+
81
+ async with ClientSession(
82
+ headers={
83
+ "Content-Type": "application/json",
84
+ "Authorization": f"Bearer {HF_TOKEN}"
85
+ }
86
+ ) as session:
87
+ async with session.post(tei_url, json=payload) as resp:
88
+ if resp.status != 200:
89
+ raise RuntimeError(await resp.text())
90
+ result = await resp.json()
91
+
92
+ tmp_file.write(
93
+ json.dumps({"vector": result[0], embed_in_text_col: sentence}) + "\n"
94
+ )
95
+
96
+
97
+ async def embed_ds(input_ds, tei_url, embed_in_text_col, temp_file):
98
+ semaphore = asyncio.BoundedSemaphore(int(SEMAPHORE_BOUND))
99
+ jobs = [
100
+ asyncio.create_task(embed_sent(row[embed_in_text_col], embed_in_text_col, semaphore, tei_url, temp_file))
101
+ for row in input_ds if row[embed_in_text_col].strip()
102
+ ]
103
+ logger.info(f"num chunks to embed: {len(jobs)}")
104
+
105
+ tic = time.time()
106
+ await tqdm_asyncio.gather(*jobs)
107
+ logger.info(f"embed time: {time.time() - tic}")
108
+
109
+
110
+ def wake_up_endpoint(url):
111
+ n_loop = 0
112
+ while requests.get(
113
+ url=url,
114
+ headers={"Authorization": f"Bearer {HF_TOKEN}"}
115
+ ).status_code != 200:
116
+ time.sleep(2)
117
+ n_loop += 1
118
+ if n_loop > 30:
119
+ raise TimeoutError("TEI endpoint is unavailable")
120
+ logger.info("TEI endpoint is up")
121
+
122
+
123
+ def run_embed(input_ds, input_splits, embed_in_text_col, output_ds, tei_url, private):
124
+ wake_up_endpoint(tei_url)
125
+ input_splits = [spl.strip() for spl in input_splits.split(",") if spl]
126
+ input_ds = load_dataset(input_ds, split="+".join(input_splits))
127
+ with tempfile.NamedTemporaryFile(mode="a", suffix=".jsonl") as temp_file:
128
+ asyncio.run(embed_ds(input_ds, tei_url, embed_in_text_col, temp_file))
129
+
130
+ dataset = Dataset.from_json(temp_file.name)
131
+ dataset.push_to_hub(
132
+ output_ds,
133
+ private=private,
134
+ token=HF_TOKEN
135
+ )
136
+
137
+ logger.info("Done embedding")
138
+
139
+
140
+ def change_dropdown(choice):
141
+ if choice == "spacy" or choice == "sequence":
142
+ return [
143
+ gr.Textbox(visible=True),
144
+ gr.Textbox(visible=False)
145
+ ]
146
+ else:
147
+ return [
148
+ gr.Textbox(visible=False),
149
+ gr.Textbox(visible=True)
150
+ ]
151
+
152
+
153
+ with gr.Blocks() as demo:
154
+ gr.Markdown(
155
+ """
156
+ ## Chunk your dataset before embedding
157
+ """
158
+ )
159
+ with gr.Tab("Chunk"):
160
+ chunk_in_ds = gr.Textbox(lines=1, label="Input dataset name")
161
+ with gr.Row():
162
+ chunk_in_splits = gr.Textbox(lines=1, label="Input dataset splits", placeholder="train, test")
163
+ chunk_in_text_col = gr.Textbox(lines=1, label="Input text column name", placeholder="text")
164
+ with gr.Row():
165
+ chunk_out_ds = gr.Textbox(lines=1, label="Output dataset name", scale=6)
166
+ chunk_private = gr.Checkbox(label="Make chunked dataset private")
167
+ with gr.Row():
168
+ dropdown = gr.Dropdown(
169
+ ["spacy", "sequence", "constant"], label="Chunking strategy",
170
+ info="'spacy' uses a Spacy tokenizer, 'sequence' splits texts by a chosen sequence, "
171
+ "'constant' makes chunks of the constant size",
172
+ scale=2
173
+ )
174
+ split_seq = gr.Textbox(
175
+ lines=1,
176
+ interactive=True,
177
+ visible=False,
178
+ label="Sequence",
179
+ info="A text sequence to split on",
180
+ placeholder="\n\n"
181
+ )
182
+ chunk_len = gr.Textbox(
183
+ lines=1,
184
+ interactive=True,
185
+ visible=False,
186
+ label="Length",
187
+ info="The length of chunks to split into",
188
+ placeholder="512"
189
+ )
190
+ dropdown.change(fn=change_dropdown, inputs=dropdown, outputs=[split_seq, chunk_len])
191
+ with gr.Row():
192
+ gr.ClearButton(
193
+ components=[
194
+ chunk_in_ds, chunk_in_splits, chunk_in_text_col, chunk_out_ds,
195
+ dropdown, split_seq, chunk_len, chunk_private
196
+ ]
197
+ )
198
+ chunk_btn = gr.Button("Chunk")
199
+ chunk_btn.click(
200
+ fn=chunk,
201
+ inputs=[chunk_in_ds, chunk_in_splits, chunk_in_text_col, chunk_out_ds,
202
+ dropdown, split_seq, chunk_len, chunk_private]
203
+ )
204
+
205
+ with gr.Tab("Embed"):
206
+ embed_in_ds = gr.Textbox(lines=1, label="Input dataset name")
207
+ with gr.Row():
208
+ embed_in_splits = gr.Textbox(lines=1, label="Input dataset splits", placeholder="train, test")
209
+ embed_in_text_col = gr.Textbox(lines=1, label="Input text column name", placeholder="text")
210
+ with gr.Row():
211
+ embed_out_ds = gr.Textbox(lines=1, label="Output dataset name", scale=6)
212
+ embed_private = gr.Checkbox(label="Make embedded dataset private")
213
+ tei_url = gr.Textbox(lines=1, label="TEI endpoint url")
214
+ with gr.Row():
215
+ gr.ClearButton(
216
+ components=[embed_in_ds, embed_in_splits, embed_in_text_col, embed_out_ds, tei_url, embed_private]
217
+ )
218
+ embed_btn = gr.Button("Run embed")
219
+ embed_btn.click(
220
+ fn=run_embed,
221
+ inputs=[embed_in_ds, embed_in_splits, embed_in_text_col, embed_out_ds, tei_url, embed_private]
222
+ )
223
+
224
+
225
+ demo.launch(debug=True)