yuvarajareddy001 commited on
Commit
d443c9e
·
verified ·
1 Parent(s): a5c1bd9

fixing punkt_tab issue and updating gradio UI

Browse files
Files changed (1) hide show
  1. app.py +42 -25
app.py CHANGED
@@ -1,18 +1,14 @@
1
  import gradio as gr
2
  import os
3
- import shutil
4
- import kagglehub
5
- import pandas as pd
6
- import numpy as np
7
  import nltk
8
  import networkx as nx
 
9
  import tensorflow_hub as hub
10
- from collections import Counter
11
  from nltk.tokenize import sent_tokenize
12
- from textblob import TextBlob
13
 
14
  # Download NLTK dependencies
15
- nltk.download('punkt')
16
 
17
  # Load Universal Sentence Encoder
18
  embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
@@ -48,24 +44,45 @@ def generate_summary(text, top_n):
48
  def summarize(text, num_sentences):
49
  return generate_summary(text, num_sentences)
50
 
51
- examples = [
52
- ["""Artificial intelligence (AI) is intelligence demonstrated by machines, as opposed to the natural intelligence displayed by animals and humans. Leading AI textbooks define the field as the study of \"intelligent agents\": any system that perceives its environment and takes actions that maximize its chance of achieving its goals. AI research has explored various problem-solving techniques, including reasoning, knowledge representation, and perception. Over the years, advancements in AI have led to significant progress in areas such as speech recognition, language translation, and image analysis. Machine learning, a subset of AI, enables computers to learn from data and make predictions or decisions without being explicitly programmed. Deep learning, a specialized branch of machine learning, uses neural networks to model complex patterns in data. AI applications range from self-driving cars to medical diagnostics, revolutionizing industries worldwide. Despite its potential, AI also raises ethical concerns regarding privacy, bias, and automation-related job displacement. Researchers and policymakers are actively working on frameworks to ensure AI development aligns with human values. The future of AI remains a topic of debate, with discussions on achieving artificial general intelligence (AGI) and its implications for society. As AI continues to evolve, it is crucial to balance innovation with ethical considerations. AI-driven automation is transforming workplaces, leading to new opportunities and challenges. Understanding AI's capabilities and limitations is essential for maximizing its benefits while mitigating potential risks."""],
53
- ["""Climate change is a long-term shift in weather patterns, primarily due to human activities such as burning fossil fuels. This leads to an increase in greenhouse gases in the atmosphere, which trap heat and cause global temperatures to rise. The effects of climate change include rising sea levels, extreme weather events, and disruptions to ecosystems. Scientists have observed a significant increase in global temperatures over the past century, correlating with industrialization and deforestation. Climate change impacts agriculture, leading to food shortages and changes in crop yields. Melting polar ice caps contribute to rising sea levels, endangering coastal communities and marine biodiversity. Extreme weather conditions, such as hurricanes, wildfires, and droughts, are becoming more frequent and severe due to climate change. Governments and organizations worldwide are implementing policies to reduce carbon emissions and transition to renewable energy sources. The Paris Agreement, an international treaty, aims to limit global temperature rise and promote sustainable development. Public awareness and individual actions, such as reducing energy consumption and adopting eco-friendly practices, play a crucial role in combating climate change. Renewable energy technologies, including solar and wind power, offer sustainable alternatives to fossil fuels. Scientists continue to research innovative solutions, such as carbon capture and geoengineering, to mitigate climate change's effects. Collaboration among nations, industries, and communities is essential for achieving climate resilience and sustainability. Education and advocacy efforts are vital in encouraging climate-conscious behaviors and policy changes. Addressing climate change requires collective action and long-term commitment from all sectors of society. The future of the planet depends on proactive measures to curb emissions and protect natural resources. Sustainable living practices, conservation efforts, and technological advancements can help mitigate climate change's impact on future generations."""],
54
- ["""The history of space exploration began in the mid-20th century with the launch of Sputnik 1 by the Soviet Union. Since then, humans have landed on the Moon, sent rovers to Mars, and explored deep space with robotic missions. Space agencies, such as NASA, ESA, and Roscosmos, have played a pivotal role in advancing space exploration. The Apollo program marked a historic milestone with the first Moon landing in 1969, inspiring generations of scientists and engineers. Advancements in rocketry and satellite technology have enabled space telescopes like Hubble to capture breathtaking images of the universe. The International Space Station (ISS) serves as a hub for scientific research and international collaboration in space. Private companies, including SpaceX and Blue Origin, are revolutionizing space travel with reusable rocket technology. Plans for manned missions to Mars and lunar colonization are being developed as part of humanity's long-term space exploration goals. The search for extraterrestrial life continues through missions like the Mars rovers and deep-space probes. Space exploration contributes to technological innovations, benefiting industries on Earth, from communication to healthcare. The study of exoplanets expands our understanding of planetary systems and the potential for habitable worlds. Astronomers and physicists use space missions to study black holes, dark matter, and cosmic phenomena. The challenges of deep-space travel include radiation exposure, psychological effects, and resource sustainability. Space tourism is emerging as a new industry, allowing civilians to experience space travel firsthand. International cooperation and funding are crucial for ambitious space exploration projects. The future of space exploration involves developing sustainable habitats and harnessing space resources. Understanding space's mysteries fuels scientific curiosity and inspires future generations of explorers."""]
 
 
 
 
 
 
55
  ]
56
 
57
- # Gradio Interface
58
- demo = gr.Interface(
59
- fn=summarize,
60
- inputs=[
61
- gr.Textbox(lines=10, placeholder="Enter text to summarize"),
62
- gr.Slider(1, 10, step=1, label="Number of sentences")
63
- ],
64
- outputs="text",
65
- title="Text Summarization using Universal Sentence Encoder",
66
- description="This app generates a summary from the input text using sentence similarity and PageRank algorithm.",
67
- examples=examples
68
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- # Launch the Gradio app
71
- demo.launch()
 
1
  import gradio as gr
2
  import os
3
+ import random
 
 
 
4
  import nltk
5
  import networkx as nx
6
+ import numpy as np
7
  import tensorflow_hub as hub
 
8
  from nltk.tokenize import sent_tokenize
 
9
 
10
  # Download NLTK dependencies
11
+ nltk.download('punkt_tab')
12
 
13
  # Load Universal Sentence Encoder
14
  embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
 
44
  def summarize(text, num_sentences):
45
  return generate_summary(text, num_sentences)
46
 
47
+ random_texts = [
48
+ """Artificial intelligence (AI) is intelligence demonstrated by machines, as opposed to the natural intelligence displayed by animals and humans. AI research explores problem-solving techniques such as reasoning, perception, and knowledge representation. Over the years, advancements in AI have led to significant progress in areas like speech recognition, computer vision, and robotics. Machine learning, a subset of AI, enables systems to learn from data and make predictions. Deep learning, a more advanced technique, uses neural networks to detect complex patterns. AI applications range from self-driving cars to automated medical diagnostics. However, AI also raises ethical concerns regarding bias, privacy, and automation's impact on employment. Policymakers are working on frameworks to regulate AI while maximizing its benefits. The future of AI includes advancements in artificial general intelligence (AGI), which aims to mimic human intelligence across tasks. Companies and researchers are working towards more responsible AI development. AI-driven automation is transforming workplaces, introducing both opportunities and challenges. AI chatbots and virtual assistants are becoming increasingly common in customer service. Understanding AIs limitations is crucial to prevent misinformation and misuse. AI ethics focuses on ensuring that models make fair and unbiased decisions. AI is also being integrated into creative fields, generating music, art, and writing. Future AI systems could be capable of self-learning without human intervention. The debate on AI regulation continues as technology evolves. AI in healthcare is helping doctors diagnose diseases more accurately. Companies are investing billions in AI research to stay competitive. The rapid development of AI requires continuous monitoring and evaluation to align with human values.""",
49
+
50
+ """Climate change is a long-term shift in weather patterns, primarily driven by human activities such as burning fossil fuels. The increase in greenhouse gases traps heat, leading to rising global temperatures. Scientists have observed a drastic increase in extreme weather events, including hurricanes, droughts, and wildfires. Melting polar ice caps are causing sea levels to rise, threatening coastal communities. Climate change also affects biodiversity, leading to habitat loss for many species. Agriculture is heavily impacted, with unpredictable weather patterns affecting crop yields. Governments worldwide are implementing policies to reduce carbon emissions and promote renewable energy. The Paris Agreement is a global effort to limit temperature rise and mitigate climate effects. Public awareness and individual actions, like reducing energy consumption, are crucial in combating climate change. Scientists are developing carbon capture technology to remove CO2 from the atmosphere. The shift to electric vehicles is reducing dependency on fossil fuels. Deforestation contributes to climate change by reducing carbon absorption from trees. Many companies are adopting sustainable practices to minimize their carbon footprint. Renewable energy sources like solar and wind are becoming more accessible and affordable. Climate activists advocate for stronger regulations and accountability from large industries. The global economy is adapting to more sustainable production methods. Education plays a key role in spreading awareness about climate change. Governments are investing in climate resilience infrastructure to protect vulnerable areas. The future of climate action depends on technological innovation and international cooperation.""",
51
+
52
+ """The history of space exploration began in the mid-20th century with the launch of Sputnik 1 by the Soviet Union. This marked the beginning of the space race between the USA and USSR. The Apollo program led to the first human landing on the Moon in 1969, a defining moment in history. Since then, advancements in space technology have enabled robotic missions to explore Mars, Jupiter, and beyond. The Hubble Space Telescope has provided breathtaking images of the universe, helping astronomers understand cosmic phenomena. The International Space Station (ISS) serves as a collaborative research hub for astronauts from multiple countries. Private companies like SpaceX and Blue Origin are revolutionizing space travel with reusable rocket technology. Plans for manned missions to Mars are actively being developed, aiming for the 2030s. Space tourism is becoming a reality, with civilians now able to experience space travel. The search for extraterrestrial life continues, with rovers analyzing Martian soil for signs of microbial life. Scientists study exoplanets to determine their potential habitability. Deep-space exploration is unlocking secrets of black holes, dark matter, and the origins of the universe. The future of space travel includes plans for lunar bases and asteroid mining. Advancements in satellite technology are improving global communications and Earth monitoring. NASA and other space agencies are collaborating on ambitious interstellar projects. Space junk poses a growing problem, requiring better debris management strategies. The potential for space colonization is a topic of scientific debate and ethical consideration. Cutting-edge propulsion systems could one day allow interstellar travel. Artificial intelligence is being integrated into space missions to enhance efficiency. The discovery of water on Mars has renewed interest in the planet's potential for sustaining life.""",
53
+
54
+ """The human brain is one of the most complex structures known to science. It contains billions of neurons that communicate through electrical and chemical signals. Brain function is responsible for cognition, emotions, and motor control. Neuroscientists study the brain to understand consciousness and memory formation. Brain plasticity allows neurons to rewire and adapt to new experiences. Damage to certain brain areas can lead to cognitive disorders like Alzheimer's and Parkinson's. The field of neurotechnology is developing brain-machine interfaces that enable communication through thought. Brain scans like MRI and fMRI help researchers study brain activity in real-time. Sleep is crucial for brain function, allowing memory consolidation and cognitive restoration. Certain neurotransmitters like dopamine and serotonin regulate mood and emotions. The blood-brain barrier protects the brain from harmful substances but also limits drug delivery. Meditation and mindfulness practices have been shown to positively affect brain structure. Neurological research aims to develop treatments for conditions like depression and epilepsy. Understanding brain function could one day lead to artificial intelligence mimicking human thought processes. The debate on free will and consciousness continues in philosophical and scientific discussions. The study of dreams provides insight into subconscious thought processing. Brain injuries can have long-lasting effects on personality and cognition. Cognitive enhancement through brain stimulation is an emerging field of research. New discoveries in neuroscience continue to shape our understanding of human intelligence and behavior.""",
55
+
56
+ """Blockchain technology has revolutionized digital transactions by providing secure, decentralized record-keeping. Initially developed for Bitcoin, blockchain is now used in finance, healthcare, and logistics. The core principle of blockchain is a distributed ledger system that ensures transparency and immutability. Smart contracts automate transactions without the need for intermediaries. Cryptocurrencies like Ethereum and Bitcoin operate on blockchain networks. Decentralized finance (DeFi) is expanding financial opportunities without traditional banks. Non-fungible tokens (NFTs) use blockchain to verify ownership of digital assets. Governments are exploring the use of blockchain for secure voting systems. The security of blockchain relies on cryptographic hashing and consensus mechanisms. While highly secure, blockchain faces challenges like scalability and energy consumption. Environmental concerns have led to the development of eco-friendly consensus models. The technology is also being explored for supply chain transparency and fraud prevention. Large corporations are investing in blockchain to streamline business operations. Regulators are working to establish laws governing cryptocurrency and blockchain applications. Cross-border payments using blockchain reduce transaction fees and increase speed. Blockchain-based identity management could help eliminate identity theft. The concept of Web3 envisions a fully decentralized internet powered by blockchain. Quantum computing poses a potential threat to blockchain encryption in the future. Innovations in layer 2 scaling solutions aim to enhance blockchain efficiency. The continued evolution of blockchain is expected to transform multiple industries worldwide."""
57
  ]
58
 
59
+ def get_random_text():
60
+ return random.choice(random_texts)
61
+
62
+ def process_input(user_input, num_sentences):
63
+ return summarize(user_input, num_sentences)
64
+
65
+ def set_random_text():
66
+ return get_random_text()
67
+
68
+ def clear_fields():
69
+ return "", ""
70
+
71
+ demo = gr.Blocks()
72
+ with demo:
73
+ with gr.Row():
74
+ user_input = gr.Textbox(lines=10, placeholder="Enter text to summarize or click Generate Random Text")
75
+
76
+ num_sentences = gr.Slider(1, 10, step=1, label="Number of sentences")
77
+ output = gr.Textbox(label="Output")
78
+
79
+ with gr.Row():
80
+ generate_btn = gr.Button("Generate Random Text")
81
+ submit_btn = gr.Button("Summarize")
82
+ clear_btn = gr.Button("Clear")
83
+
84
+ generate_btn.click(set_random_text, inputs=[], outputs=[user_input])
85
+ submit_btn.click(process_input, inputs=[user_input, num_sentences], outputs=[output])
86
+ clear_btn.click(clear_fields, inputs=[], outputs=[user_input, output])
87
 
88
+ demo.launch()