Suzana commited on
Commit
9f12c8a
·
verified ·
1 Parent(s): d0baea5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -28
app.py CHANGED
@@ -1,47 +1,31 @@
1
  import gradio as gr
2
  from transformers import pipeline
3
 
4
- # Use a global variable to lazy-load the model only when first called
5
  classifier = None
6
 
7
- def get_classifier():
8
  global classifier
 
9
  if classifier is None:
10
  classifier = pipeline(
11
  "text-classification",
12
  model="j-hartmann/emotion-english-roberta-large",
13
  return_all_scores=True,
 
14
  )
15
- return classifier
16
-
17
- def classify_emotion(text: str):
18
- clf = get_classifier()
19
- # returns list of {label, score}
20
- scores = clf(text)[0]
21
  return {item["label"]: float(item["score"]) for item in scores}
22
 
23
- # Build the Gradio interface
24
  iface = gr.Interface(
25
  fn=classify_emotion,
26
- inputs=gr.Textbox(
27
- lines=2,
28
- placeholder="Type any English sentence here…",
29
- label="Input Text"
30
- ),
31
- outputs=gr.Label(
32
- num_top_classes=6,
33
- label="Emotion Probabilities"
34
- ),
35
- examples=[
36
- ["I love you!"],
37
- ["The movie was heart breaking!"]
38
- ],
39
  title="English Emotion Classifier",
40
  description=(
41
- "Predicts one of Ekman's 6 basic emotions plus neutral "
42
- "(anger 🤬, disgust 🤢, fear 😨, joy 😀, neutral 😐, "
43
- "sadness 😭, surprise 😲)."
44
  )
45
- )
46
-
47
- # DO NOT call iface.launch() in Hugging Face Spaces
 
1
  import gradio as gr
2
  from transformers import pipeline
3
 
4
+ # Global variable for the classifier
5
  classifier = None
6
 
7
+ def classify_emotion(text: str):
8
  global classifier
9
+ # Load model on first request
10
  if classifier is None:
11
  classifier = pipeline(
12
  "text-classification",
13
  model="j-hartmann/emotion-english-roberta-large",
14
  return_all_scores=True,
15
+ device_map="auto" # automatically uses GPU if available
16
  )
17
+ scores = classifier(text)[0]
 
 
 
 
 
18
  return {item["label"]: float(item["score"]) for item in scores}
19
 
20
+ # Gradio interface
21
  iface = gr.Interface(
22
  fn=classify_emotion,
23
+ inputs=gr.Textbox(lines=2, placeholder="Type any English sentence…"),
24
+ outputs=gr.Label(num_top_classes=6),
25
+ examples=[["I love you!"], ["The movie was heart breaking!"]],
 
 
 
 
 
 
 
 
 
 
26
  title="English Emotion Classifier",
27
  description=(
28
+ "Predicts one of Ekman's 6 basic emotions plus neutral:\n"
29
+ "anger 🤬, disgust 🤢, fear 😨, joy 😀, neutral 😐, sadness 😭, surprise 😲"
 
30
  )
31
+ )