Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -21,113 +21,135 @@ nltk.download('vader_lexicon', quiet=True)
|
|
| 21 |
# --- Emotion Analyzer ---
|
| 22 |
class EmotionalAnalyzer:
|
| 23 |
def __init__(self):
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
self.labels = ["sadness", "joy", "love", "anger", "fear", "surprise"]
|
| 31 |
self.sia = SentimentIntensityAnalyzer()
|
| 32 |
|
| 33 |
def predict_emotion(self, text):
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
def analyze(self, text):
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
def plot_emotions(self):
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
# --- Emotion-Aware LLM Response ---
|
| 99 |
def emotion_aware_response(input_text):
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
)
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 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:
|