Rahmat82's picture
token update
41e6994 verified
import gradio as gr
import aiohttp
import asyncio
import os
# API endpoint - model name
API_URL = "https://api-inference.huggingface.co/models/Rahmat82/t5-small-finetuned-summarization-xsum"
SECRET_KEY = os.environ.get("summarize_text")
# asynchronous function
async def summarize(text, retries=6):
if len(text) < 240:
return "⛔ You text is too short! Please input a longer text for summarization."
headers = {"Authorization": f"Bearer {SECRET_KEY}"}
data = {
"inputs": text,
"options": {
"max_new_tokens": 128,
"min_length": 10,
"max_length": 500,
"length_penalty": 2.0,
"num_beams": 3,
"early_stopping": True
}
}
async with aiohttp.ClientSession() as session:
for attempt in range(retries):
try:
async with session.post(API_URL, headers=headers, json=data) as response:
# raise exception for non-200 status codes
response.raise_for_status()
result = await response.json()
return result[0]["summary_text"]
except (aiohttp.ClientResponseError, aiohttp.ClientConnectionError) as e:
# retry only if the error is 503 (Service Unavailable)
if isinstance(e, aiohttp.ClientResponseError) and e.status == 503 and attempt < retries - 1:
# add a short delay before retrying
await asyncio.sleep(2.5)
continue
else:
return "Oops! 🙈 It looks like those mischievous monkeys🐒 might be swinging around the server, causing a bit of chaos with the cables. Please try it again!"
# define gradio interface
iface = gr.Interface(
theme=gr.themes.Soft(),
fn=summarize,
title="Text Summarizer",
description="<h4>On local GPU/CPU it takes <1s 🚀</h4> <h5>Please keep in mind that the input text should be at least few sentences long 🙂</h5>" ,
inputs=gr.Textbox(label="Write your text here --- quick🐰 input", lines=10),
outputs=gr.Textbox(label="Summary --- quack🦆 output"),
submit_btn=gr.Button("Summarize", variant="primary"),
allow_flagging='never',
examples=[
["""
If you ever feel the need to sleep while standing, a company in Japan has catered to your needs. The Koyoju Plywood Corporation on Japan's northernmost island of Hokkaido has unveiled the "Giraffenap" booth. This ingenious cubicle allows the user to sleep in a vertical position. It will allow office workers and commuters to catch forty winks without the need for a bed. The designers say a 20-minute nap improves mental performance and increases productivity by reducing fatigue. It also boosts concentration and aids memory retention. The Giraffenap pods come in two designs – the futuristic-looking 'Spacia' and the lattice wood 'Forest'. They will go on sale in December at an expected price of around $20,000. The Giraffenap website says there is a need to refresh while at work. It says: "It's so common these days to work non-stop without an opportunity to properly recover from physical fatigue or stress, often resulting in unwanted sleepiness during the day. Now it's time to break the stereotype that nodding off on the job is a sign of boredom or laziness." The site added that naps allow for "more efficient and fulfilling work". The website stated that napping reduces drowsiness, and improves ingenuity and creativeness. The designers offered some advice for an effective snooze. The optimal time is 15 to 20 minutes, and all naps should take place before 3 p.m. In addition, you should not lie down as this leads to deep sleep.
"""],
["""
A new form of transport will be with us in the next few years – flying taxis. Many of us grew up watching sci-fi movies with airborne taxis. Science fiction is now becoming science fact. The Japanese airline ANA has teamed up with a U.S. tech start-up called Joby Aviation. The two companies aim to start operating air taxis at the 2025 World Expo in Osaka. They are currently working together on building the flying vehicle. They also need to work out what traffic rules the taxis will need to follow, and what kind of training flying taxi pilots will need. The five-seat, all-electric taxi will be able to take off and land vertically. It will have a flight range of 241 kilometers and a top speed of 321kph. Joby's CEO said the taxis would be good for the environment. He told reporters: "Joby exists to help people save time while reducing their carbon footprint. Japan offers us a spectacular opportunity to do just that with 92 per cent of the population living in urban areas, and Tokyo being one of the top 20 most congested cities in the world." The president of ANA, Koji Shibata, was also excited about the project. He said: "ANA has 70 years of experience delivering safe and reliable flights to customers across the world.…Being able to provide them with the option to travel rapidly, and sustainably, from an international airport to a downtown location is very appealing."
"""],
["""
The koala is regarded as the epitome of cuddliness. However, animal lovers will be saddened to hear that this lovable marsupial has been moved to the endangered species list. The Australian Koala Foundation estimates there are somewhere between 43,000-100,000 koalas left in the wild. Their numbers have been dwindling rapidly due to disease, loss of habitat, bushfires, being hit by cars, and other threats. Stuart Blanch from the World Wildlife Fund in Australia said: "Koalas have gone from no listing to vulnerable to endangered within a decade. That is a shockingly fast decline." He added that koalas risk "sliding toward extinction" unless there are "stronger laws…to protect their forest homes". The koala has huge cultural significance for Australia. Wikipedia writes: "The koala is well known worldwide and is a major draw for Australian zoos and wildlife parks. It has been featured in advertisements, games, cartoons, and as soft toys. It benefited the national tourism industry by over an estimated billion Australian dollars in 1998, a figure that has since grown." Despite this, efforts to protect the koala have been failing. Australia's Environment Minister Sussan Ley said there have been "many pressures on the koala," and that it is "vulnerable to climate change and to disease". She said the 2019-2020 bushfires, which killed at least 6,400 of the animals, were "a tipping point".
"""],
["""
Everybody knows that eating carrots is good for our eyesight. A new study suggests that grapes are also good for our eyes. Researchers from the National University of Singapore have found that eating just a few grapes a day can improve our vision. This is especially so for people who are older. Dr Eun Kim, the lead researcher, said: "Our study is the first to show that grape consumption beneficially impacts eye health in humans, which is very exciting, especially with a growing, ageing population." Dr Kim added that, "grapes are an easily accessible fruit that studies have shown can have a beneficial impact" on our eyesight. This is good news for people who don't really like carrots. The study is published in the journal "Food & Function". Thirty-four adults took part in a series of experiments over 16 weeks. Half of the participants ate one-and-a-half cups of grapes per day; the other half ate a placebo snack. Dr Kim did not tell the participants or the researchers whether she was testing the grapes or the snack. She thought that not revealing this information would give better test results. She found that people who ate the grapes had improved muscle strength around the retina. The retina passes information about light to the brain via electrical signals. It protects the eyes from damaging blue light. A lot of blue light comes from computer and smartphone screens, and from LED lights.
"""]
]
)
iface.launch()