Spaces:
Running
Running
File size: 19,893 Bytes
b4f77f4 96d2af2 90a0dbb a5c6b5f b4f77f4 117007f 90a0dbb b4f77f4 90a0dbb b4f77f4 a5c6b5f 90a0dbb a5c6b5f 346be3f a5c6b5f 346be3f a5c6b5f 346be3f a5c6b5f 346be3f a5c6b5f 96d2af2 a5c6b5f b4f77f4 a5c6b5f b4f77f4 a5c6b5f b4f77f4 346be3f | 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 | from compressor.semantic import compress_text, count_tokens
import gradio as gr
import time
async def predict(text, word_reduction_factor, reference_text_steering):
if len(text.split()) > 10000:
return "Text is too long for this demo. Please provide a text with less than 10000 words."
if word_reduction_factor is None:
word_reduction_factor = 0.5
start = time.perf_counter()
compressed = compress_text(text, compression_rate= word_reduction_factor, reference_text_steering=reference_text_steering)
elapsed_ms = (time.perf_counter() - start) * 1000
perc_reduction = round(100 - (count_tokens(compressed) / count_tokens(text)) * 100, 2)
return f"{compressed}\n\nToken Reduction: {perc_reduction}% | Compressed in {elapsed_ms:.1f} ms on CPU"
SWEDEN_EN = 'Almost 30 years ago, a revolutionary idea changed the way Europe regarded road collisions. It has probably saved countless lives but it\'s yet to be fully accepted by politicians. In 1995, a serious crash occurred on the E4 motorway near Stockholm, Sweden. Five young people were travelling in a hatchback car when the vehicle went into a roll near the exit ramp for the Ikea store. The car smashed into a concrete structure supporting a streetlight by the side of the road, and all five passengers were killed. "I am rather sure they were speeding, and as it was wet, they probably aquaplaned," says Claes Tingvall. Almost 30 years on, he struggles to remember all the details – but he is sure about one thing: "The car was a three-door Peugeot 205 GTI, red." More than 500 people died on Sweden\'s roads that year, but this tragedy signalled a turning point in how Tingvall, and eventually the world, regarded road crashes. An estimated 1.2 million lives are cut short by road traffic collisions globally each year, while millions more suffer often life-changing injuries. While the death toll has decreased slightly over the past 13 years – the number of fatalities on the world\'s roads are 5% lower than they were in 2010 according to the World Health Organization (WHO) – progress has been slow and falls far short of the WHO\'s target of halving the number of road deaths by the end of this decade. Today, Sweden has some of the lowest rates of road traffic fatalities in the world, and the story of how the country has strived to bring that number to zero provides a lesson for other countries where the death toll has remained stubbornly high. Back in 1995, Tingvall had become the head of road safety for the Swedish Road Adminstration. He was very well qualified for the role, but quite unlike any of his predecessors. Instead of coming up through the ranks of road transport engineers and bureaucrats, Tingvall had a medical background: he had studied at the renowned Karolinska Institute, where he had gained a doctorate in the epidemiology of injuries.'
SWEDEN_PT = 'Há quase 30 anos, uma ideia revolucionária mudou a forma como a Europa encarava as colisões rodoviárias. Provavelmente salvou inúmeras vidas, mas ainda não foi totalmente aceite pelos políticos. Em 1995, ocorreu um grave acidente na autoestrada E4, perto de Estocolmo, na Suécia. Cinco jovens viajavam em um carro hatch quando o veículo capotou perto da rampa de saída da loja Ikea. O carro bateu em uma estrutura de concreto que sustentava um poste de luz na beira da estrada e todos os cinco passageiros morreram. “Tenho certeza de que eles estavam em alta velocidade e, como estava molhado, provavelmente aquaplanaram”, diz Claes Tingvall. Quase 30 anos depois, ele luta para lembrar de todos os detalhes – mas de uma coisa tem certeza: “O carro era um Peugeot 205 GTI de três portas, vermelho”. Mais de 500 pessoas morreram nas estradas da Suécia naquele ano, mas esta tragédia assinalou um ponto de viragem na forma como Tingvall, e eventualmente o mundo, encaravam os acidentes rodoviários. Estima-se que 1,2 milhões de vidas sejam ceifadas por colisões rodoviárias em todo o mundo todos os anos, enquanto outros milhões sofrem frequentemente lesões que alteram as suas vidas. Embora o número de mortos tenha diminuído ligeiramente ao longo dos últimos 13 anos – o número de vítimas mortais nas estradas mundiais é 5% inferior ao de 2010, segundo a Organização Mundial de Saúde (OMS) – o progresso tem sido lento e fica muito aquém do esperado. A meta da OMS de reduzir para metade o número de mortes nas estradas até ao final desta década. Hoje, a Suécia tem algumas das taxas de mortalidade rodoviária mais baixas do mundo, e a história de como o país se esforçou para reduzir esse número a zero fornece uma lição para outros países onde o número de mortes permaneceu teimosamente elevado. Em 1995, Tingvall tornou-se chefe de segurança rodoviária da Administração Rodoviária Sueca. Ele estava muito bem qualificado para o papel, mas muito diferente de qualquer um de seus antecessores. Em vez de ascender na hierarquia de engenheiros e burocratas de transporte rodoviário, Tingvall tinha formação médica: estudou no renomado Instituto Karolinska, onde obteve o doutorado em epidemiologia de lesões.'
AZORES_EN = 'Akin to France\'s heartier, spicier, richer boeuf bourguignon, "alcatra" is synonymous with a single island in the remote Azores archipelago. The Azores, an archipelago of nine islands belonging to Portugal and located roughly between Europe and the US, are cow country. They\'re said to be home to more cattle than people, and despite being home to less than 3% of Portugal\'s population, the islands produce 30% of Portugal\'s dairy products and 13% of its beef. Beef is part of everyday life in the Azores, and come spring on one particular island, the ingredient even crosses paths with religion. In the days following Easter, Azorean people kick off a series of religious celebrations called Festas do Espírito Santo (Festivals of the Holy Spirit). During the 13th Century, a Catholic sect called the Cult of the Holy Spirit predicted a utopian era on Earth. This fringe faith was discouraged in mainland Europe but lived on in these remote islands in the middle of the Atlantic Ocean. The sect was also promoted by Portuguese queen Elizabeth of Aragon (also known as Elizabeth of Portugal), who was known for her charity. Over the subsequent centuries, a series of festivals emerged on the Azores that blended these utopian aspirations with the queen\'s alleged generosity. Between Easter and the week following Whitsunday, a total of eight weeks, the islands host a series of parades and other cultural and religious festivals that revolve around brightly coloured community houses called impérios. During this time, the community houses also collect donations from locals, which is then redistributed to people in the form of bread, beef and wine. These three elements generally come together in the form of a soup, called sopa do Espírito Santo, that\'s served at the impérios during the festivals. But on the island of Terceira, locals combine these ingredients in a different and delicious way, one that\'s become synonymous with the island\'s culinary identity. Austin Bush The Festas do Espírito Santo revolve around community houses called impérios (Credit: Austin Bush)Austin Bush The Festas do Espírito Santo revolve around community houses called impérios (Credit: Austin Bush) "People eat alcatra year round, but especially during the celebrations in spring and summer," explains Duarte Fournier. He is the Grand Master of the Brotherhood of Alcatra, a culinary fraternity on Terceira, and is telling me about the island\'s signature dish: cuts of beef braised in local wine, smoked pork fat and dried spices, resulting in something of a heartier, spicier, richer version of France\'s famed boeuf bourguignon. We\'re sitting at a cafe in Angra do Heroísmo, Terceira\'s largest city, and as we chat, children race to and from a nearby império delivering massive trays of raw beef to neighbours. Fournier tells me that alcatra likely has its origins in northern Portugal, where there\'s a tradition of baking goat in wine. "We don\'t know why it\'s called alcatra," he says. "We suppose it\'s from Arabic. Al catar means \'small pieces of meat\'." According to Fournier, alcatra differs from mainland Portugal\'s baked meat dishes in that it includes dried spices, generally allspice and black peppercorns, but also sometimes clove or cinnamon.'
AZORES_PT = 'Semelhante ao boeuf bourguignon mais vigoroso, picante e rico da França, "alcatra" é sinônimo de uma única ilha no remoto arquipélago dos Açores. Os Açores, um arquipélago de nove ilhas pertencentes a Portugal e localizado aproximadamente entre a Europa e os EUA, são um país de vacas. Diz-se que abrigam mais gado do que pessoas e, apesar de abrigarem menos de 3% da população de Portugal, as ilhas produzem 30% dos produtos lácteos de Portugal e 13% da sua carne bovina. A carne bovina faz parte do quotidiano dos Açores e, quando chega a primavera numa determinada ilha, o ingrediente cruza até com a religião. Nos dias seguintes à Páscoa, os açorianos dão início a uma série de celebrações religiosas denominadas Festas do Espírito Santo. Durante o século 13, uma seita católica chamada Culto do Espírito Santo previu uma era utópica na Terra. Esta fé marginal foi desencorajada na Europa continental, mas sobreviveu nestas ilhas remotas no meio do Oceano Atlântico. A seita também foi promovida pela rainha portuguesa Isabel de Aragão (também conhecida como Isabel de Portugal), que era conhecida pela sua caridade. Ao longo dos séculos seguintes, surgiu nos Açores uma série de festivais que misturavam estas aspirações utópicas com a alegada generosidade da rainha. Entre a Páscoa e a semana seguinte ao Domingo de Pentecostes, num total de oito semanas, as ilhas acolhem uma série de desfiles e outros festivais culturais e religiosos que giram em torno de casas comunitárias de cores vivas chamadas impérios. Durante esse período, as casas comunitárias também arrecadam doações dos moradores, que depois são redistribuídas às pessoas na forma de pão, carne e vinho. Estes três elementos juntam-se geralmente na forma de uma sopa, chamada sopa do Espírito Santo, que é servida nos impérios durante as festas. Mas na ilha Terceira os cariocas combinam estes ingredientes de uma forma diferente e deliciosa, que se tornou sinónimo da identidade culinária da ilha. Austin Bush As Festas do Espírito Santo giram em torno de casas comunitárias chamadas impérios (Crédito: Austin Bush)Austin Bush As Festas do Espírito Santo giram em torno de casas comunitárias chamadas impérios (Crédito: Austin Bush) "As pessoas comem alcatra o ano todo, mas principalmente durante as comemorações na primavera e no verão", explica Duarte Fournier. Ele é o Grão-Mestre da Irmandade de Alcatra, uma fraternidade culinária da Terceira, e está me contando sobre o prato característico da ilha: cortes de carne refogados no vinho local, gordura de porco defumada e especiarias secas, resultando em um prato mais forte e picante. , versão mais rica do famoso boeuf bourguignon da França. Estamos sentados num café em Angra do Heroísmo, a maior cidade da Terceira, e enquanto conversamos, crianças correm de e para um império próximo, entregando enormes bandejas de carne crua aos vizinhos. Fournier disse-me que a alcatra provavelmente tem a sua origem no norte de Portugal, onde existe uma tradição de assar cabra no vinho. “Não sabemos por que se chama alcatra”, diz ele. "Supomos que seja do árabe. Al catar significa \'pequenos pedaços de carne\'." Segundo Fournier, a alcatra difere dos pratos de carne assada de Portugal continental por incluir especiarias secas, geralmente pimenta da Jamaica e pimenta preta, mas por vezes também cravo ou canela.'
ENERGY_EN = "The transition to renewable energy has accelerated faster than most analysts predicted a decade ago, but the grid infrastructure built for centralized fossil fuel plants was never designed for the variability of wind and solar power. Solar panels generate electricity only when the sun is shining, and wind turbines only when the wind is blowing within a usable speed range, which means a grid dominated by renewables needs some way to smooth out the gaps between generation and demand.\n\nBattery storage has emerged as the leading solution for short-duration gaps, typically covering a few hours to a full day of mismatch between supply and demand. Lithium-ion batteries, the same chemistry used in electric vehicles, dominate grid-scale storage today because manufacturing costs have fallen by more than 80% over the past decade, driven largely by the scale of EV battery production. A single large grid-scale battery installation can now store hundreds of megawatt-hours, enough to power tens of thousands of homes for several hours during an evening demand peak after solar generation has dropped off.\n\nHowever, batteries alone cannot solve the longer seasonal mismatch between renewable generation and demand — a region with strong summer solar generation but limited wind may still face a shortfall during a cloudy, low-wind week in winter. For these longer gaps, utilities are exploring a mix of technologies: pumped hydro storage, which uses excess electricity to pump water uphill and releases it through turbines when needed; green hydrogen, produced by using renewable electricity to split water and stored for later use in fuel cells or turbines; and demand-response programs that pay large industrial users to reduce consumption during shortfalls rather than building additional generation capacity to cover rare peak events.\n\nGrid operators also face a technical challenge unrelated to storage: frequency stability. Traditional power plants use large spinning turbines that provide natural inertia, helping the grid absorb sudden mismatches between supply and demand without a frequency collapse. Solar panels and many wind turbines connect to the grid through power electronics rather than directly spinning turbines, so they don't provide this inertia naturally. Grid operators are increasingly deploying synthetic inertia systems and grid-forming inverters to replicate this stabilizing effect as the share of renewable generation grows.\n\nThe economics have shifted decisively in favor of renewables plus storage compared to new fossil fuel generation in most markets, but the transition still requires substantial investment in transmission infrastructure, since the best wind and solar resources are often located far from the population centers that consume the electricity. Building new high-voltage transmission lines can take a decade or more due to permitting and land-use disputes, which has become one of the primary bottlenecks slowing the pace of decarbonization, even as the cost of the generation and storage technology itself continues to fall."
COFFEE_PT = 'A produção de café no Brasil enfrenta um desafio crescente com as mudanças climáticas, que já estão alterando os padrões históricos de temperatura e chuva nas principais regiões produtoras do país. O Brasil é, de longe, o maior produtor mundial de café, respondendo por aproximadamente um terço da oferta global, e a maior parte dessa produção está concentrada em estados como Minas Gerais, Espírito Santo e São Paulo, regiões que historicamente oferecem o equilíbrio ideal entre altitude, temperatura e regime de chuvas para o cultivo do grão arábica.\n\nNos últimos anos, produtores relatam um aumento na frequência de eventos climáticos extremos: geadas fora de época, veranicos prolongados durante o período de floração e chuvas concentradas em janelas de tempo mais curtas do que o normal. Cada um desses eventos afeta a lavoura de maneira diferente. Uma geada tardia pode destruir folhas e ramos inteiros de uma safra que estava se desenvolvendo normalmente, enquanto um veranico durante a floração compromete diretamente a formação dos frutos, reduzindo a produtividade mesmo quando a planta sobrevive sem danos visíveis.\n\nPesquisadores da Embrapa e de universidades agrícolas têm investido no desenvolvimento de variedades de café mais resistentes ao estresse térmico e hídrico, cruzando linhagens tradicionais com variedades que naturalmente toleram condições mais adversas. Esse trabalho de melhoramento genético é lento — leva tipicamente entre oito e doze anos para uma nova variedade sair do laboratório e chegar de forma confiável às lavouras comerciais — o que cria uma defasagem preocupante entre a velocidade das mudanças climáticas observadas e a velocidade com que a produção consegue se adaptar a elas.\n\nOutra frente de adaptação é a migração geográfica da produção. Algumas regiões que antes eram consideradas marginais para o cultivo de café, por serem frias ou de altitude elevada demais, começaram a se tornar viáveis à medida que as temperaturas médias sobem, enquanto regiões tradicionalmente produtoras enfrentam temperaturas cada vez mais próximas do limite tolerável pela planta. Esse deslocamento gradual da fronteira produtiva já é visível em partes do sul de Minas Gerais e em áreas mais altas do Espírito Santo, onde produtores relatam colheitas de melhor qualidade nos últimos anos, justamente conforme o clima da região se torna mais parecido com o que antes caracterizava zonas mais frias.\n\nCooperativas de pequenos produtores, que respondem por uma parcela significativa da produção nacional, tendem a ser as mais vulneráveis a esses choques climáticos, já que geralmente não têm acesso a sistemas de irrigação, seguro agrícola ou reservas financeiras para absorver uma safra perdida. Programas de assistência técnica e linhas de crédito voltadas especificamente para adaptação climática têm crescido nos últimos anos, mas especialistas do setor apontam que o ritmo de expansão desses programas ainda está aquém da urgência do problema, especialmente para produtores em regiões mais isoladas com acesso limitado a extensão rural.'
gradio_examples = [
[SWEDEN_EN, 0.3, "Global road traffic death statistics and the WHO's target to halve them."],
[SWEDEN_PT, 0.6, "A carreira medica de Claes Tingvall e sua nomeacao na Suecia."],
[AZORES_EN, 0.4, "The religious festivals and traditions behind the alcatra dish."],
[AZORES_PT, 0.7, "Os ingredientes e o modo de preparo tradicional da alcatra."],
[ENERGY_EN, 0.5, "Challenges of grid-scale battery storage for renewable energy."],
[COFFEE_PT, 0.45, "O impacto das mudancas climaticas na producao de cafe no Brasil."],
]
gradio_title = "Semantic Compression [ English / Portuguese ]"
gradio_description = "Provide a text and the system will compress it, trying to preserve the original meaning. The system uses semantic embeddings to compress the text. The word reduction factor controls how much the text will be compressed. The higher the value, the more compressed the text will be. Optionally, provide a reference text to steer the compression towards a specific angle or subtopic within the input."
reduction_factor = gr.Slider(
minimum=0.1,
maximum=0.9,
value=0.5,
step=0.05,
interactive=True,
label="Reduction Factor"
)
# Create the gradio interface
gr.Interface(
fn=predict,
inputs=[
gr.Textbox(lines=10, label="Input Text"),
reduction_factor,
gr.Textbox(lines=5, label="Reference text to steer compression (Optional)", placeholder="Enter reference text to steer compression towards this text")
],
outputs=[gr.Textbox(label="Compressed Text")],
title=gradio_title,
description=gradio_description,
examples=gradio_examples,
flagging_mode="never"
).launch()
|