-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
97 lines (82 loc) · 2.69 KB
/
Copy pathapp.py
File metadata and controls
97 lines (82 loc) · 2.69 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
from flask import Flask, render_template, request
import re
import pickle
import numpy as np
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.sequence import pad_sequences
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import nltk
import matplotlib.pyplot as plt
from io import BytesIO
import base64
# Initialize Flask app
app = Flask(__name__)
# Download NLTK data
nltk.download('stopwords')
nltk.download('wordnet')
# Initialize NLP tools
lemmatizer = WordNetLemmatizer()
stop_words = set(stopwords.words('english'))
# Constants
MAX_LENGTH = 100
# Load model and tokenizer
model = load_model('amazon_model.h5')
with open('tokenizer (2).pkl', 'rb') as f:
tokenizer = pickle.load(f)
def clean_text(text):
"""Clean and preprocess text"""
text = re.sub(r'[^a-zA-Z\s]', '', text)
text = re.sub(r'\s+', ' ', text)
text = text.lower().strip()
text = ' '.join([lemmatizer.lemmatize(word)
for word in text.split()
if word not in stop_words])
return text
def generate_wordcloud(text):
"""Generate word cloud image"""
from wordcloud import WordCloud
plt.figure(figsize=(10, 5))
wordcloud = WordCloud(
width=800,
height=400,
background_color='white',
colormap='viridis',
max_words=100
).generate(text)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
# Save image to bytes
img_bytes = BytesIO()
plt.savefig(img_bytes, format='png', bbox_inches='tight', dpi=150)
img_bytes.seek(0)
plt.close()
return base64.b64encode(img_bytes.read()).decode('utf-8')
@app.route('/')
def home():
return render_template('index.html')
@app.route('/analyze', methods=['POST'])
def analyze():
text = request.form['text']
cleaned_text = clean_text(text)
wordcloud_img = generate_wordcloud(cleaned_text)
# Tokenize and pad text
sequence = tokenizer.texts_to_sequences([cleaned_text])
padded = pad_sequences(sequence, maxlen=MAX_LENGTH)
# Make prediction
prediction = model.predict(padded, verbose=0)
confidence = float(prediction[0][0])
sentiment = 'positive' if confidence > 0.6 else 'negative' if confidence < 0.4 else 'neutral'
# Prepare response
response = {
'text': text,
'cleaned_text': cleaned_text,
'sentiment': sentiment,
'confidence': round(max(confidence, 1-confidence) * 100, 2),
'positive_prob': round(confidence * 100, 2),
'negative_prob': round((1 - confidence) * 100, 2),
'wordcloud': wordcloud_img
}
return render_template('results.html', **response)
if __name__ == '__main__':
app.run(debug=True)