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

后端 未结 1 1274
没有蜡笔的小新
没有蜡笔的小新 2021-01-07 13:55

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 searchin

相关标签:
1条回答
  • 2021-01-07 14:05

    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);
                    },
              });
        });
    });
    
    0 讨论(0)
提交回复
热议问题