Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use python libraries in React Native

I want to use some Python libraries (for machine learning etc) in a React Native app. Is it possible to do it without using a server (i.e. run the Python code within the mobile app) so that no internet is required?

like image 567
Avery235 Avatar asked Dec 14 '17 04:12

Avery235


People also ask

Can I use Python in react-native?

In a matter of minutes and without a single line of code, Buddy allows you to connect Python and Build Android React Native Application.

How do I add Python to react-native?

You could compile your python Cython then create a android lib with Android NDK then create a Native module and consume it. You could also translate in jython and create a native module using the generated class but you need to be sure you don't use Java API that isn't implemented by Android.

Can I use any JS library in react-native?

​ Usually libraries built specifically for other platforms will not work with React Native. Examples include react-select which is built for the web and specifically targets react-dom , and rimraf which is built for Node. js and interacts with your computer file system.


1 Answers

The React Native App consists of two major portions

  • Business Logic which is a NodeJs app. This app controls the other piece
  • Frontend which is written in Javascript, however it gets linked to native interfaces (Java in case of Android and Obj-C in case of iOS)

In this framework, best way to integrate Python Code, machine learning or otherwise is to connect NodeJS app with Python interpreter. This also happens to be complex to implement. This will go something like this

#include <Python.h>


int main(int argc, char *argv[]){
  Py_SetProgramName(argv[0]);  /* optional but recommended */
  Py_Initialize();
  PyRun_SimpleString("from time import time,ctime\n"
                 "print 'Today is',ctime(time())\n");
  Py_Finalize();
  return 0;
}

As seen at Embedding Tutorial

Now this is bit tricky so lets look at secondary options like connecting with the model using C++. Like Tensorflow also has a C++ API which can be used to integrate Models into NodeJS. Final option is ofcourse to use it as a separate child process or server side call.

like image 194
Supreet Sethi Avatar answered Sep 29 '22 17:09

Supreet Sethi