Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI
|
2 |
+
from pydantic import BaseModel
|
3 |
+
from transformers import PegasusTokenizer, PegasusForConditionalGeneration
|
4 |
+
import torch
|
5 |
+
|
6 |
+
app = FastAPI()
|
7 |
+
|
8 |
+
# Load m么 h矛nh
|
9 |
+
model_name = "google/pegasus-cnn_dailymail"
|
10 |
+
tokenizer = PegasusTokenizer.from_pretrained(model_name)
|
11 |
+
model = PegasusForConditionalGeneration.from_pretrained(model_name)
|
12 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
13 |
+
model = model.to(device)
|
14 |
+
|
15 |
+
# Schema input
|
16 |
+
class InputText(BaseModel):
|
17 |
+
text: str
|
18 |
+
|
19 |
+
# H脿m t贸m t岷痶
|
20 |
+
def summarize(text: str) -> str:
|
21 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=1024)
|
22 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
23 |
+
summary_ids = model.generate(
|
24 |
+
inputs["input_ids"],
|
25 |
+
max_length=150,
|
26 |
+
min_length=60,
|
27 |
+
num_beams=4,
|
28 |
+
no_repeat_ngram_size=3,
|
29 |
+
early_stopping=True
|
30 |
+
)
|
31 |
+
return tokenizer.decode(summary_ids[0], skip_special_tokens=True)
|
32 |
+
|
33 |
+
# Route API
|
34 |
+
@app.post("/summarize")
|
35 |
+
def summarize_api(input: InputText):
|
36 |
+
return {"summary": summarize(input.text)}
|