Spaces:
Sleeping

File size: 3,640 Bytes
69d5ffc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
import gradio as gr
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM

# --- ZeroGPU ---
# A Hugging Face Spaces el paquet "spaces" ja ve instal·lat i dona accés a la GPU.
# En local no hi és, així que fem servir un decorador que no fa res.
try:
    import spaces
    ON_SPACES = True
except ImportError:
    ON_SPACES = False

    class spaces:
        @staticmethod
        def GPU(func=None, **kwargs):
            if func is None:
                return lambda f: f
            return func

# --- Càrrega del model (un sol cop, en arrencar l'app) ---
# A ZeroGPU s'ha de moure el model a "cuda" en arrencar; la GPU real
# s'assigna només mentre s'executa la funció marcada amb @spaces.GPU.
if ON_SPACES:
    device = "cuda"
else:
    device = "cuda" if torch.cuda.is_available() else "cpu"
# bfloat16 a GPU; float32 a CPU (més ràpid i estable a CPU)
dtype = torch.bfloat16 if device == "cuda" else torch.float32

MODEL_NAME = "ZyroGod/flan-t5-base-summarization"

tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME, dtype=dtype).to(device)
model.eval()


@spaces.GPU
def summarize(article, max_length, min_length, num_beams):
    if not article or not article.strip():
        return "Please enter some text to summarize."

    max_length, min_length, num_beams = int(max_length), int(min_length), int(num_beams)
    if min_length >= max_length:
        min_length = max(1, max_length - 10)

    input_text = "summarize: " + article.strip()
    inputs = tokenizer(
        input_text, return_tensors="pt", max_length=512, truncation=True
    ).to(device)

    with torch.no_grad():
        output_ids = model.generate(
            **inputs,
            max_length=max_length,
            min_length=min_length,
            num_beams=num_beams,
            length_penalty=2.0,
            no_repeat_ngram_size=3,
        )

    return tokenizer.decode(output_ids[0], skip_special_tokens=True)


EXAMPLE = (
    "It's hard to overstate how upset many Republicans are feeling in the wake of "
    "what has turned into a stunning defeat for the party at the polls. Most Republican "
    "acquaintances and contacts I spoke to during the day yesterday expected losses, but "
    "were cautiously optimistic that perhaps they'd be able to maintain the House of "
    "Representatives and eke out victories in races that they expected to be tight. "
    "The coming hours and days, another Republican contact told me, will involve a lot "
    "of soul searching to determine what went wrong."
)

with gr.Blocks(title="Text Summarizer") as demo:
    gr.Markdown(
        "# 📝 Text Summarizer\n"
        "Enganxa un text en **anglès** i obtén-ne un resum "
        f"(model: `{MODEL_NAME}`)."
    )

    with gr.Row():
        with gr.Column():
            article = gr.Textbox(
                label="Text (English)", lines=12, placeholder="Paste your article here..."
            )
            with gr.Accordion("Paràmetres avançats", open=False):
                max_len = gr.Slider(32, 256, value=128, step=8, label="Longitud màxima")
                min_len = gr.Slider(5, 100, value=20, step=5, label="Longitud mínima")
                beams = gr.Slider(1, 8, value=4, step=1, label="Num. beams")
            btn = gr.Button("Resumeix", variant="primary")
        with gr.Column():
            summary = gr.Textbox(label="Resum", lines=8)

    btn.click(summarize, inputs=[article, max_len, min_len, beams], outputs=summary)
    gr.Examples(examples=[[EXAMPLE]], inputs=[article])

if __name__ == "__main__":
    demo.queue().launch()