0% found this document useful (0 votes)
4 views21 pages

Figure

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views21 pages

Figure

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

<TextView

android:id="@+id/titletxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="News Articles Summarizer"
android:layout_centerHorizontal="true"
android:textSize="24sp"
android:textStyle="bold"
android:layout_marginBottom="16dp"
android:textColor="@color/white"/>

Figure: RelativeLayout
<TextView
android:id="@+id/titletxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="News Articles Summarizer"
android:layout_centerHorizontal="true"
android:textSize="24sp"
android:textStyle="bold"
android:layout_marginBottom="16dp"
android:textColor="@color/white"/>

Figure: Title Text


<TextView
android:id="@+id/urlLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="URL"
android:textSize="16sp"
android:textStyle="bold"
android:layout_below="@id/titletxt"
android:focusable="true"
android:focusableInTouchMode="true"/>

Figure: URL Label

<EditText
android:id="@+id/urlText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/urlLabel"
android:hint="Paste Url Here"
android:textSize="14sp" />

Figure: Edit Text


<TextView
android:id="@+id/numSentencesLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number of Sentences"
android:textSize="16sp"
android:textStyle="bold"
android:layout_below="@id/urlText"
android:layout_marginBottom="2dp"/>

Figure: Summary length Label

<EditText
android:id="@+id/numSentencesEntry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:inputType="number"
android:text="2"
android:hint="Summary Length"
android:layout_below="@id/numSentencesLabel"
android:layout_marginBottom="2dp"/>

Figure: Summary Length Label


<Button
android:id="@+id/summarizeButton"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_below="@id/numSentencesEntry"
android:layout_alignParentStart="true"
android:layout_marginStart="40dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="16dp"
android:background="@drawable/button"
android:text="Summarize"
android:textColor="#ffffff"
android:cursorVisible="true"/>

Figure: Summarize Button

<Button
android:id="@+id/resetButton"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_below="@id/numSentencesEntry"
android:layout_alignParentEnd="true"
android:layout_marginStart="23dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="40dp"
android:layout_marginBottom="5dp"
android:layout_toEndOf="@+id/summarizeButton"
android:background="@drawable/resetbtn"
android:text="Reset"
android:textColor="#ffffff"
android:cursorVisible="true"/>

Figure: Reset Button


<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/summarizeButton"
android:layout_centerHorizontal="true"
android:visibility="gone"
android:layout_marginBottom="16dp"/>

Figure: Progress Bar

<TextView
android:id="@+id/feedbackLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/progressBar"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp"/>

Figure: Feedback Label


<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/summaryLabel"
android:layout_marginBottom="4dp">

<TextView
android:id="@+id/summaryText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textColor="#000000"
android:padding="8dp"
android:background="#dddddd"
android:scrollbars="vertical"/>
</ScrollView>

Figure: Scrollable Summary Text View


protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState);
setContentView(R.layout.activity_main);
titleText = findViewById(R.id.titleText);
authorText = findViewById(R.id.authorText);
publicationText = findViewById(R.id.publicationText);
summaryText = findViewById(R.id.summaryText);
sentimentText = findViewById(R.id.sentimentText);
urlText = findViewById(R.id.urlText);
numSentencesEntry = findViewById(R.id.numSentencesEntry);
progressBar = findViewById(R.id.progressBar);
feedbackLabel = findViewById(R.id.feedbackLabel);
summarizeButton = findViewById(R.id.summarizeButton);
resetButton = findViewById(R.id.resetButton);
summarizeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSummarization();
}
});
resetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
resetFields();
}
});
}

Figure: Initialize
private void resetFields() {
titleText.setText("");
authorText.setText("");
publicationText.setText("");
summaryText.setText("");
sentimentText.setText("");
urlText.setText("");
progressBar.setVisibility(View.GONE);
feedbackLabel.setText("");
}

Figure: Reset
private void startSummarization() {
progressBar.setVisibility(View.VISIBLE);
feedbackLabel.setText("Summarizing...");
new Thread(new Runnable() {
@Override
public void run() {
try {
summarizeArticle();
} catch (Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
feedbackLabel.setText("Error: " + e.getMessage());
progressBar.setVisibility(View.GONE);
}
});
}
}
}).start();
}

Figure: Start Summarization


private void summarizeArticle() throws IOException {
String url = urlText.getText().toString().trim();
if (url.isEmpty()) {
runOnUiThread(new Runnable() {
@Override
public void run() {
feedbackLabel.setText("URL cannot be empty.");
progressBar.setVisibility(View.GONE);
}
});
return;
}

int numSentences;
try {
numSentences = Integer.parseInt(numSentencesEntry.getText().toString());
} catch (NumberFormatException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
feedbackLabel.setText("Invalid number of sentences.");
progressBar.setVisibility(View.GONE);
}
});
return;
}

Document doc = Jsoup.connect(url).get();


String articleTitle = doc.title();
String articleText = "";

Figure: Summarize Article


// Try to extract the main content of the article
Elements paragraphs = doc.select("p");
for (Element paragraph : paragraphs) {
articleText += paragraph.text() + " ";
}

// Fallback if no paragraphs found


if (articleText.isEmpty()) {
articleText = doc.body().text();
}

String author = "";


String publishDate = "";
Elements metaTags = doc.getElementsByTag("meta");
for (Element metaTag : metaTags) {
String content = metaTag.attr("content");
String name = metaTag.attr("name");
if ("author".equals(name)) {
author = content;
}
if ("article:published_time".equals(metaTag.attr("property"))) {
publishDate = content;
}
}

Figure: Content Extraction


// Preprocess the article text
String summary = preprocessText(articleText, numSentences);
float polarity = analyzeSentiment(articleText);

String finalAuthor = author;


String finalPublishDate = publishDate;
runOnUiThread(new Runnable() {
@Override
public void run() {
updateGUI(articleTitle, finalAuthor, finalPublishDate, summary, polarity);
progressBar.setVisibility(View.GONE);
feedbackLabel.setText("Summarization Complete!");
}
});
}

Figure: Article Preprocess


private String preprocessText(String text, int numSentences) {
List<String> sentences = sentTokenize(text);
Map<String, Integer> wordCounts = new HashMap<>();
for (String sentence : sentences) {
String[] words = sentence.split(" ");
for (String word : words) {
wordCounts.put(word, wordCounts.getOrDefault(word, 0) + 1);
}
}
Map<Integer, Integer> sentenceWeights = new HashMap<>();
for (int i = 0; i < sentences.size(); i++) {
int weight = 0;
for (String word : sentences.get(i).split(" ")) {
weight += wordCounts.get(word);
}
sentenceWeights.put(i, weight);
}

Figure: Tokenize and Count Word Frequency

List<Integer> sortedSentences = sentenceWeights.entrySet().stream()


.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.limit(numSentences)
.map(Map.Entry::getKey)
.sorted()
.collect(Collectors.toList());
StringBuilder summary = new StringBuilder();
for (int i : sortedSentences) {
summary.append(sentences.get(i)).append(". ");
}
return summary.toString().trim();
}

Figure: Sort Sentence by Weight


private float analyzeSentiment(String text) {
int positiveScore = 0;
int negativeScore = 0;
String[] positiveWords = {
"good","win", "great", "excellent", "positive", "fortunate", "correct",
"superior", "happy", "joyful", "peaceful", "enthusiastic",
"profitable", "valuable", "amazing", "wonderful", "fantastic", "awesome",
"delightful", "pleasurable", "satisfying", "glad",
"optimistic", "content", "successful", "vibrant", "love", "lovely", "admire", "adore",
"beautiful", "beauty", "best", "blessing", "brilliant", "charming", "cheerful", "cool",
"creative", "cute", "easy", "progress", "progressive", "hope", "hopeful", "inspiring",
"ethical", "fair", "just", "transparent", "honest", "trustworthy", "reliable", "principled"
};

String[] negativeWords = {
"bad", "terrible", "poor", "negative", "unfortunate", "wrong", "inferior",
"sad", "angry", "war", "death", "awful", "horrible", "terrible", "disappointing",
"disgusting", "unpleasant", "miserable", "regretful", "dreadful",
"frustrating", "upset", "disheartening", "hate", "hateful", "angry", "annoy", "annoying",
"ashamed", "blame", "boring", "cry", "damage", "danger", "dark", "defeat", "dislike", "failure",
"fear", "corrupt", "corruption", "scandal", "dishonest", "unethical", "untrustworthy",
"deceptive", "manipulative", "biased", "partisan", "divisive", "controversial"
};

Figure: Negative And Positive Word


String[] words = text.toLowerCase().split("\\s+");
for (String word : words) {
if (Arrays.asList(positiveWords).contains(word)) {
positiveScore++;
} else if (Arrays.asList(negativeWords).contains(word)) {
negativeScore++;
}
}
int totalScore = positiveScore - negativeScore;
return (float) totalScore / words.length;
}

Figure: Count Negative and Positive Word


private void updateGUI(String title, String author, String publishDate, String
summary, float polarity) {
titleText.setText(title);
authorText.setText(author);
publicationText.setText(publishDate);

// Check if the summary ends with a period


if (!summary.endsWith(".")) {
summary += ".";
}

summaryText.setText(summary);
sentimentText.setText("Polarity: " + polarity + ", Sentiment: " + (polarity > 0
? "positive" : polarity < 0 ? "negative" : "neutral"));
}
}

Figure: GUI Update


public class MainActivityTest {
@Rule
public ActivityScenarioRule<MainActivity> activityScenarioRule = new
ActivityScenarioRule<>(MainActivity.class);

@Test
public void testSummarizeButton() {
// Test the Summarize button functionality

Espresso.onView(ViewMatchers.withId(R.id.urlText)).perform(ViewActions.type
Text
("https://edition.cnn.com/asia/live-news/india-general-election-
results-06-04-24-intl-hnk/index.html"));

Espresso.onView(ViewMatchers.withId(R.id.summarizeButton)).perform(ViewA
ctions.click());

Espresso.onView(ViewMatchers.withId(R.id.summaryText)).check(ViewAssertio
ns.matches(ViewMatchers.isDisplayed()));
}
}

Figure: UI Testing
public void testSummarization() {
// Test the summarization method with a URL as input text
String inputText = "https://edition.cnn.com/asia/live-news/india-general-
election-results-06-04-24-intl-hnk/index.html";
int numSentences = 3;

// Call the preprocessText method with the input URL and numSentences
String actualSummary = preprocessText(inputText, numSentences);

// Display a message indicating successful summarization


System.out.println("Summarization successfully completed.");

// Assert that the length of the actual summary is not zero


assertTrue("Summary length is greater than 0", actualSummary.length() > 0);
}

Figure: Test Summarization Method


private String preprocessText(String url, int numSentences) {
try {
// Scrap content from the given URL
Document doc = Jsoup.connect(url).get();
String content = doc.body().text();

// Display the scrapped content


System.out.println("Scrapped Content:");
System.out.println(content);

// Summarize the scrapped content


String summary = summarize(content, numSentences);

// Display the summary


System.out.println("\nSummary:");
System.out.println(summary);

return summary;
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
return "";
}
}

Figure: Scrapping, Summarization & Display

private String summarize(String text, int numSentences) {


String[] sentences = text.split("\\. "); // Split the text into sentences
StringBuilder summary = new StringBuilder();
for (int i = 0; i < numSentences && i < sentences.length; i++) {
summary.append(sentences[i]).append(". "); // Append the first numSentences
sentences to the summary
}
return summary.toString().trim(); // Return the summary as a string
}

Figure: Simulation Method

You might also like