-
Notifications
You must be signed in to change notification settings - Fork 23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Emotionallity Detection update #334
Draft
SvenjaKern
wants to merge
4
commits into
main
Choose a base branch
from
emotion
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
59 changes: 30 additions & 29 deletions
59
classifiers/text_analysis/emotionality_detection/__init__.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,35 +1,36 @@ | ||
import requests | ||
from extractors.util.spacy import SpacySingleton | ||
from pydantic import BaseModel | ||
from LeXmo import LeXmo | ||
|
||
INPUT_EXAMPLE = { | ||
"text": """As Harry went inside the Chamber of Secrets, he discovered the Basilisk's layer. Before him stood Tom | ||
Riddle, with his wand. Harry was numb for a second as if he had seen a ghost. Moments later the giant | ||
snake attacked Harry but fortunately, Harry dodged and ran into one of the sewer lines while the serpent | ||
followed. The Basilisk couldn't be killed with bare hands but only with a worthy weapon.""" | ||
"text": "I did not know that you were coming! I am very glad to see you. If you would tell me sooner, I would have baked some cookies, though.", | ||
"apiKey": "<API_KEY_GOES_HERE>" | ||
} | ||
|
||
|
||
class EmotionalityDetectionModel(BaseModel): | ||
text: str | ||
|
||
class Config: | ||
schema_example = {"example": INPUT_EXAMPLE} | ||
|
||
|
||
def emotionality_detection(request: EmotionalityDetectionModel): | ||
"""Fetches emotions from a given text""" | ||
|
||
text = request.text | ||
try: | ||
emo = LeXmo.LeXmo(text) | ||
del emo["text"] | ||
del emo["positive"] | ||
del emo["negative"] | ||
unique = dict(zip(emo.values(), emo.keys())) | ||
if len(unique) == 1: | ||
return "Cannot determine emotion" | ||
else: | ||
emo = max(emo, key=emo.get) | ||
return {"emotion": emo} | ||
except ValueError: | ||
return "Valid text required" | ||
apiKey: str | ||
text: str | ||
|
||
class Config: | ||
schema_example = {"example": INPUT_EXAMPLE} | ||
|
||
def emotionality_detection(req: EmotionalityDetectionModel): | ||
"""huggingface model for emotion detection""" | ||
headers = {"Authorization": f"Bearer {req.apiKey}"} | ||
data = {"inputs": req.text} | ||
try: | ||
response = requests.post("https://api-inference.huggingface.co/models/j-hartmann/emotion-english-distilroberta-base", headers=headers, json=data) | ||
response_json = response.json() | ||
|
||
# flatten the list of lists | ||
flat_list = [item for sublist in response_json for item in sublist] | ||
|
||
# find the item with the highest score | ||
max_item = max(flat_list, key=lambda x: x["score"]) | ||
|
||
# retrieve the label of the item with the highest score | ||
max_label = max_item["label"] | ||
|
||
return max_label | ||
except Exception as e: | ||
return f"That didn't work. Did you provide a valid API key? Go error: {e} and message: {response_json}" |
45 changes: 28 additions & 17 deletions
45
classifiers/text_analysis/emotionality_detection/code_snippet_common.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,26 +1,37 @@ | ||
```python | ||
from LeXmo import LeXmo | ||
|
||
def emotionality_detection(text:str) -> str: | ||
""" | ||
@param text: text to check | ||
@return: either 'anger', 'fear', 'anticipation', 'trust', 'surprise', 'sadness', 'joy' or 'disgust' depending on the score | ||
""" | ||
emo = LeXmo.LeXmo(text) | ||
del emo["text"] | ||
del emo["positive"] | ||
del emo["negative"] | ||
emo = max(emo, key=emo.get) | ||
return emo | ||
|
||
|
||
import requests | ||
|
||
def emotionality_detection(text, api_key): | ||
headers = {"Authorization": f"Bearer {api_key}"} | ||
data = {"inputs": text} | ||
try: | ||
response = requests.post("https://api-inference.huggingface.co/models/j-hartmann/emotion-english-distilroberta-base", headers=headers, json=data) | ||
response_json = response.json() | ||
|
||
# flatten the list of lists | ||
flat_list = [item for sublist in response_json for item in sublist] | ||
|
||
# find the item with the highest score | ||
max_item = max(flat_list, key=lambda x: x["score"]) | ||
|
||
# retrieve the label of the item with the highest score | ||
max_label = max_item["label"] | ||
|
||
return max_label | ||
except Exception as e: | ||
return f"That didn't work. Did you provide a valid API key? Go error: {e} and message: {response_json}" | ||
|
||
# ↑ necessary bricks function | ||
# ----------------------------------------------------------------------------------------- | ||
# ↓ example implementation | ||
|
||
def example_integration(): | ||
texts = ["I am scared to continue.", "Oh my goodness it was the best evening ever, hype!"] | ||
for text in texts: | ||
print(f"\"{text}\" has emotion: {emotionality_detection(text)}") | ||
hf_api_key = "<API_KEY_GOES_HERE>" | ||
texts = ["What a great day to go to the beach.", "Sorry to hear that. CAn I help you?", "Why the hell would you do that?"] | ||
for text in texts: | ||
output = emotionality_detection(text, api_key=hf_api_key) | ||
print(output) | ||
|
||
example_integration() | ||
``` |
27 changes: 15 additions & 12 deletions
27
classifiers/text_analysis/emotionality_detection/code_snippet_refinery.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,19 @@ | ||
```python | ||
#expects labeling task to have labels ["anger", "fear", "anticipation", "trust", "surprise", "sadness", "joy", "disgust"] | ||
from LeXmo import LeXmo | ||
import requests | ||
|
||
ATTRIBUTE: str = "text" # only text attributes | ||
ATTRIBUTE: str = "text" | ||
API_KEY: str = "<API_KEY_GOES_HERE>" | ||
|
||
def emotionality_detection(record): | ||
text = record[ATTRIBUTE].text # SpaCy document, hence we need to call .text to get the string | ||
emo = LeXmo.LeXmo(text) | ||
del emo["text"] | ||
del emo["positive"] | ||
del emo["negative"] | ||
emo = max(emo, key=emo.get) | ||
|
||
return emo | ||
def emotionality_detection(text, api_key): | ||
headers = {"Authorization": f"Bearer {API_KEY}"} | ||
data = {"inputs": record[ATTRIBUTE].text} | ||
try: | ||
response = requests.post("https://api-inference.huggingface.co/models/j-hartmann/emotion-english-distilroberta-base", headers=headers, json=data) | ||
response_json = response.json() | ||
flat_list = [item for sublist in response_json for item in sublist] | ||
max_item = max(flat_list, key=lambda x: x["score"]) | ||
max_label = max_item["label"] | ||
return max_label | ||
except Exception as e: | ||
return f"That didn't work. Did you provide a valid API key? Go error: {e} and message: {response_json}" | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would add this to the "llm" category as well as this is using a roberta model from HuggingFace.