Spaces:
Sleeping
Sleeping
Download app.py from Pavan97/EA_US_Pavan: direct link, hf CLI and curl.
- Browser
- Download file 2.36 kB
-
https://huggingface.co/spaces/Pavan97/EA_US_Pavan/resolve/main/app.py
- Command line
-
hf download hf://spaces/Pavan97/EA_US_Pavan/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Pavan97/EA_US_Pavan/resolve/main/app.py
2.36 kB
| import gradio as gr | |
| import spaces | |
| import torch | |
| from transformers import ( | |
| AutoTokenizer, | |
| AutoModelForSequenceClassification | |
| ) | |
| MODEL_ID = "Pavan97/pavan_EA_us_latest" | |
| THRESHOLD = 0.25 | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) | |
| model = AutoModelForSequenceClassification.from_pretrained( | |
| MODEL_ID | |
| ) | |
| model.eval() | |
| def predict_emotions(text): | |
| if not text or not text.strip(): | |
| return {}, "Please enter some text." | |
| device = torch.device( | |
| "cuda" if torch.cuda.is_available() else "cpu" | |
| ) | |
| model.to(device) | |
| inputs = tokenizer( | |
| text, | |
| return_tensors="pt", | |
| truncation=True, | |
| max_length=256 | |
| ).to(device) | |
| with torch.inference_mode(): | |
| logits = model(**inputs).logits[0] | |
| probabilities = torch.sigmoid( | |
| logits | |
| ).cpu().tolist() | |
| scores = { | |
| model.config.id2label[i]: float(prob) | |
| for i, prob in enumerate(probabilities) | |
| } | |
| detected = { | |
| emotion: score | |
| for emotion, score in scores.items() | |
| if score >= THRESHOLD | |
| } | |
| top_five = dict( | |
| sorted( | |
| scores.items(), | |
| key=lambda item: item[1], | |
| reverse=True | |
| )[:5] | |
| ) | |
| if detected: | |
| summary = ", ".join( | |
| sorted( | |
| detected, | |
| key=detected.get, | |
| reverse=True | |
| ) | |
| ) | |
| else: | |
| summary = "No emotion exceeded the threshold." | |
| model.to("cpu") | |
| return top_five, summary | |
| demo = gr.Interface( | |
| fn=predict_emotions, | |
| inputs=gr.Textbox( | |
| lines=4, | |
| label="Enter your text", | |
| placeholder="Type something to analyze..." | |
| ), | |
| outputs=[ | |
| gr.Label( | |
| num_top_classes=5, | |
| label="Top Emotion Scores" | |
| ), | |
| gr.Textbox(label="Detected Emotions") | |
| ], | |
| title="EA US Pavan — Emotion Analysis", | |
| description=( | |
| "AI-powered emotion detection using RoBERTa. " | |
| "Recognizes 28 emotions from text." | |
| ), | |
| examples=[ | |
| ["I am excited about my new job!"], | |
| ["I feel nervous about my interview tomorrow."], | |
| ["Thank you so much for helping me!"], | |
| ["I am angry and disappointed."] | |
| ], | |
| cache_examples=False | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |