File size: 5,216 Bytes
016174f d835ff5 0d32d53 d835ff5 9f15b87 d835ff5 d87df45 d835ff5 6c2566d d835ff5 6c2566d d835ff5 4ef144a d835ff5 4ef144a d835ff5 4ef144a d835ff5 4ef144a d835ff5 c0d3665 d835ff5 4ef144a d835ff5 61820a6 4ef144a d835ff5 4ef144a d835ff5 4ef144a d835ff5 4ef144a d835ff5 4ef144a d835ff5 4ef144a 016174f 0eecf08 016174f 4ef144a 6c2566d |
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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
import argparse
import asyncio
import gradio as gr
import numpy as np
import time
import json
import os
import tempfile
import requests
import logging
from aiohttp import ClientSession
from langchain.text_splitter import RecursiveCharacterTextSplitter
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class Chunker:
def __init__(self, strategy, split_seq=".", chunk_len=512):
self.split_seq = split_seq
self.chunk_len = int(chunk_len) # Ensure chunk_len is an integer
if strategy == "recursive":
self.split = RecursiveCharacterTextSplitter(
chunk_size=self.chunk_len, # Use the integer chunk_len
separators=[split_seq]
).split_text
elif strategy == "sequence":
self.split = self.seq_splitter
elif strategy == "constant":
self.split = self.const_splitter
def seq_splitter(self, text):
return text.split(self.split_seq)
def const_splitter(self, text):
return [
text[i * self.chunk_len:(i + 1) * self.chunk_len]
for i in range(int(np.ceil(len(text) / self.chunk_len)))
]
def chunk_text(input_text, strategy, split_seq, chunk_len):
chunker = Chunker(strategy, split_seq, chunk_len)
chunks = chunker.split(input_text)
return chunks
async def embed_sent(sentence, tei_url):
payload = {
"inputs": sentence,
"truncate": True
}
async with ClientSession(
headers={
"Content-Type": "application/json",
}
) as session:
async with session.post(tei_url, json=payload) as resp:
if resp.status != 200:
raise RuntimeError(await resp.text())
result = await resp.json()
return result[0]
async def embed_first_sentence(chunks, tei_url):
if not chunks:
return [], []
first_sentence = chunks[0]
embedded_sentence = await embed_sent(first_sentence, tei_url)
return first_sentence, embedded_sentence
def wake_up_endpoint(url):
logger.info("Starting up TEI endpoint")
n_loop = 0
while requests.get(
url=url,
headers={"Content-Type": "application/json"}
).status_code != 200:
time.sleep(2)
n_loop += 1
if n_loop > 40:
raise gr.Error("TEI endpoint is unavailable")
logger.info("TEI endpoint is up")
async def process_text(input_text, strategy, split_seq, chunk_len, tei_url):
wake_up_endpoint(tei_url)
chunks = chunk_text(input_text, strategy, split_seq, chunk_len)
first_sentence, embedded_sentence = await embed_first_sentence(chunks, tei_url)
return chunks, first_sentence, embedded_sentence
def change_dropdown(choice):
if choice == "recursive":
return [
gr.Textbox(visible=True),
gr.Textbox(visible=True)
]
elif choice == "sequence":
return [
gr.Textbox(visible=True),
gr.Textbox(visible=False)
]
else:
return [
gr.Textbox(visible=False),
gr.Textbox(visible=True)
]
def main(args):
with gr.Blocks(theme='sudeepshouche/minimalist') as demo:
gr.Markdown("## Chunk and Embed")
input_text = gr.Textbox(lines=5, label="Input Text")
with gr.Row():
dropdown = gr.Dropdown(
["recursive", "sequence", "constant"], label="Chunking Strategy",
info="'recursive' uses a Langchain recursive tokenizer, 'sequence' splits texts by a chosen sequence, "
"'constant' makes chunks of the constant size",
scale=2
)
split_seq = gr.Textbox(
lines=1,
interactive=True,
visible=False,
label="Sequence",
info="A text sequence to split on",
placeholder="\n\n"
)
chunk_len = gr.Textbox(
lines=1,
interactive=True,
visible=False,
label="Length",
info="The length of chunks to split into in characters",
placeholder="512"
)
dropdown.change(fn=change_dropdown, inputs=dropdown, outputs=[split_seq, chunk_len])
tei_url = gr.Textbox(lines=1, label="TEI Endpoint URL")
with gr.Row():
clear = gr.ClearButton(components=[input_text, dropdown, split_seq, chunk_len, tei_url])
embed_btn = gr.Button("Submit")
embed_btn.click(
fn=process_text,
inputs=[input_text, dropdown, split_seq, chunk_len, tei_url],
outputs=[gr.JSON(label="Chunks"), gr.Textbox(label="First Chunked Sentence"), gr.JSON(label="Embedded Sentence")]
)
demo.queue()
demo.launch(server_name="0.0.0.0", server_port=args.port)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="A MAGIC example by ConceptaTech")
parser.add_argument("--port", type=int, default=7860, help="Port to expose Gradio app")
args = parser.parse_args()
main(args)
|