Curative's picture
Update app.py
e8f73fc verified
raw
history blame
2.32 kB
import gradio as gr
from transformers import pipeline
# Lazy‑load pipelines
sentiment = classifier = ner = summarizer = None
def get_sentiment():
global sentiment
if not sentiment:
sentiment = pipeline("sentiment-analysis",
model="distilbert-base-uncased-finetuned-sst-2-english")
return sentiment
def get_classifier():
global classifier
if not classifier:
classifier = pipeline(
"zero-shot-classification",
model="facebook/bart-large-mnli")
return classifier
def get_ner():
global ner
if not ner:
ner = pipeline("ner",
model="elastic/distilbert-base-uncased-finetuned-conll03-english",
aggregation_strategy="simple")
return ner
def get_summarizer():
global summarizer
if not summarizer:
summarizer = pipeline("summarization",
model="Curative/t5-summarizer-cnn")
return summarizer
def process(text, features):
result = {}
if "Summarization" in features:
result["summary"] = get_summarizer()(
text, max_length=150, min_length=40, do_sample=False
)[0]["summary_text"]
if "Sentiment" in features:
sent = get_sentiment()(text)[0]
result["sentiment"] = {"label": sent["label"], "score": sent["score"]}
if "Classification" in features:
candidate_labels = [
"technology", "sports", "business", "politics",
"health", "science", "travel", "entertainment"
]
cls = get_classifier()(text, candidate_labels=candidate_labels)
# Map labels → scores
result["classification"] = dict(zip(cls["labels"], cls["scores"]))
if "Entities" in features:
ents = get_ner()(text)
result["entities"] = [
{"word": e["word"], "type": e["entity_group"]} for e in ents
]
return result
with gr.Blocks() as demo:
gr.Markdown("## 🛠️ Multi‑Feature NLP Service")
inp = gr.Textbox(lines=6, placeholder="Enter your text here…")
feats = gr.CheckboxGroup(
["Summarization","Sentiment","Classification","Entities"],
label="Select features to run"
)
btn = gr.Button("Run")
out = gr.JSON(label="Results")
btn.click(process, [inp, feats], out)
demo.queue(api_open=True).launch()