Proof of concept for automatic category guessing for OpenFoodFacts data.

app.py 1.1KB

123456789101112131415161718192021222324252627282930313233343536
  1. from bottle import hook, request, response, route, run
  2. from sklearn.externals import joblib
  3. mlb, classifier = joblib.load('offClassifier.pkl')
  4. @hook('after_request')
  5. def enable_cors():
  6. """
  7. You need to add some headers to each request.
  8. Don't use the wildcard '*' for Access-Control-Allow-Origin in production.
  9. """
  10. response.headers['Access-Control-Allow-Origin'] = '*'
  11. response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
  12. response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
  13. @route('/predict', method=['OPTIONS', 'POST'])
  14. def predict():
  15. if request.method == 'OPTIONS':
  16. return {}
  17. products = request.json
  18. predictions = mlb.inverse_transform(
  19. classifier.predict([p['name'] for p in products])
  20. )
  21. return {
  22. 'data': [
  23. product.update({'predictedCategories': categories}) or product
  24. for product, categories in zip(products, predictions)
  25. ]
  26. }
  27. if __name__ == '__main__':
  28. run(host='localhost', port=4242)