Код: Выделить всё
Sell Weapons
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
{% for key, value in data.items() %}
{% if value is string %}
['{{ key }}', '{{ value }}'],
{% else %}
['{{ key }}', {{ value }}],
{% endif %}
{% endfor %}
]);
var options = {
title: 'Clients comments',
is3D: true,
//pieHole: 0.5
pieStartAngle: 100
/*slices: {
2: {offset: 0.2},
3: {offset: 0.3}
}*/
/*slices: {
1: { color: 'transparent' }
}*/
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
evaluate first product
evaluate second product
evaluate third product
[h4]
{{ prediction_text }} [/h4]
customer satisfaction
[img]https://i.stack.imgur. com/0TnmT.png[/img]
итак, идея заключается в том, что пользователь будет писать комментарии, я должен читать эти комментарии, анализировать и рисовать круговые диаграммы на основе его полярности (негативности и позитивности), для это я создал следующий код Python:
Код: Выделить всё
import numpy as np
from flask import Flask,request,jsonify,render_template
import pickle
from transformers import pipeline
from collections import Counter
import matplotlib.pyplot as plt
sentiment_pipeline = pipeline("sentiment-analysis")
app =Flask(__name__)
@app.route('/')
def home():
return render_template("Commenting.html")
@app.route('/predict',methods=['POST'])
# @app.route('/')
def predict():
text = [x for x in request.form.values()]
print(text)
status = []
for sentence in text:
print(sentence)
status.append(sentiment_pipeline(sentence)[0]['label'])
print(status)
# data = {'Task': 'Hours per Day', 'Work': 22, 'Eat': 4, 'Commute': 6, 'Watching TV': 5, 'Sleeping': 15}
data = Counter(status)
print(data)
# data ={"Positive":list(data.values())[0],"Negative":list(data.values())[1]}
# positive_text =list(data .keys())[0]
# positive_frequency =list(data .values())[0]
# negative_text = list(data.keys())[1]
# negative_frequency = list(data.values())[1]
# total =positive_frequency+negative_frequency
# text_sho =(f'{positive_text} takes {positive_frequency/(positive_frequency+negative_frequency)*100 } % '
# f'and {negative_text} takes {negative_frequency/(positive_frequency+negative_frequency)*100} %')
# sentiment_pipeline = pipeline("sentiment-analysis")
# status = []
# for sentence in text:
# status.append(sentiment_pipeline(sentence)[0]['label'])
# # print(sentiment_pipeline(sentence)[0])
# emotion_counter = Counter(status)
# plt.pie([float(v) for v in emotion_counter.values()], labels=[k for k in emotion_counter],
# autopct="%2.3f%%")
# plt.savefig("templates/sentiment_distribution.png")
# plt.show()
# values =[float(v) for v in emotion_counter.values()]
# labels = [k for k in emotion_counter]
#
# text=list(text)
return render_template('Commenting.html',data=data)
# sentiment_pipeline = pipeline("sentiment-analysis")
# result =sentiment_pipeline(text)[0]
# if result['label']=='POSITIVE':
# return render_template('Commenting.html',prediction_text=f'emotion of comment is positive')
# else:
# return render_template('Commenting.html', prediction_text=f'emotion of comment is not positive')
if __name__ =="__main__":
app.run()
Код: Выделить всё
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\Web_Development\venv\Lib\site-packages\flask\app.py", line 1455, in wsgi_app
response = self.full_dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\PycharmProjects\Web_Development\venv\Lib\site-packages\flask\app.py", line 869, in full_dispatch_request
rv = self.handle_user_exception(e)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\PycharmProjects\Web_Development\venv\Lib\site-packages\flask\app.py", line 867, in full_dispatch_request
rv = self.dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\PycharmProjects\Web_Development\venv\Lib\site-packages\flask\app.py", line 852, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\PycharmProjects\Web_Development\app.py", line 11, in home
return render_template("Commenting.html")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\PycharmProjects\Web_Development\venv\Lib\site-packages\flask\templating.py", line 152, in render_template
return _render(app, template, context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\PycharmProjects\Web_Development\venv\Lib\site-packages\flask\templating.py", line 133, in _render
rv = template.render(context)
^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\PycharmProjects\Web_Development\venv\Lib\site-packages\jinja2\environment.py", line 1301, in render
self.environment.handle_exception()
File "C:\Users\User\PycharmProjects\Web_Development\venv\Lib\site-packages\jinja2\environment.py", line 936, in handle_exception
raise rewrite_traceback_stack(source=source)
File "C:\Users\User\PycharmProjects\Web_Development\templates\Commenting.html", line 12, in top-level template code
{% for key, value in data.items() %}
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\PycharmProjects\Web_Development\venv\Lib\site-packages\jinja2\environment.py", line 485, in getattr
return getattr(obj, attribute)
^^^^^^^^^^^^^^^^^^^^^^^
jinja2.exceptions.UndefinedError: 'data' is undefined
127.0.0.1 - - [31/Mar/2024 16:01:22] "GET / HTTP/1.1" 500 -
Подробнее здесь: https://stackoverflow.com/questions/782 ... t-in-flask