-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
107 lines (70 loc) · 2.8 KB
/
app.py
File metadata and controls
107 lines (70 loc) · 2.8 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from textblob import TextBlob
from datetime import datetime
import os
app = Flask(__name__)
# Set up database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///entries.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# Thought model
class Thought(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.Text, nullable=False) # Full journal
sentiment = db.Column(db.String(20), nullable=False) # Overall mood
breakdown = db.Column(db.Text, nullable=False) # Per sentence results
date = db.Column(db.DateTime, default=datetime.utcnow)
# Homepage - show all past entries
@app.route('/')
def home():
entries = Thought.query.order_by(Thought.date.desc()).all()
# Count sentiment types and make sure they default to 0 if None
total_positive = Thought.query.filter(Thought.sentiment.like('%Positive%')).count() or 0
total_negative = Thought.query.filter(Thought.sentiment.like('%Negative%')).count() or 0
total_neutral = Thought.query.filter(Thought.sentiment.like('%Neutral%')).count() or 0
return render_template('index.html',
entries=entries,
total_positive=total_positive,
total_negative=total_negative,
total_neutral=total_neutral)
# Analyze and store journal entry
@app.route('/analyze', methods=['POST'])
def analyze():
text = request.form['text']
blob = TextBlob(text)
sentence_results = []
total_polarity = 0
for sentence in blob.sentences:
polarity = sentence.sentiment.polarity
total_polarity += polarity
if polarity > 0:
sentiment = "Positive 😊"
elif polarity < 0:
sentiment = "Negative 😡"
else:
sentiment = "Neutral 😐"
sentence_results.append(f"{sentence} → {sentiment}")
avg_polarity = total_polarity / len(blob.sentences)
if avg_polarity > 0:
overall_sentiment = "Positive 😊"
elif avg_polarity < 0:
overall_sentiment = "Negative 😡"
else:
overall_sentiment = "Neutral 😐"
# Save entry with breakdown joined as one string
new_thought = Thought(
content=text,
sentiment=overall_sentiment,
breakdown='\n'.join(sentence_results)
)
db.session.add(new_thought)
db.session.commit()
return redirect('/')
return render_template('result.html', text=text, results=sentence_results, overall=overall_sentiment)
# Auto-create database on first run
if __name__ == '__main__':
with app.app_context():
db.create_all()
port = int(os.environ.get("PORT", 5000))
app.run(host="0.0.0.0", port=port)