preface
This is a word cloud application developed using Vue at the front end and Flask at the back end. The code has been uploaded to flask-VUe-word-cloud. The reason for writing this small project is that the team has a year-end report recently. Some leaders used word clouds in their PPT to show their team’s work achievements in a year. There is also a big man said not to guard their own land, broaden their horizons in technology can help us grow better. I was just exposed to Python and R word cloud generation, so as a mobile developer, I wanted to run a local word cloud generation service, so I came up with this project.
The directory structure
Backend is the server of the Flask implementation and frontend is the frontend of the Vue implementation.
. ├ ─ ─ backend │ ├ ─ ─ app │ └ ─ ─ venv └ ─ ─ frontend ├ ─ ─ the README. Md ├ ─ ─ build ├ ─ ─ the config ├ ─ ─ dist ├ ─ ─ index. The HTML ├ ─ ─ ├─ package.json ├─ SRC ├─ ├.txtCopy the code
Vue is a progressive JavaScript framework. Vue website
Flask is a lightweight Web application framework written in Python. Flask Learning Resources
Let’s look at how the code works so far:
The development environment
Hardware:
- MacOS Mojave 10.14.6
Software:
- Nodejs v11.6.0
- Python 3.7.4
Ensure that the Node JS environment has been installed. For details, see the NodeJS official website.
The front-end development
1. Install vuE-CLI
Vue CLI is a complete system for rapid development based on vue.js.
$ npm install -g vue-cli
Copy the code
2. Create projects
The new directory
$ mkdir word-cloud
$ cd word-cloud/
Copy the code
Create a project
$ vue init webpack frontend
Copy the code
After executing the above command, it will let you set the basic information of the project. My configuration is as follows:
Then wait for some basic dependencies to be installed and then go to the Frontend directory
$ cd frontend
$ npm run dev
Copy the code
It will be prompted on the console after execution
Your application is running here: http://localhost:8080
Copy the code
We are now ready to run. You can visit http://localhost:8080 as follows:
If we look at the directory structure of frontend, we have generated some directories and code by default.
.├ ── Build ├─ Config ├─ index.html ├── Package-lock-├ ─ package-.json ├─ SRC ├─ staticCopy the code
3. Install Element-UI
Element is a Vue 2.0-based desktop component library for developers, designers, and product managers.
$ npm i element-ui -S
Copy the code
The use of plug-in
Import ElementUI in the directory/SRC /main.js that vue-CLI helped us generate
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Copy the code
Finally using
Vue.use(ElementUI)
Copy the code
4. Install AxiOS
Since it is a separate application, the requested library, Axios, is also installed. Axios is an HTTP client based on promises.
$ npm install --save axios
Copy the code
Import axios in/SRC /main.js as well
import axios from 'axios'
Copy the code
Registered axios
Vue.prototype.axios = axios
Copy the code
Then we can use Axios to send the request.
5. Write pages
First go to app. vue and delete the logo we don’t need.
<template>
<div id="app"> <! -- <img src="./assets/logo.png"> -->
<router-view/>
</div>
</template>
Copy the code
New wordCloud. vue, this is our main page. One title, one input field, two buttons.
<template> <div> <h2> </h2> <div id="word-text-area">
<el-input type="textarea" :rows="10" placeholder="Please enter the content" v-model="textarea">
</el-input>
<div id="word-img">
<el-image :src="'data:image/png; base64,'+pic" :fit="fit">
<div slot="error" class="image-slot">
<i class="el-icon-picture-outline"></i>
</div>
</el-image>
</div>
<div id="word-operation">
<el-row>
<el-button type="primary" @click="onSubmit"</el-button> <el-buttontype="success" @click="onDownload"Picture round > download < / el - button > < / el - row > < / div > < / div > < / div > < / template >Copy the code
Implement the click event and send the request
<script>
export default {
name: 'wordcloud'.data() {
return {
textarea: ' ',
pic: "",
pageTitle: 'Flask Vue Word Cloud',
}
},
methods: {
onSubmit() {
var param = {
"word": this.textarea
}
this.axios.post("/word/cloud/generate", param).then(
res => {
this.pic = res.data
console.log(res.data)
}
).catch(res => {
console.log(res.data.res)
})
},
onDownload() {
const imgUrl = 'data:image/png; base64,' + this.pic
const a = document.createElement('a')
a.href = imgUrl
a.setAttribute('download'.'word-cloud')
a.click()
}
}
}
</script>
Copy the code
Finally, find index.js in SRC/Router to modify the route.
export default new Router({
routes: [{
path: '/',
name: 'index',
component: WordCloud
}]
})
Copy the code
Packaging resources
$ npm run build
Copy the code
After execution is complete, the resources are packaged into the dist directory.
At this point, the front-end development work is complete.
The backend development
1. Install Python3
Since Python version 2.7 comes with the MAC system, let’s install Python3 first, which I used homebrew for.
brew install python3
Copy the code
Since I have installed it before, there is a warning after the execution, follow the instructions
Warning: python 3.7.4_1 is already installed, it’s just not linked You can use
brew link python
to link this version.
Linking /usr/local/ Cellar/python / 3.7.4 _1... Error: Permission denied @ dir_s_mkdir - /usr/local/Frameworks
Copy the code
Error again, no permissions
Reference: stackoverflow.com/questions/2…
sudo chown -R $USER:admin /usr/local
Copy the code
Performed again
brew link python
Copy the code
Linking /usr/local/ Cellar/python / 3.7.4 _1... 1 symlinks createdCopy the code
Error resolved. Python3 will display the correct version number.
$python3 Python 3.7.4 (default, Sep 7 2019, 18:27:02) [Clang 10.0.1 (clang-1001.0.46.4)] on Darwin Type"help"."copyright"."credits" or "license" for more information.
Copy the code
2. Create a virtual environment
The Python virtual environment can provide an independent running environment for Python projects, so that different applications use different Versions of Python. We use the virtual environment to develop a Python application.
Create a back-end directory
$ mkdir backend
$ cd backend/
Copy the code
Creating a Virtual Environment
python3 -m venv venv
Copy the code
Activating a Virtual Environment
source venv/bin/activate
Copy the code
The command for stopping the virtual environment is as follows
deactivate
Copy the code
Install the flask
Flask was introduced at the beginning of the article.
pip install flask
Copy the code
If no errors are reported, the installation is complete.
4, install the word cloud into a library
Wordcloud is python’s excellent wordcloud generation library. Word cloud shows text more intuitively with words as the basic unit.
pip install wordcloud
Copy the code
4. Write code
The Flask code section is referred to in The Flask Mega-Tutorial, and you can write The application after The first chapter. Here I explain the key code.
Modify python’s default HTML and static resource directory in __init__.py, which is the resource directory we generated above with NPM run build in front-end development.
app = Flask(__name__,
template_folder=".. /.. /frontend/dist",
static_folder=".. /.. /frontend/dist/static")
Copy the code
Start Flask after the changes are made and you’ll be accessing vue’s page.
The code in routes.py is the home page and the interface to generate the word cloud.
# Real words cloud library to generate pictures
def get_word_cloud(text):
# font = "./SimHei.ttf"
# pil_img = WordCloud(width=500, height=500, font_path=font).generate(text=text).to_image()
pil_img = WordCloud(width=800, height=300, background_color="white").generate(text=text).to_image()
img = io.BytesIO()
pil_img.save(img, "PNG")
img.seek(0)
img_base64 = base64.b64encode(img.getvalue()).decode()
return img_base64
# main page
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
Generate word cloud image interface, base64 format return
@app.route('/word/cloud/generate', methods=["POST"])
def cloud():
text = request.json.get("word")
res = get_word_cloud(text)
return res
Copy the code
Then you do the flask Run and you run.
Of course this is a rudimentary application that takes half a day to run, but it has the basic functionality of separating the application from the front and back ends, which will be improved in the future.
TODO
- Support Chinese word segmentation
- Support stop words
- Integrated Docker
- Custom background color
- Customize image size
- Custom word cloud shapes
- Custom fonts
- Server Deployment
- other
To learn more, please pay attention to the official number: nine o ‘clock off work