Spaces:
Sleeping
Sleeping
File size: 2,494 Bytes
56c961a cf59149 1ef8f70 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
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})") |