-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
57 lines (47 loc) · 1.88 KB
/
main.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
from flask import Flask, request, make_response
from wordcloud import WordCloud
import jieba
from collections import defaultdict
import io
import base64
import platform
app = Flask(__name__)
@app.route("/wordcloud", methods=["get", "post"])
def getWordImage(width=300, height=300):
if request.method == "POST":
print("request:",request,request.args,request.files, request.form)
file = request.files["file"]
segs = jieba.cut(file.read())
stop_words = []
try:
with open("./data/stop_words_chinese.txt", 'r', encoding="utf8") as f:
for line in f:
stop_words.append(line.strip())
except Exception as e:
print("error", e)
word_freqs = defaultdict(int)
for seg in segs:
if seg not in stop_words:
word_freqs[seg] += 1
if platform.system() == "Darwin":
wc = WordCloud(width=width, height=height, font_path="/Library/Fonts/Songti.ttc")
elif platform.system() == "Linux":
wc = WordCloud(width=width, height=height, font_path="/Library/Fonts/Songti.ttc")
elif platform.system() == "Windows":
wc = WordCloud(width=width, height=height, font_path="/Library/Fonts/Songti.ttc")
else:
wc = WordCloud(width=width, height=height)
wc.generate_from_frequencies(word_freqs)
print("test ", wc.to_image(), type(wc.to_image()))
wc_image = wc.to_image()
img_stream = io.BytesIO()
wc_image.save(img_stream, "png")
headers = {
"Access-Control-Allow-Origin":"*"
}
return make_response( "data:image/png;base64," + base64.b64encode(img_stream.getvalue()).decode('ascii'),200,headers)
else:
print(request,request.form)
return "please upload a text file"
if __name__ == "__main__":
app.run(debug=True)