Spaces:
Sleeping

summarize / app.py
jmuller's picture
fixed issues with tokenizer, no longer global
c6b3038
Raw History Blame Contribute Delete
5.08 kB
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)