Spaces:
Sleeping
Sleeping
pip install transformers | |
pip install googletrans==4.0.0-rc1 | |
import streamlit as st | |
from transformers import pipeline | |
from googletrans import Translator | |
# Initialize translation and classification pipelines | |
translator = Translator() | |
emotion_classifier = pipeline("text-classification", model="arpanghoshal/EmoRoBERTa") | |
def classify_emotion(text, src_lang="auto", target_lang="en"): | |
""" | |
Classifies emotion in text after translating to English (if needed). | |
Args: | |
text: Input text sentence in any language. | |
src_lang: Source language of the text (default: "auto"). | |
target_lang: Target language for translation (default: "en"). | |
Returns: | |
A dictionary containing the predicted emotion and its probability. | |
""" | |
# Translate to English if necessary | |
if src_lang != target_lang: | |
translated_text = translator.translate(text, dest=target_lang).text | |
else: | |
translated_text = text | |
# Classify emotion using EmoRoBERTa | |
predictions = emotion_classifier(translated_text) | |
return predictions[0] | |
def split_sentences_with_conjunctions(paragraph): | |
""" | |
Splits a paragraph into sentences considering conjunctions and punctuation. | |
Args: | |
paragraph: The input paragraph as a string. | |
Returns: | |
A list of individual sentences. | |
""" | |
sentences = [] | |
current_sentence = "" | |
conjunctions = ["and", "but", "or", "for", "nor", "so", "yet"] # Common conjunctions | |
for word in paragraph.split(): | |
current_sentence += word + " " | |
if word.lower() in conjunctions or word.endswith(".") or word.endswith("?"): | |
sentences.append(current_sentence.strip()) | |
current_sentence = "" | |
# Add any remaining sentence fragment | |
if current_sentence.strip(): | |
sentences.append(current_sentence.strip()) | |
return sentences | |
paragraph = st.text_area("Enter your input: ") | |
# Split paragraph into sentences considering conjunctions | |
sentences = split_sentences_with_conjunctions(paragraph) | |
# Classify emotion for each sentence | |
emotion_results = [] | |
for sentence in sentences: | |
if sentence.strip(): # Check if sentence is not empty after stripping | |
emotion_result = classify_emotion(sentence) | |
emotion_results.append(emotion_result) | |
# Print emotions for each sentence | |
for sentence, emotion_result in zip(sentences, emotion_results): | |
print(f"Sentence: {sentence} | Emotion: {emotion_result['label']} ({emotion_result['score']:.2f})") |