-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
54 lines (44 loc) · 1.76 KB
/
app.py
File metadata and controls
54 lines (44 loc) · 1.76 KB
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
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_watson.natural_language_understanding_v1 import Features, EmotionOptions
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from flask import Flask, request, jsonify
import logging
# Set up IBM Watson NLU credentials
api_key = 'cyEJ8kUS7fv66WDXDHpkmkQcV9gL3ZHtNsXym3p_vtlV'
service_url = 'https://api.au-syd.natural-language-understanding.watson.cloud.ibm.com/instances/c2e19256-8e33-42a7-a19d-1f49833f8fa5'
# Authenticate
authenticator = IAMAuthenticator(api_key)
natural_language_understanding = NaturalLanguageUnderstandingV1(
version='2021-08-01',
authenticator=authenticator
)
natural_language_understanding.set_service_url(service_url)
def detect_emotions(text):
if len(text.strip()) < 5:
raise ValueError("Text too short to analyze emotions.")
try:
response = natural_language_understanding.analyze(
text=text,
features=Features(emotion=EmotionOptions())
).get_result()
return response['emotion']['document']['emotion']
except Exception as e:
logging.error(f"Error in detect_emotions: {e}")
return {}
app = Flask(__name__)
@app.route('/')
def home():
return '''
<h1>Emotion Detection</h1>
<form action="/detect_emotion" method="post">
<textarea name="text" rows="4" cols="50"></textarea><br>
<input type="submit" value="Detect Emotion">
</form>
'''
@app.route('/detect_emotion', methods=['POST'])
def detect_emotion():
text = request.form['text']
emotions = detect_emotions(text)
return jsonify(emotions)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)