Run Python ML models directly in React and React Native apps - no backend required!
- Python in the Browser: Run real Python code client-side using Pyodide
- React Integration: Seamless hooks and components for React apps
- React Native Support: Native bridge for mobile applications
- Offline-First: No internet required after initial model load
- Easy Bundling: CLI tools for model packaging and deployment
- TypeScript: Full TypeScript support for better DX
- Web Workers: Non-blocking Python execution
npm install @python-react-ml/core @python-react-ml/react
npm install @python-react-ml/core @python-react-ml/react-native
# iOS additional setup
cd ios && pod install
npm install -g @python-react-ml/cli
install.mp4
# model.py
import numpy as np
def predict(input_data):
"""Main prediction function"""
# Your ML model logic here
features = np.array(input_data)
# Simple linear model example
result = np.sum(features) * 0.5
return float(result)
def get_model_info():
"""Optional: Return model metadata"""
return {
"name": "My Model",
"version": "1.0.0",
"type": "regression"
}
python-react-ml bundle model.py -o my-model.bundle.zip
import { useModel } from '@python-react-ml/react';
function MyApp() {
const { model, status, predict, error } = useModel('/my-model.bundle.zip');
const handlePredict = async () => {
if (model) {
const result = await predict([1.0, 2.0, 3.0]);
console.log('Prediction:', result);
}
};
if (status === 'loading') return <div>Loading model...</div>;
if (status === 'error') return <div>Error: {error}</div>;
return (
<div>
<h1>Python ML in React!</h1>
<button onClick={handlePredict} disabled={status !== 'ready'}>
Run Prediction
</button>
</div>
);
}
Package | Description | Size |
---|---|---|
@python-react-ml/core |
Core Python execution engine | |
@python-react-ml/react |
React hooks and components | |
@python-react-ml/react-native |
React Native native bridge | |
@python-react-ml/cli |
CLI tools for bundling |
import { useModel } from '@python-react-ml/react';
function ModelComponent() {
const { model, status, predict, reload } = useModel('/path/to/model.bundle.zip');
return (
<div>
<p>Status: {status}</p>
{status === 'ready' && (
<button onClick={() => predict([1, 2, 3])}>
Predict
</button>
)}
</div>
);
}
import { PythonModelProvider, useModelContext } from '@python-react-ml/react';
function App() {
return (
<PythonModelProvider pyodideUrl="https://cdn.jsdelivr.net/pyodide/v0.24.1/full/pyodide.js">
<ModelComponent />
</PythonModelProvider>
);
}
function ModelComponent() {
const { loadModel, isInitialized } = useModelContext();
// Use context...
}
import { ModelLoader } from '@python-react-ml/react';
function App() {
return (
<ModelLoader
modelUrl="/model.bundle.zip"
onLoad={(model) => console.log('Model loaded!', model)}
onError={(error) => console.error('Load failed:', error)}
>
{({ status, model, predict }) => (
<div>
<p>Status: {status}</p>
{status === 'ready' && (
<button onClick={() => predict([1, 2, 3])}>
Predict
</button>
)}
</div>
)}
</ModelLoader>
);
}
import { useModelNative } from '@python-react-ml/react-native';
function ModelScreen() {
const {
isLoaded,
isLoading,
predict,
error
} = useModelNative('/path/to/model.bundle.zip');
const handlePredict = async () => {
try {
const result = await predict([1.0, 2.0, 3.0]);
Alert.alert('Result', `Prediction: ${result}`);
} catch (err) {
Alert.alert('Error', err.message);
}
};
return (
<View style={styles.container}>
<Text>Model Status: {isLoading ? 'Loading...' : isLoaded ? 'Ready' : 'Not loaded'}</Text>
{error && <Text style={styles.error}>Error: {error}</Text>}
<TouchableOpacity
onPress={handlePredict}
disabled={!isLoaded}
style={styles.button}
>
<Text>Run Prediction</Text>
</TouchableOpacity>
</View>
);
}
python-react-ml init my-project
cd my-project
python-react-ml validate model.py
# Basic bundling
python-react-ml bundle model.py
# Advanced options
python-react-ml bundle model.py \
--output my-model.bundle.zip \
--name "My Awesome Model" \
--version "1.2.0" \
--include data.pkl requirements.txt \
--deps numpy pandas scikit-learn
Main class for Python execution.
class PythonReactML {
constructor(options: PythonEngineOptions)
loadModelFromBundle(url: string): Promise<PythonModel>
loadModelFromFile(filePath: string): Promise<PythonModel>
cleanup(): Promise<void>
}
Represents a loaded Python model.
interface PythonModel {
manifest: PythonModelManifest;
predict: (input: any) => Promise<any>;
getInfo?: () => Promise<any>;
cleanup?: () => void;
}
Hook for loading and using a Python model.
interface UseModelResult {
model: PythonModel | null;
status: 'idle' | 'loading' | 'ready' | 'error';
error: string | null;
predict: (input: any) => Promise<any>;
reload: () => Promise<void>;
}
Hook for managing the Python engine.
interface PythonEngineState {
engine: PythonReactML | null;
isInitialized: boolean;
isLoading: boolean;
error: string | null;
}
python-react-ml init [name]
- Initialize new projectpython-react-ml bundle <entry>
- Bundle Python modelpython-react-ml validate <entry>
- Validate model code
Check out our examples directory for complete sample applications:
- React Web App - Complete web application
- React Native App - Mobile application
- Advanced Models - Complex ML models
- Python Code: Write your ML model in Python with a
predict()
function - Bundling: CLI tools package your Python code and dependencies into a ZIP bundle
- Runtime: In the browser, Pyodide (Python compiled to WebAssembly) executes your code
- React Integration: Hooks and components provide seamless integration
graph LR
A[Python Model] --> B[CLI Bundle]
B --> C[ZIP Bundle]
C --> D[React App]
D --> E[Pyodide/WebWorker]
E --> F[Python Execution]
We welcome contributions! Please see our Contributing Guide for details.
git clone https://github.com/yourusername/python-react-ml.git
cd python-react-ml
npm install
npm run build
npm test
npm run build
npm run publish:all
- Web: Limited to Pyodide-compatible packages (most popular ML libraries supported)
- File Size: Bundles can be large due to Python runtime
- Performance: Slightly slower than native Python (but often faster than server round-trips)
- React Native: Requires native bridge implementation (iOS/Android) We will see how can we optimize it in the long run
- Support for TensorFlow.js integration
- Model caching and lazy loading
- Performance optimizations
- More ML framework examples
- Advanced debugging tools
MIT Β© Shyam Sathish (https://github.com/ShyamSathish005) MIT Β© Siddharth B (https://github.com/Siddharth-B) MIT Β© Sathyanrayanaa. T (https://github.com/Sathyanrayanaa-T)
- Pyodide - Python in the browser
- React - UI library
- TypeScript - Type safety
Made with β€οΈ for developers who want to bring Python ML to the Frontend