Spaces:
Sleeping

File size: 5,078 Bytes
156c42a
371b411
0190edb
156c42a
 
 
 
 
 
 
 
c6b3038
 
 
 
 
 
 
 
 
 
 
156c42a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c4d593
e2d1576
1e6920a
156c42a
9e41e17
 
 
 
 
 
156c42a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4588c59
 
156c42a
 
 
 
 
 
 
 
c6b3038
156c42a
 
 
 
 
 
4588c59
156c42a
 
c6b3038
156c42a
 
 
0190edb
9e41e17
156c42a
 
 
 
 
 
 
 
c6b3038
 
 
156c42a
 
 
 
 
 
 
 
 
 
 
 
 
 
c6b3038
 
 
 
 
 
 
 
 
156c42a
 
 
 
 
 
 
 
 
9e41e17
c6b3038
0190edb
c08f4a8
c6b3038
9e41e17
 
 
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import os
import sys
import warnings
import streamlit as st
import requests
import torch
import requests
from bs4 import BeautifulSoup
from transformers import pipeline, AutoTokenizer

#left_column, right_column = st.columns(2)
device = -1
try:
    if torch.cuda.is_available() and False:
        print("GPU is available")
        device = 0
except Exception as e:
    exc_type, exc_value, tb = sys.exc_info()
    warnings.warn(exc_type, exc_value)
    print("problem getting GPU ")
if device == -1:
    print("GPU not available!")
url="https://text.npr.org"
def get_headlines_links():
    global links
    global url
    # creating requests object
    html = requests.get(url).content

    # creating soup object
    soup = BeautifulSoup(html, 'html.parser')
    items = []
    for a in soup.find_all('a', href=True):
        href = a['href']
        if href.startswith("http"):
            continue
        atext = a.text
        items.append({"href": href, "text": atext})
    headlines = [a["text"] for a in items]
    links = [a["href"] for a in items]
    return headlines, links

def get_paragraphs(soup):
    # creating soup object

    for a in soup.findAll('a'):
        a.replaceWithChildren()
    paras = soup.find_all("p")
    pstart = 0
    for i, p in enumerate(paras):
        if p.text.startswith("By"):
            pstart = i+2
            break
    return paras, pstart

def get_hindex(headlines):
    global url
    st.write("\n")
    st.write("NPR news story summarizer\n")
    sbox = st.selectbox(f"Pick a headline here from NPR and get a summary below",
                         options=headlines)
    hindex = headlines.index(sbox)
    paras, pstart = get_story(hindex)
    #st.text(paras)
    return hindex



def get_story(index):
    global links
    npr = "https://text.npr.org/"
    url = npr + links[index]
    html = requests.get(url).content
    soup = BeautifulSoup(html, 'html.parser')
    paras, pstart = get_paragraphs(soup)

    return paras, pstart
    # return paras
    # chunks = chunkify(paras, pstart)
    # summary = summarize_chunks(chunks)
    # return summarya

def chunkify(paras, pstart):
    global pipe
    #print(paras)
    SOFT_MAX_WORDS = int(0.65 * pipe.model.config.max_position_embeddings)
    HARD_MAX_TOKENS = int(0.95* pipe.model.config.max_position_embeddings)
    cur_p = pstart
    num_tokens = 0
    chunks = []
    max_p = len(paras)
    long_text = ''
    while num_tokens < HARD_MAX_TOKENS and cur_p < max_p:
        ptext = paras[cur_p].text
        cur_long = long_text + ptext
        tokens = pipe.tokenizer(cur_long)
        num_tokens = len(tokens.input_ids)
        if num_tokens < HARD_MAX_TOKENS:
            long_text = cur_long
            cur_p += 1
            continue
        else:
            if long_text == '': # first paragraph
                words = ptext.split(' ')
                long_text = " ".join(words[:SOFT_MAX_WORDS])
                tokens = pipe.tokenizer(long_text)
                num_tokens = len(tokens.input_ids)
                cur_p += 1
                if num_tokens > HARD_MAX_TOKENS:
                   warnings.warn("paragraph too large, tokens:  {num_tokens}")
        #print(f" cur_p {cur_p} tokens {len(tokens.input_ids)} ")
        chunks.append(long_text)
        long_text = ''
        num_tokens = 0
    # do last chunk if there is one.
    if cur_p == max_p:
        chunks.append(long_text)

    return chunks
# be careful, pipe is a global but also passed as a param
#  why am I doing that.
def summarize_chunks(chunks, pipe):
    full_summary = ''
    try:
        for ci, chunk in enumerate(chunks):
            psummary = pipe(chunk, max_length=140, min_length=20, do_sample=False)
            psummary = psummary[0]["summary_text"]
            full_summary += psummary
    except Exception:
        exc_type, exc_val, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        msg = f"{exc_type} {exc_val} {fname} {exc_tb.tb_lineno}"
        print(msg)
        raise RuntimeError(msg)
    return full_summary
if True:
    try:
        model = "facebook/bart-large-cnn"
        pipe = pipeline("summarization", device=device, model=model)
    except Exception:
        exc_type, exc_value, tb = sys.exc_info()
        msg = f"{exc_type} \n {exc_value}"
        warnings.warn(msg)
        raise RuntimeError("could not create pipeline")
        print("done")
if True:
    headlines, links = get_headlines_links()
    hindex = get_hindex(headlines)
    paras, pstart = get_story(hindex)
    ptext = [p.text for p in paras[pstart:]]
    output = "\n".join(ptext)
    with st.container(border=True):
        st.subheader("Full Story")
        st.text_area(" ",output, height=400)
    chunks = chunkify(paras, pstart)
    #chunks = chunkify(paras, pstart)
    if device == -1:
        st.write("\nbe patient, no GPU, this might take some time on the CPU\n")
    summary = summarize_chunks(chunks, pipe)
    with st.container(border=True):
        st.subheader("Summary")
        st.text_area(" ",summary, height=200)