add-semi-colons
add-semi-colons

Reputation: 18830

Python-Flask: Pass data to machine learning python script and get results back

My knowledge in web frameworks are pretty bad. I have a build a machine learning model in python and it takes a set of strings as an input and return results. After searching on the web I came across with Flask. But what I don't know is how to actually create a flask app to actually take a string and allow user to submit and pass that string to my machine learning python script and return results. This is all I have so far

import threading
import subprocess
import os
import sys
from flask import Flask
from flask import render_template, abort
app = Flask(__name__)
app.debug = True

def run_script():
    theproc = subprocess.Popen([sys.executable, "ML_script.py"])
    theproc.communicate()


if __name__ == "__main__":
    app.run()

If you can point to an example or provide a solution /skeleton that would be fantastic.

Upvotes: 0

Views: 2692

Answers (1)

kylieCatt
kylieCatt

Reputation: 11039

You can use your machine learning functions like any other Python function there is no need for subprocess. Setup your app:

from flask import Flask
from flask import render_template, abort, jsonify, request,redirect, json
from my_app.machine_learning import analyzer
app = Flask(__name__)
app.debug = True

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/learning', methods=['POST'])
def learning():
    data = json.loads(request.data)
    # data == {"userInput": "whatever text you entered"}
    response = analyzer(data)
    return jsonify(response)


if __name__ == '__main__':
    app.run()

I used a stand in name for your machine learning module but analyzer() should be a function in that module that calls all your other functions needed to do your computations and returns a dictionary that has your results in it. So something like this:

def analyzer(data):
    vocab = build_vocab(training_data)
    cl = train_classifier(vocab, trianing_data)
    results = cl.predict(data)
    results = format_results_to_dict()
    return results

The template is pretty straight forward:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="../static/script.js"></script>
</script>
</head>

<body>
    <h1>Calculation</h1>
    <h1>Test Page</h1>
    <input id="user-input" placeholder="Text to be analyzed"></input>
    <p id="results">Results will go here<p>
    <button id="submit">Submit</button>
</body>
</html>

And the JS script to tie it all together:

$(document).ready(function(){
    $("#submit").click(function(event){
        var uInput = $("#user-input").val();
        $.ajax({
              type: "POST",
              url: '/learning',
              data: JSON.stringify({userInput: uInput}),
              contentType: 'application/json',
              success: function(response){
                   $("#results").text(response.results);
                },
          });
    });
});

Upvotes: 5

Related Questions