Sephfox commited on
Commit
b298218
·
verified ·
1 Parent(s): 507a920

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -89
app.py CHANGED
@@ -21,113 +21,135 @@ nltk.download('vader_lexicon', quiet=True)
21
  # --- Emotion Analyzer ---
22
  class EmotionalAnalyzer:
23
  def __init__(self):
24
- self.model = AutoModelForSequenceClassification.from_pretrained(
25
- "bhadresh-savani/distilbert-base-uncased-emotion"
26
- )
27
- self.tokenizer = AutoTokenizer.from_pretrained(
28
- "bhadresh-savani/distilbert-base-uncased-emotion"
29
- )
 
 
 
 
 
30
  self.labels = ["sadness", "joy", "love", "anger", "fear", "surprise"]
31
  self.sia = SentimentIntensityAnalyzer()
32
 
33
  def predict_emotion(self, text):
34
- inputs = self.tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
35
- with torch.no_grad():
36
- outputs = self.model(**inputs)
37
- probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
38
- return self.labels[torch.argmax(probs).item()]
 
 
 
 
 
39
 
40
  def analyze(self, text):
41
- vader_scores = self.sia.polarity_scores(text)
42
- blob = TextBlob(text)
43
- blob_data = {
44
- "polarity": blob.sentiment.polarity,
45
- "subjectivity": blob.sentiment.subjectivity,
46
- "word_count": len(blob.words),
47
- "sentence_count": len(blob.sentences),
48
- }
49
- return {
50
- "emotion": self.predict_emotion(text),
51
- "vader": vader_scores,
52
- "textblob": blob_data,
53
- }
 
 
 
54
 
55
  def plot_emotions(self):
56
- simulated_emotions = {
57
- "joy": random.randint(10, 30),
58
- "sadness": random.randint(5, 20),
59
- "anger": random.randint(10, 25),
60
- "fear": random.randint(5, 15),
61
- "love": random.randint(10, 30),
62
- "surprise": random.randint(5, 20),
63
- }
64
- df = pd.DataFrame(list(simulated_emotions.items()), columns=["Emotion", "Percentage"])
65
- plt.figure(figsize=(8, 4))
66
- sns.barplot(x="Emotion", y="Percentage", data=df)
67
- plt.title("Simulated Emotional State")
68
- plt.tight_layout()
69
- path = "emotions.png"
70
- plt.savefig(path)
71
- plt.close()
72
- return path
 
 
 
73
 
74
  # --- Text Completion LLM ---
75
  tokenizer = AutoTokenizer.from_pretrained("diabolic6045/ELN-Llama-1B-base")
76
  model = AutoModelForCausalLM.from_pretrained("diabolic6045/ELN-Llama-1B-base")
77
 
78
  def generate_completion(message, temperature, max_length):
79
- inputs = tokenizer(message, return_tensors="pt", truncation=True, max_length=512)
80
- input_ids = inputs["input_ids"]
81
- current_text = message
82
-
83
- for _ in range(max_length - input_ids.shape[1]):
84
- with torch.no_grad():
85
- outputs = model(input_ids)
86
- logits = outputs.logits[:, -1, :] / temperature
87
- probs = torch.softmax(logits, dim=-1)
88
- next_token = torch.multinomial(probs, num_samples=1)
89
-
90
- if next_token.item() == tokenizer.eos_token_id:
91
- break
92
-
93
- input_ids = torch.cat([input_ids, next_token], dim=-1)
94
- new_token_text = tokenizer.decode(next_token[0], skip_special_tokens=True)
95
- current_text += new_token_text
96
- yield current_text
 
 
 
97
 
98
  # --- Emotion-Aware LLM Response ---
99
  def emotion_aware_response(input_text):
100
- analyzer = EmotionalAnalyzer()
101
- results = analyzer.analyze(input_text)
102
- image_path = analyzer.plot_emotions()
103
-
104
- prompt = (
105
- f"Input: {input_text}\n"
106
- f"Detected Emotion: {results['emotion']}\n"
107
- f"VADER Scores: {results['vader']}\n"
108
- f"Respond thoughtfully and emotionally aware:"
109
- )
110
-
111
- inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
112
- with torch.no_grad():
113
- output_ids = model.generate(
114
- inputs.input_ids,
115
- max_length=512,
116
- do_sample=True,
117
- temperature=0.7,
118
- top_k=50,
119
- top_p=0.95,
120
- pad_token_id=tokenizer.eos_token_id
 
 
 
 
 
 
 
 
 
121
  )
122
- response = tokenizer.decode(output_ids[0], skip_special_tokens=True)
123
-
124
- summary = (
125
- f"Emotion: {results['emotion']}\n"
126
- f"VADER: {results['vader']}\n"
127
- f"TextBlob: {results['textblob']}\n\n"
128
- f"LLM Response:\n{response}"
129
- )
130
- return summary, image_path
131
 
132
  # --- Gradio Interface ---
133
  with gr.Blocks(title="ELN LLaMA 1B Enhanced Demo") as app:
 
21
  # --- Emotion Analyzer ---
22
  class EmotionalAnalyzer:
23
  def __init__(self):
24
+ try:
25
+ self.model = AutoModelForSequenceClassification.from_pretrained(
26
+ "bhadresh-savani/distilbert-base-uncased-emotion"
27
+ )
28
+ self.tokenizer = AutoTokenizer.from_pretrained(
29
+ "bhadresh-savani/distilbert-base-uncased-emotion"
30
+ )
31
+ except Exception:
32
+ self.model = None
33
+ self.tokenizer = None
34
+
35
  self.labels = ["sadness", "joy", "love", "anger", "fear", "surprise"]
36
  self.sia = SentimentIntensityAnalyzer()
37
 
38
  def predict_emotion(self, text):
39
+ try:
40
+ if self.model is None or self.tokenizer is None:
41
+ raise ValueError("Model or tokenizer not initialized properly.")
42
+ inputs = self.tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
43
+ with torch.no_grad():
44
+ outputs = self.model(**inputs)
45
+ probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
46
+ return self.labels[torch.argmax(probs).item()]
47
+ except Exception:
48
+ return "Unknown"
49
 
50
  def analyze(self, text):
51
+ try:
52
+ vader_scores = self.sia.polarity_scores(text)
53
+ blob = TextBlob(text)
54
+ blob_data = {
55
+ "polarity": blob.sentiment.polarity,
56
+ "subjectivity": blob.sentiment.subjectivity,
57
+ "word_count": len(blob.words),
58
+ "sentence_count": len(blob.sentences),
59
+ }
60
+ return {
61
+ "emotion": self.predict_emotion(text),
62
+ "vader": vader_scores,
63
+ "textblob": blob_data,
64
+ }
65
+ except Exception:
66
+ return {"emotion": "Unknown", "vader": {}, "textblob": {}}
67
 
68
  def plot_emotions(self):
69
+ try:
70
+ simulated_emotions = {
71
+ "joy": random.randint(10, 30),
72
+ "sadness": random.randint(5, 20),
73
+ "anger": random.randint(10, 25),
74
+ "fear": random.randint(5, 15),
75
+ "love": random.randint(10, 30),
76
+ "surprise": random.randint(5, 20),
77
+ }
78
+ df = pd.DataFrame(list(simulated_emotions.items()), columns=["Emotion", "Percentage"])
79
+ plt.figure(figsize=(8, 4))
80
+ sns.barplot(x="Emotion", y="Percentage", data=df)
81
+ plt.title("Simulated Emotional State")
82
+ plt.tight_layout()
83
+ path = "emotions.png"
84
+ plt.savefig(path)
85
+ plt.close()
86
+ return path
87
+ except Exception:
88
+ return None
89
 
90
  # --- Text Completion LLM ---
91
  tokenizer = AutoTokenizer.from_pretrained("diabolic6045/ELN-Llama-1B-base")
92
  model = AutoModelForCausalLM.from_pretrained("diabolic6045/ELN-Llama-1B-base")
93
 
94
  def generate_completion(message, temperature, max_length):
95
+ try:
96
+ inputs = tokenizer(message, return_tensors="pt", truncation=True, max_length=512)
97
+ input_ids = inputs["input_ids"]
98
+ current_text = message
99
+
100
+ for _ in range(max_length - input_ids.shape[1]):
101
+ with torch.no_grad():
102
+ outputs = model(input_ids)
103
+ logits = outputs.logits[:, -1, :] / temperature
104
+ probs = torch.softmax(logits, dim=-1)
105
+ next_token = torch.multinomial(probs, num_samples=1)
106
+
107
+ if next_token.item() == tokenizer.eos_token_id:
108
+ break
109
+
110
+ input_ids = torch.cat([input_ids, next_token], dim=-1)
111
+ new_token_text = tokenizer.decode(next_token[0], skip_special_tokens=True)
112
+ current_text += new_token_text
113
+ return current_text
114
+ except Exception:
115
+ return "Error generating text."
116
 
117
  # --- Emotion-Aware LLM Response ---
118
  def emotion_aware_response(input_text):
119
+ try:
120
+ analyzer = EmotionalAnalyzer()
121
+ results = analyzer.analyze(input_text)
122
+ image_path = analyzer.plot_emotions()
123
+
124
+ prompt = (
125
+ f"Input: {input_text}\n"
126
+ f"Detected Emotion: {results['emotion']}\n"
127
+ f"VADER Scores: {results['vader']}\n"
128
+ f"Respond thoughtfully and emotionally aware:"
129
+ )
130
+
131
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
132
+ with torch.no_grad():
133
+ output_ids = model.generate(
134
+ inputs.input_ids,
135
+ max_length=512,
136
+ do_sample=True,
137
+ temperature=0.7,
138
+ top_k=50,
139
+ top_p=0.95,
140
+ pad_token_id=tokenizer.eos_token_id
141
+ )
142
+ response = tokenizer.decode(output_ids[0], skip_special_tokens=True)
143
+
144
+ summary = (
145
+ f"Emotion: {results['emotion']}\n"
146
+ f"VADER: {results['vader']}\n"
147
+ f"TextBlob: {results['textblob']}\n\n"
148
+ f"LLM Response:\n{response}"
149
  )
150
+ return summary, image_path
151
+ except Exception:
152
+ return "Error processing emotion-aware response", None
 
 
 
 
 
 
153
 
154
  # --- Gradio Interface ---
155
  with gr.Blocks(title="ELN LLaMA 1B Enhanced Demo") as app: