Reputation: 3135
I am trying to render a wordcloud that I can run on my computer w/o flask.
I am using this question as a base
@app.route('/wordcloud/<vendor_duns>')
def images(vendor_duns):
words = Words.query.filter(Words.vendor_duns == vendor_duns).with_entities(Words.words).all()
# t = [r.__dict__ for r in words]
# print(t)
one_row = list(itertools.chain.from_iterable(words))
text = ' '.join(one_row)
return render_template("wordcloud.html", text=text)
@app.route('/fig/<vendor_duns>')
def fig(vendor_duns):
# TODO add test model and query
words = Words.query.filter(Words.vendor_duns == vendor_duns).with_entities(Words.words).all()
one_row = list(itertools.chain.from_iterable(words))
text = ' '.join(one_row)
wordcloud = WordCloud().generate(text)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
img = BytesIO()
plt.savefig(img)
img.seek(0)
return send_file(img, mimetype='image/png')
{% extends "base.html" %}
{% block title %}Wordcloud{% endblock %}
{% block content %}
{{text}}
<div>
<img src="{{ url_for('sam.fig', vendor_duns=vendor_duns) }}" alt="Image Placeholder" height="100">
</div>
{% endblock %}
First off the {{text}}
in the template is just for view. If I nav to a specific vendor_duns I will get a long string of text, but no image.
So two questions, where exactly do I need to run the query? in the fig
or image function
.
The second question, I get a blank image, so I am not sure exactly how to write the wordcloud to a buffer.
Upvotes: 0
Views: 2568
Reputation: 1
Here is an example how you can plot wordcloud in flask app using BytesIO(), wordcloud and render it in html page.
@app.route("/<xyz>")
def profile():
wordcloud = WordCloud(collocations=True, background_color= "white" ).generate(text)
wordcloudImage = wordcloud.to_image()
img = BytesIO()
wordcloudImage.save(img, format='PNG')
imgword='data:image/png;base64,}'.format(base64.b64encode(img.getvalue()).decode())
return render_template('visuals.html', wordcloud = imgword)
#in html file put
<div class="img" align="center">
<img src="{{ wordcloud }}" alt="wordcloud">
</div>
Upvotes: 0
Reputation: 3135
wordcloud to_image
method creates a PIL object so all you have to do is just call the PIL's save
method.
img = BytesIO()
wordcloud.to_image().save(img, 'PNG')
img.seek(0)
Upvotes: 1