Spaces:
Sleeping
Sleeping
add summarizer files
Browse files- README.md +45 -14
- app.py +144 -0
- requirements.txt +4 -0
README.md
CHANGED
|
@@ -1,14 +1,45 @@
|
|
| 1 |
-
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
app_file: app.py
|
| 9 |
-
pinned: false
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Resumidor de Texto BERT2BERT
|
| 3 |
+
emoji: 📝
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: green
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 4.44.1
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# 📝 Resumidor de Texto (BERT2BERT)
|
| 13 |
+
|
| 14 |
+
Resume textos largos en español usando el modelo **BERT2BERT** con técnica de micro-chunking.
|
| 15 |
+
|
| 16 |
+
## Modelo
|
| 17 |
+
|
| 18 |
+
- **Nombre:** `mrm8488/bert2bert_shared-spanish-finetuned-summarization`
|
| 19 |
+
- **Tipo:** Encoder-Decoder (BERT2BERT)
|
| 20 |
+
- **Idioma:** Español
|
| 21 |
+
|
| 22 |
+
## API
|
| 23 |
+
|
| 24 |
+
Este espacio expone una API que puede ser usada con Gradio Client o Daggr:
|
| 25 |
+
|
| 26 |
+
```python
|
| 27 |
+
from gradio_client import Client
|
| 28 |
+
|
| 29 |
+
client = Client("tu-usuario/summarizer")
|
| 30 |
+
result = client.predict(texto="Tu texto largo aquí...")
|
| 31 |
+
print(result)
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
## Uso con Daggr
|
| 35 |
+
|
| 36 |
+
```python
|
| 37 |
+
from daggr import GradioNode
|
| 38 |
+
|
| 39 |
+
summarizer = GradioNode(
|
| 40 |
+
"tu-usuario/summarizer",
|
| 41 |
+
api_name="/predict",
|
| 42 |
+
inputs={"texto": gr.Textbox()},
|
| 43 |
+
outputs={"resumen": gr.Textbox()},
|
| 44 |
+
)
|
| 45 |
+
```
|
app.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Espacio de Hugging Face: Resumidor de Texto (BERT2BERT)
|
| 3 |
+
========================================================
|
| 4 |
+
Modelo: mrm8488/bert2bert_shared-spanish-finetuned-summarization
|
| 5 |
+
|
| 6 |
+
Entrada: Texto largo en español
|
| 7 |
+
Salida: Texto resumido
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import gradio as gr
|
| 11 |
+
import torch
|
| 12 |
+
from transformers import BertTokenizerFast, EncoderDecoderModel
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class SummarizationService:
|
| 16 |
+
def __init__(self):
|
| 17 |
+
ckpt = "mrm8488/bert2bert_shared-spanish-finetuned-summarization"
|
| 18 |
+
self.device = torch.device("cpu")
|
| 19 |
+
|
| 20 |
+
print(f"Cargando modelo BERT2BERT: {ckpt}...")
|
| 21 |
+
self.tokenizer = BertTokenizerFast.from_pretrained(ckpt)
|
| 22 |
+
self.model = EncoderDecoderModel.from_pretrained(
|
| 23 |
+
ckpt,
|
| 24 |
+
low_cpu_mem_usage=False,
|
| 25 |
+
use_safetensors=False,
|
| 26 |
+
torch_dtype=torch.float32,
|
| 27 |
+
)
|
| 28 |
+
self.model.eval()
|
| 29 |
+
print("Modelo cargado correctamente.")
|
| 30 |
+
|
| 31 |
+
def summarize(self, text: str) -> str:
|
| 32 |
+
"""Resume el texto usando micro-chunking para manejar textos largos."""
|
| 33 |
+
text = text.replace("\n", " ").strip()
|
| 34 |
+
|
| 35 |
+
gen_params = {
|
| 36 |
+
"min_length": 25,
|
| 37 |
+
"max_length": 100,
|
| 38 |
+
"num_beams": 4,
|
| 39 |
+
"length_penalty": 2.0,
|
| 40 |
+
"no_repeat_ngram_size": 3,
|
| 41 |
+
"early_stopping": True
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
chunks = self._chunk_text(text, max_tokens=200)
|
| 45 |
+
summaries = []
|
| 46 |
+
|
| 47 |
+
for chunk in chunks:
|
| 48 |
+
inputs = self.tokenizer(
|
| 49 |
+
[chunk],
|
| 50 |
+
padding="max_length",
|
| 51 |
+
truncation=True,
|
| 52 |
+
max_length=512,
|
| 53 |
+
return_tensors="pt"
|
| 54 |
+
)
|
| 55 |
+
input_ids = inputs["input_ids"].to(self.device)
|
| 56 |
+
attention_mask = inputs["attention_mask"].to(self.device)
|
| 57 |
+
|
| 58 |
+
with torch.no_grad():
|
| 59 |
+
output_ids = self.model.generate(
|
| 60 |
+
input_ids=input_ids,
|
| 61 |
+
attention_mask=attention_mask,
|
| 62 |
+
**gen_params
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
summary_piece = self.tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
| 66 |
+
if summary_piece.strip():
|
| 67 |
+
summaries.append(summary_piece.strip())
|
| 68 |
+
|
| 69 |
+
return " ".join(summaries)
|
| 70 |
+
|
| 71 |
+
def _chunk_text(self, text: str, max_tokens: int) -> list:
|
| 72 |
+
"""Divide el texto en fragmentos manejables para BERT."""
|
| 73 |
+
sentences = text.split('. ')
|
| 74 |
+
chunks = []
|
| 75 |
+
current_chunk = []
|
| 76 |
+
current_length = 0
|
| 77 |
+
|
| 78 |
+
for sentence in sentences:
|
| 79 |
+
sentence = sentence.strip()
|
| 80 |
+
if not sentence:
|
| 81 |
+
continue
|
| 82 |
+
|
| 83 |
+
tokens = self.tokenizer.tokenize(sentence)
|
| 84 |
+
sent_len = len(tokens)
|
| 85 |
+
|
| 86 |
+
if sent_len > max_tokens:
|
| 87 |
+
if current_chunk:
|
| 88 |
+
chunks.append(". ".join(current_chunk) + ".")
|
| 89 |
+
current_chunk = []
|
| 90 |
+
current_length = 0
|
| 91 |
+
chunks.append(sentence + ".")
|
| 92 |
+
continue
|
| 93 |
+
|
| 94 |
+
if current_length + sent_len > max_tokens:
|
| 95 |
+
chunks.append(". ".join(current_chunk) + ".")
|
| 96 |
+
current_chunk = [sentence]
|
| 97 |
+
current_length = sent_len
|
| 98 |
+
else:
|
| 99 |
+
current_chunk.append(sentence)
|
| 100 |
+
current_length += sent_len
|
| 101 |
+
|
| 102 |
+
if current_chunk:
|
| 103 |
+
chunks.append(". ".join(current_chunk) + ".")
|
| 104 |
+
|
| 105 |
+
return chunks
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# Inicializar servicio
|
| 109 |
+
print("Inicializando servicio de resumen...")
|
| 110 |
+
service = SummarizationService()
|
| 111 |
+
print("Servicio listo.")
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def resumir_texto(texto: str) -> str:
|
| 115 |
+
"""Función principal para Gradio."""
|
| 116 |
+
if not texto or not texto.strip():
|
| 117 |
+
return "Por favor, introduce un texto para resumir."
|
| 118 |
+
|
| 119 |
+
try:
|
| 120 |
+
resumen = service.summarize(texto)
|
| 121 |
+
return resumen
|
| 122 |
+
except Exception as e:
|
| 123 |
+
return f"Error al resumir: {str(e)}"
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# Interfaz Gradio
|
| 127 |
+
iface = gr.Interface(
|
| 128 |
+
fn=resumir_texto,
|
| 129 |
+
inputs=gr.Textbox(
|
| 130 |
+
lines=10,
|
| 131 |
+
placeholder="Pega aquí tu texto largo en español...",
|
| 132 |
+
label="Texto a Resumir"
|
| 133 |
+
),
|
| 134 |
+
outputs=gr.Textbox(label="Resumen"),
|
| 135 |
+
title="📝 Resumidor de Texto (BERT2BERT)",
|
| 136 |
+
description="Resume textos largos en español usando el modelo BERT2BERT con técnica de micro-chunking.",
|
| 137 |
+
examples=[
|
| 138 |
+
["La inteligencia artificial es un campo de la informática que se centra en crear sistemas inteligentes. Estos sistemas pueden aprender de la experiencia y realizar tareas como reconocimiento de voz y toma de decisiones. El aprendizaje automático permite a las computadoras mejorar su rendimiento a través de la experiencia."]
|
| 139 |
+
],
|
| 140 |
+
flagging_mode="never",
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
if __name__ == "__main__":
|
| 144 |
+
iface.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=4.0.0
|
| 2 |
+
torch
|
| 3 |
+
transformers
|
| 4 |
+
sentencepiece
|