generated from Vikranth3140/NLTK-Web-App
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
80 lines (60 loc) · 2.22 KB
/
app.py
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
from flask import Flask, render_template, request, jsonify, send_from_directory
from werkzeug.utils import secure_filename
import fitz # PyMuPDF
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import os
import matplotlib.pyplot as plt
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Ensure the upload folder exists
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return "No file part", 400
file = request.files['file']
if file.filename == '':
return "No selected file", 400
filename = secure_filename(file.filename)
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(file_path)
text = extract_text_from_pdf(file_path)
sentiment = analyze_sentiment(text)
plot_filename = plot_sentiment(sentiment, filename)
return jsonify({'sentiment': sentiment, 'plot_filename': plot_filename})
def extract_text_from_pdf(pdf_path):
document = fitz.open(pdf_path)
text = ""
for page_num in range(document.page_count):
page = document.load_page(page_num)
text += page.get_text()
return text
def analyze_sentiment(text):
analyzer = SentimentIntensityAnalyzer()
sentiment_scores = analyzer.polarity_scores(text)
return sentiment_scores
def plot_sentiment(sentiment, filename):
categories = ['Negative', 'Neutral', 'Positive']
scores = [sentiment['neg'], sentiment['neu'], sentiment['pos']]
colors = ['#ff4c4c', '#ffc107', '#4caf50']
plt.figure(figsize=(8, 6))
plt.bar(categories, scores, color=colors)
plt.xlabel('Sentiment')
plt.ylabel('Score')
plt.title('Sentiment Analysis')
plt.ylim(0, 1)
plot_filename = f"{filename}_sentiment.png"
output_path = os.path.join(app.config['UPLOAD_FOLDER'], plot_filename)
plt.savefig(output_path)
plt.close()
return plot_filename
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
app.run(debug=True)