Harinipsp commited on
Commit
1ef8f70
1 Parent(s): ccf4a65

Create appy.py

Browse files
Files changed (1) hide show
  1. appy.py +72 -0
appy.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from transformers import pipeline
3
+ from googletrans import Translator
4
+
5
+ # Initialize translation and classification pipelines
6
+ translator = Translator()
7
+ emotion_classifier = pipeline("text-classification", model="arpanghoshal/EmoRoBERTa")
8
+
9
+
10
+ def classify_emotion(text, src_lang="auto", target_lang="en"):
11
+ """
12
+ Classifies emotion in text after translating to English (if needed).
13
+
14
+ Args:
15
+ text: Input text sentence in any language.
16
+ src_lang: Source language of the text (default: "auto").
17
+ target_lang: Target language for translation (default: "en").
18
+
19
+ Returns:
20
+ A dictionary containing the predicted emotion and its probability.
21
+ """
22
+ # Translate to English if necessary
23
+ if src_lang != target_lang:
24
+ translated_text = translator.translate(text, dest=target_lang).text
25
+ else:
26
+ translated_text = text
27
+
28
+ # Classify emotion using EmoRoBERTa
29
+ predictions = emotion_classifier(translated_text)
30
+ return predictions[0]
31
+
32
+
33
+ def split_sentences_with_conjunctions(paragraph):
34
+ """
35
+ Splits a paragraph into sentences considering conjunctions and punctuation.
36
+
37
+ Args:
38
+ paragraph: The input paragraph as a string.
39
+
40
+ Returns:
41
+ A list of individual sentences.
42
+ """
43
+ sentences = []
44
+ current_sentence = ""
45
+ conjunctions = ["and", "but", "or", "for", "nor", "so", "yet"] # Common conjunctions
46
+
47
+ for word in paragraph.split():
48
+ current_sentence += word + " "
49
+ if word.lower() in conjunctions or word.endswith(".") or word.endswith("?"):
50
+ sentences.append(current_sentence.strip())
51
+ current_sentence = ""
52
+
53
+ # Add any remaining sentence fragment
54
+ if current_sentence.strip():
55
+ sentences.append(current_sentence.strip())
56
+
57
+ return sentences
58
+ paragraph = st.text_area("Enter your input: ")
59
+
60
+ # Split paragraph into sentences considering conjunctions
61
+ sentences = split_sentences_with_conjunctions(paragraph)
62
+
63
+ # Classify emotion for each sentence
64
+ emotion_results = []
65
+ for sentence in sentences:
66
+ if sentence.strip(): # Check if sentence is not empty after stripping
67
+ emotion_result = classify_emotion(sentence)
68
+ emotion_results.append(emotion_result)
69
+
70
+ # Print emotions for each sentence
71
+ for sentence, emotion_result in zip(sentences, emotion_results):
72
+ print(f"Sentence: {sentence} | Emotion: {emotion_result['label']} ({emotion_result['score']:.2f})")