import gradio as gr
from transformers import pipeline
import torch


model_name = 'google/pegasus-cnn_dailymail'
summarization_model = pipeline('summarization', model=model_name, tokenizer=model_name, device=0 if torch.cuda.is_available() else -1)

def generate_abstractive_summary(text, type, min_len=120, max_len=512, **kwargs):
    text = text.strip().replace("\n", " ")
    if type == "top_p":
        text = summarization_model(text, min_length=min_len,
                                   max_length=max_len,
                                   top_k=50, top_p=0.95, clean_up_tokenization_spaces=True, truncation=True, **kwargs)
    elif type == "greedy":
        text = summarization_model(text, min_length=min_len,
                                   max_length=max_len, clean_up_tokenization_spaces=True, truncation=True, **kwargs)
    elif type == "top_k":
        text = summarization_model(text, min_length=min_len, max_length=max_len, top_k=50,
                                   clean_up_tokenization_spaces=True, truncation=True, **kwargs)
    elif type == "beam":
        text = summarization_model(text, min_length=min_len,
                                   max_length=max_len,
                                   clean_up_tokenization_spaces=True, truncation=True, **kwargs)
    summary = text[0]['summary_text'].replace("<n>", " ")

    return summary

def sentiment_analysis(text):
    summary_content = generate_abstractive_summary(text, type="beam", do_sample=True, num_beams=15,no_repeat_ngram_size=4)

    return summary_content 

demo = gr.Interface(fn=sentiment_analysis, 
                    inputs='text',
                    outputs='text',
                    examples=[['The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side. During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest man-made structure in the world, a title it held for 41 years until the Chrysler Building in New York City was finished in 1930. It was the first structure to reach a height of 300 metres. Due to the addition of a broadcasting aerial at the top of the tower in 1957, it is now taller than the Chrysler Building by 5.2 metres (17 ft). Excluding transmitters, the Eiffel Tower is the second tallest free-standing structure in France after the Millau Viaduct.']],
                    title = "摘要"
                    )


if __name__ == "__main__":
    demo.queue(concurrency_count=3)
    demo.launch(server_name = "0.0.0.0", server_port = 7028)
