Spaces:
Runtime error
Runtime error
Update test_api
Browse filesFiles changed (5)
- .gitignore+1
- app.py+122-73
- plot_calls.pyAdded+9
- requirements.txt+1
- test_api.py+75-43
97 unmodified lines989910010197 unmodified lines.bash_env**/*secret***/*private*/call_history.csv137 unmodified lines1381391401411421431441451461471481491501511411421432 unmodified lines146147148160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209149150211151152153154155156213214157158216217218219159160221161162163164165166167168169170171172173174175176177178179180181182183184185186187223224225226188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278137 unmodified lines
routes.get_types = get_types
functions = { "text2int": text2int, "text2int_preprocessed": try_text2int_preprocessed,}
def text2int_selector(text, func): f = functions[func] return f(text)
sentiment = pipeline(task="sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
2 unmodified lines
with gr.Blocks() as html_block: gr.Markdown("# Gradio Blocks (3.0) with REST API")
inputs_text2int = [ gr.Text(placeholder="Type a number as text or a sentence", label="Text to process", value="forty two"), gr.Radio(["text2int", "text2int_preprocessed"], label="Function Selection", value="text2int") ]
outputs_text2int = gr.Textbox(label="Output integer")
button_text2int = gr.Button("text2int")
button_text2int.click( fn=text2int_selector, inputs=inputs_text2int, outputs=outputs_text2int, api_name="text2int", )
examples_text2int = [ ["one thousand forty seven", "text2int"], ["one hundred", "text2int_preprocessed"], ]
gr.Examples(examples=examples_text2int, inputs=inputs_text2int)
inputs_sentiment = [ gr.Text(placeholder="Type a number as text or a sentence", label="Text to process", value="I really like it!"), ]
outputs_sentiment = gr.Textbox(label="Sentiment result")
button_sentiment = gr.Button("sentiment analysis")
button_sentiment.click( get_sentiment, inputs=inputs_sentiment, outputs=outputs_sentiment, api_name="sentiment-analysis" )
examples_sentiment = [ ["Couldn't agree more!"], ["Sorry, I can not accept this!"], ]
gr.Examples(examples=examples_sentiment, inputs=inputs_sentiment)
gr.Markdown(r""" gr.Markdown("# Rori - Mathbot")
## API with gr.Tab("Text to integer"): inputs_text2int = [ gr.Text(placeholder="Type a number as text or a sentence", label="Text to process", value="forty two"), ]
```pythonimport requests outputs_text2int = gr.Textbox(label="Output integer")
requests.post( url="https://tangibleai-mathtext.hf.space/run/text2int", json={"data": ["one hundred forty five", "text2int"]}).json()``` button_text2int = gr.Button("text2int")
Or using `curl`: button_text2int.click( fn=try_text2int, inputs=inputs_text2int, outputs=outputs_text2int, api_name="text2int", )
examples_text2int = [ "one thousand forty seven", "one hundred", ]
gr.Examples(examples=examples_text2int, inputs=inputs_text2int)
gr.Markdown(r"""
## API ```python import requests
requests.post( url="https://tangibleai-mathtext.hf.space/run/text2int", json={"data": ["one hundred forty five"]} ).json() ```
Or using `curl`:
```bashcurl -X POST https://tangibleai-mathtext.hf.space/run/text2int -H 'Content-Type: application/json' -d '{"data": ["one hundred forty five", "text2int"]}'```""" + f"{json.loads(BQ_JSON)['type']}") ```bash curl -X POST https://tangibleai-mathtext.hf.space/run/text2int -H 'Content-Type: application/json' -d '{"data": ["one hundred forty five"]}' ``` {bq_json}""" + f"{json.loads(BQ_JSON)['type']}")
with gr.Tab("Text to integer preprocessed"): inputs_text2int_preprocessed = [ gr.Text(placeholder="Type a number as text or a sentence", label="Text to process", value="forty two"), ]
outputs_text2int_preprocessed = gr.Textbox(label="Output integer")
button_text2int = gr.Button("text2int preprocessed")
button_text2int.click( fn=try_text2int_preprocessed, inputs=inputs_text2int_preprocessed, outputs=outputs_text2int_preprocessed, api_name="text2int_preprocessed", )
examples_text2int_preprocessed = [ "one thousand forty seven", "one hundred", ]
gr.Examples(examples=examples_text2int_preprocessed, inputs=inputs_text2int_preprocessed)
gr.Markdown(r"""
## API ```python import requests
requests.post( url="https://tangibleai-mathtext.hf.space/run/text2int_preprocessed", json={"data": ["one hundred forty five"]} ).json() ```
Or using `curl`:
```bash curl -X POST https://tangibleai-mathtext.hf.space/run/text2int_preprocessed -H 'Content-Type: application/json' -d '{"data": ["one hundred forty five"]}' ``` {bq_json}""" + f"{json.loads(BQ_JSON)['type']}")
with gr.Tab("Sentiment Analysis"): inputs_sentiment = [ gr.Text(placeholder="Type a number as text or a sentence", label="Text to process", value="I really like it!"), ]
outputs_sentiment = gr.Textbox(label="Sentiment result")
button_sentiment = gr.Button("sentiment analysis")
button_sentiment.click( get_sentiment, inputs=inputs_sentiment, outputs=outputs_sentiment, api_name="sentiment-analysis" )
examples_sentiment = [ ["Totally agree!"], ["Sorry, I can not accept this!"], ]
gr.Examples(examples=examples_sentiment, inputs=inputs_sentiment)
gr.Markdown(r""" ## API ```python import requests requests.post( url="https://tangibleai-mathtext.hf.space/run/sentiment-analysis", json={"data": ["You are right!"]} ).json() ``` Or using `curl`: ```bash curl -X POST https://tangibleai-mathtext.hf.space/run/sentiment-analysis -H 'Content-Type: application/json' -d '{"data": ["You are right!"]}' ``` {bq_json}""" + f"{json.loads(BQ_JSON)['type']}")
# interface = gr.Interface(lambda x: x, inputs=["text"], outputs=["text"])# html_block.input_components = interface.input_components123456789import matplotlib.pyplot as pltimport pandas as pd
df = pd.read_csv('call_history.csv') # data loadingprint(df)
df.plot(by='endpoint', column='delay', kind='box', showmeans=True)
plt.show()4 unmodified lines56784 unmodified linespython-dotenvtransformerstorchhttpx2 unmodified lines3456678910111213111213141516171819202122232425262728293031323334351415161718192021222324252627282930313233343536373839404142434445464748495039405152535455564546474849575859606162636465666768697071727374757677787980818283845253545556575859608586878889909163929394952 unmodified linesimport asyncioimport randomimport time
import pandas as pdimport httpxfrom os.path import exists
NUMBER_OF_CALLS = 10
headers = {"Content-Type": "application/json; charset=utf-8"}
data_list_local = [ {"url": "http://127.0.0.1:7860/run/text2int", "data": ["one hundred forty five", "text2int"]}, {"url": "http://127.0.0.1:7860/run/text2int", "data": ["twenty thousand nine hundred fifty", "text2int_preprocessed"]}, {"url": "http://127.0.0.1:7860/run/text2int", "data": ["one hundred forty five", "text2int"]}, {"url": "http://127.0.0.1:7860/run/text2int", "data": ["nine hundred eighty three", "text2int_preprocessed"]}, {"url": "http://127.0.0.1:7860/run/text2int", "data": ["five million"]}, {"url": "http://127.0.0.1:7860/run/sentiment-analysis", "data": ["Totally agree"]}, {"url": "http://127.0.0.1:7860/run/sentiment-analysis", "data": ["I like it"]}, {"url": "http://127.0.0.1:7860/run/sentiment-analysis", "data": ["No more"]}, {"url": "http://127.0.0.1:7860/run/sentiment-analysis", "data": ["I am not sure"]}, {"url": "http://127.0.0.1:7860/run/sentiment-analysis", "data": ["Never"]},]
data_remote = [ {"url": "https://tangibleai-mathtext.hf.space/run/text2int", "data": ["one hundred forty five", "text2int"]}, {"url": "https://tangibleai-mathtext.hf.space/run/text2int", "data": ["twenty thousand nine hundred fifty", "text2int_preprocessed"]}, {"url": "https://tangibleai-mathtext.hf.space/run/text2int", "data": ["one hundred forty five", "text2int"]}, {"url": "https://tangibleai-mathtext.hf.space/run/text2int", "data": ["nine hundred eighty three", "text2int_preprocessed"]}, {"url": "https://tangibleai-mathtext.hf.space/run/text2int", "data": ["five million"]}, {"url": "https://tangibleai-mathtext.hf.space/run/sentiment-analysis", "data": ["Totally agree"]}, {"url": "https://tangibleai-mathtext.hf.space/run/sentiment-analysis", "data": ["I like it"]}, {"url": "https://tangibleai-mathtext.hf.space/run/sentiment-analysis", "data": ["No more"]}, {"url": "https://tangibleai-mathtext.hf.space/run/sentiment-analysis", "data": ["I am not sure"]}, {"url": "https://tangibleai-mathtext.hf.space/run/sentiment-analysis", "data": ["Never"]},]base_url = "https://tangibleai-mathtext.hf.space/run/{endpoint}"# base_url = "http://localhost:7860/run/{endpoint}"
data_list_1 = { "endpoint": "text2int", "test_data": [ "one hundred forty five", "twenty thousand nine hundred fifty", "one hundred forty five", "nine hundred eighty three", "five million", ]}
data_list_2 = { "endpoint": "text2int_preprocessed", "test_data": [ "one hundred forty five", "twenty thousand nine hundred fifty", "one hundred forty five", "nine hundred eighty three", "five million", ]}data_list_3 = { "endpoint": "sentiment-analysis", "test_data": [ "Totally agree", "I like it", "No more", "I am not sure", "Never", ]}
# async call to endpointasync def call_api(url, data, number): json = {"data": data}async def call_api(url, data, call_number, number_of_calls): json = {"data": [data]} async with httpx.AsyncClient() as client: start = time.perf_counter() # Used perf_counter for more precise result. response = await client.post(url=url, headers=headers, json=json, timeout=30) end = time.perf_counter() # print(response.status_code) return f"Call_{number}\n" \ f"start: {start:.4f} end: {end:.4f} delay: {(end - start):.4f}\n" \ f"input_text: {data}\n" \ f"result: {response.json().get('data')}" return { "endpoint": url.split("/")[-1], "test data": data, "response": response.json().get("data"), "call number": call_number, "number of calls": number_of_calls, "start": start.__round__(4), "end": end.__round__(4), "delay": (end - start).__round__(4) }
data_lists = [data_list_1, data_list_2, data_list_3]
results = []
async def main(number_of_calls): for data_list in data_lists: calls = [] for call_number in range(1, number_of_calls + 1): url = base_url.format(endpoint=data_list["endpoint"]) data = random.choice(data_list["test_data"]) calls.append(call_api(url, data, call_number, number_of_calls)) r = await asyncio.gather(*calls) results.extend(r)
async def main(n): calls = [] for num in range(n): item = random.choice(data_remote) url, data = item["url"], item["data"] # calls.append(call_api(remote_url, data_list, num)) calls.append(call_api(url, data, num)) r = await asyncio.gather(*calls) print(*r, sep="\n")
start = time.perf_counter()asyncio.run(main(NUMBER_OF_CALLS))end = time.perf_counter()print(end-start)df = pd.DataFrame(results)
asyncio.run(main(30))if exists("call_history.csv"): df.to_csv(path_or_buf="call_history.csv", mode="a", header=False, index=False)else: df.to_csv(path_or_buf="call_history.csv", mode="w", header=True, index=False).gitignore+1
app.py+122-73
plot_calls.pyAdded+9
requirements.txt+1
test_api.py+75-43