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 lines989910097 unmodified lines.bash_env**/*secret***/*private*97 unmodified lines989910010197 unmodified lines.bash_env**/*secret***/*private*/call_history.csv
137 unmodified lines1381391401411421431441451461471481491501511521531542 unmodified lines157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229137 unmodified linesroutes.get_types = get_typesfunctions = {"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 lineswith 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"""## API```pythonimport requestsrequests.post(url="https://tangibleai-mathtext.hf.space/run/text2int", json={"data": ["one hundred forty five", "text2int"]}).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']}")# interface = gr.Interface(lambda x: x, inputs=["text"], outputs=["text"])# html_block.input_components = interface.input_components137 unmodified lines1381391401411421432 unmodified lines146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278137 unmodified linesroutes.get_types = get_typessentiment = pipeline(task="sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")2 unmodified lineswith gr.Blocks() as html_block:gr.Markdown("# Rori - Mathbot")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"),]outputs_text2int = gr.Textbox(label="Output integer")button_text2int = gr.Button("text2int")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```pythonimport requestsrequests.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"]}'```{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```pythonimport requestsrequests.post(url="https://tangibleai-mathtext.hf.space/run/text2int_preprocessed", json={"data": ["one hundred forty five"]}).json()```Or using `curl`:```bashcurl -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```pythonimport requestsrequests.post(url="https://tangibleai-mathtext.hf.space/run/sentiment-analysis", json={"data": ["You are right!"]}).json()```Or using `curl`:```bashcurl -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_components
123456789import 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 lines5674 unmodified linespython-dotenvtransformerstorch4 unmodified lines56784 unmodified linespython-dotenvtransformerstorchhttpx
2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162632 unmodified linesimport asyncioimport randomimport timeimport httpxheaders = {"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"]},]# async call to endpointasync def call_api(url, data, number):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')}"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")asyncio.run(main(30))2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394952 unmodified linesimport asyncioimport randomimport timeimport pandas as pdimport httpxfrom os.path import existsNUMBER_OF_CALLS = 10headers = {"Content-Type": "application/json; charset=utf-8"}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, 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()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)start = time.perf_counter()asyncio.run(main(NUMBER_OF_CALLS))end = time.perf_counter()print(end-start)df = pd.DataFrame(results)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