
{"id":7940,"date":"2025-08-30T13:01:00","date_gmt":"2025-08-30T05:01:00","guid":{"rendered":"https:\/\/meta-quantum.today\/?p=7940"},"modified":"2025-08-30T13:23:00","modified_gmt":"2025-08-30T05:23:00","slug":"python-rust-streamlit-complete-integration-guide","status":"publish","type":"post","link":"https:\/\/meta-quantum.today\/?p=7940","title":{"rendered":"Python + Rust + Streamlit: Complete Integration Guide"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Table of Contents<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a href=\"#01\" title=\"Architecture Overview\">Architecture Overview<\/a><\/li>\n\n\n\n<li><a href=\"#02\" title=\"Prerequisites &amp; Installation\">Prerequisites &amp; Installation<\/a><\/li>\n\n\n\n<li><a href=\"#03\" title=\"Setting Up Rust Extension for Python\">Setting Up Rust Extension for Python<\/a><\/li>\n\n\n\n<li><a href=\"#04\" title=\"Creating Streamlit Web Applications\">Creating Streamlit Web Applications<\/a><\/li>\n\n\n\n<li><a href=\"#05\" title=\"Mobile App Solutions\">Mobile App Solutions<\/a><\/li>\n\n\n\n<li><a href=\"#06\" title=\"Complete Working Examples\">Complete Working Examples<\/a><\/li>\n\n\n\n<li><a href=\"#07\" title=\"Deployment &amp; Production\">Deployment &amp; Production<\/a><\/li>\n\n\n\n<li><a href=\"#08\" title=\"Troubleshooting\">Troubleshooting<\/a><\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">About Python, Rust, and Streamlit integration <\/h2>\n\n\n\n<p>Python, Rust, and Streamlit integration that covers all the essential aspects of this technology combination.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83c\udfaf <strong>Key Highlights:<\/strong><\/h2>\n\n\n\n<p><strong>\ud83d\udc65 WHO<\/strong>: Data scientists, software engineers, ML engineers, and startup teams who need high-performance web applications<\/p>\n\n\n\n<p><strong>\ud83d\udccb WHAT<\/strong>: A powerful integration combining Python&#8217;s ecosystem, Rust&#8217;s performance, and Streamlit&#8217;s rapid UI development<\/p>\n\n\n\n<p><strong>\u23f0 WHEN<\/strong>: Ideal for performance bottlenecks, real-time processing, and large dataset analysis &#8211; with a clear 6-week implementation timeline<\/p>\n\n\n\n<p><strong>\ud83c\udf0d WHERE<\/strong>: Applicable across financial services, healthcare, manufacturing, and research sectors with flexible cloud\/edge deployment options<\/p>\n\n\n\n<p><strong>\ud83c\udfaf WHY<\/strong>: Delivers 10-100x performance improvements, 50-70% faster development, and 30-60% infrastructure cost reduction<\/p>\n\n\n\n<p><strong>\u2699\ufe0f HOW<\/strong>: Three-phase implementation strategy with concrete code examples, testing frameworks, and production deployment options<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udcca <strong>Business Impact:<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Development Speed<\/strong>: 50-70% faster than traditional approaches<\/li>\n\n\n\n<li><strong>Performance Gains<\/strong>: Up to 100x improvement in computational tasks<\/li>\n\n\n\n<li><strong>Cost Savings<\/strong>: 30-60% reduction in infrastructure expenses<\/li>\n\n\n\n<li><strong>Time-to-Market<\/strong>: Launch products weeks earlier than competitors<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"01\">Architecture Overview<\/h2>\n\n\n\n<p>This guide demonstrates how to create high-performance web and mobile applications by combining:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Rust<\/strong>: High-performance backend computations and data processing<\/li>\n\n\n\n<li><strong>Python<\/strong>: Application logic, data science libraries, and glue code<\/li>\n\n\n\n<li><strong>Streamlit<\/strong>: Rapid web UI development and deployment<\/li>\n\n\n\n<li><strong>Mobile Integration<\/strong>: Responsive web design and mobile app packaging<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502   Mobile App    \u2502    \u2502   Web Browser    \u2502    \u2502  Streamlit App  \u2502\n\u2502  (Capacitor\/    \u2502\u25c4\u2500\u2500\u25ba\u2502   (Responsive)   \u2502\u25c4\u2500\u2500\u25ba\u2502   (Python)      \u2502\n\u2502   React Native) \u2502    \u2502                  \u2502    \u2502                 \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n                                                         \u2502\n                                                         \u25bc\n                                                \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n                                                \u2502  Rust Extensions\u2502\n                                                \u2502  (PyO3\/maturin) \u2502\n                                                \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"02\">Prerequisites &amp; Installation<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">System Requirements<\/h3>\n\n\n\n<p><strong>For Windows:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code># Install Rust\nwinget install Rustlang.Rust.MSVC\n\n# Install Python (3.8 or higher)\nwinget install Python.Python.3.11\n\n# Install Visual Studio Build Tools\nwinget install Microsoft.VisualStudio.2022.BuildTools<\/code><\/pre>\n\n\n\n<p><strong>For macOS:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code># Install Rust\ncurl --proto '=https' --tlsv1.2 -sSf &lt;https:\/\/sh.rustup.rs&gt; | sh\n\n# Install Python via Homebrew\nbrew install python@3.11\n\n# Install Xcode command line tools\nxcode-select --install<\/code><\/pre>\n\n\n\n<p><strong>For Linux (Ubuntu\/Debian):<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code># Install Rust\ncurl --proto '=https' --tlsv1.2 -sSf &lt;https:\/\/sh.rustup.rs&gt; | sh\n\n# Install Python and development tools\nsudo apt update\nsudo apt install python3.11 python3.11-dev python3-pip build-essential\n\n# Install additional dependencies\nsudo apt install pkg-config libssl-dev<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Python Dependencies<\/h3>\n\n\n\n<p>Create a virtual environment and install required packages:<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code># Create virtual environment\npython -m venv venv\n\n# Activate virtual environment\n# Windows:\nvenv\\\\Scripts\\\\activate\n# macOS\/Linux:\nsource venv\/bin\/activate\n\n# Install core dependencies\npip install --upgrade pip\npip install streamlit pandas numpy matplotlib plotly\npip install maturin pyo3 setuptools-rust\n\n# For mobile app development\npip install streamlit-mobile-components<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Rust Setup<\/h3>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code># Install maturin for Python-Rust integration\npip install maturin\n\n# Add Python target for Rust\nrustup target add x86_64-unknown-linux-gnu  # Linux\nrustup target add x86_64-apple-darwin       # macOS\nrustup target add x86_64-pc-windows-msvc    # Windows\n\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"03\">Setting Up Rust Extension for Python<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Project Structure<\/h3>\n\n\n\n<p>Create the following project structure:<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>my_app\/\n\u251c\u2500\u2500 Cargo.toml\n\u251c\u2500\u2500 pyproject.toml\n\u251c\u2500\u2500 src\/\n\u2502   \u2514\u2500\u2500 lib.rs\n\u251c\u2500\u2500 streamlit_app.py\n\u251c\u2500\u2500 mobile\/\n\u2502   \u251c\u2500\u2500 capacitor.config.ts\n\u2502   \u2514\u2500\u2500 public\/\n\u2514\u2500\u2500 requirements.txt\n\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Cargo.toml Configuration<\/h3>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>&#91;package]\nname = \"my_rust_extension\"\nversion = \"0.1.0\"\nedition = \"2021\"\n&#91;lib]\nname = \"my_rust_extension\"\ncrate-type = &#91;\"cdylib\"]\n&#91;dependencies]\npyo3 = { version = \"0.20\", features = &#91;\"extension-module\"] }\nnumpy = \"0.20\"\nrayon = \"1.8\"  # For parallel processing\nserde = { version = \"1.0\", features = &#91;\"derive\"] }\nserde_json = \"1.0\"\n\n&#91;dependencies.pyo3]\nversion = \"0.20\"\nfeatures = &#91;\"extension-module\", \"abi3-py38\"]\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">pyproject.toml Configuration<\/h3>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>&#91;build-system]\nrequires = &#91;\"maturin&gt;=1.0,&lt;2.0\"]\nbuild-backend = \"maturin\"\n\n&#91;project]\nname = \"my-rust-extension\"\nversion = \"0.1.0\"\ndescription = \"High-performance Python extension written in Rust\"\nrequires-python = \"&gt;=3.8\"\ndependencies = &#91;\n    \"streamlit&gt;=1.28.0\",\n    \"pandas&gt;=1.5.0\",\n    \"numpy&gt;=1.20.0\",\n    \"plotly&gt;=5.0.0\",\n]\n\n&#91;project.optional-dependencies]\ndev = &#91;\n    \"maturin&gt;=1.0,&lt;2.0\",\n    \"pytest&gt;=7.0.0\",\n]\n\n&#91;tool.maturin]\npython-source = \"python\"\nmodule-name = \"my_rust_extension._internal\"\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Rust Library Code (src\/lib.rs)<\/h3>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>use pyo3::prelude::*;\nuse pyo3::types::{PyList, PyDict};\nuse rayon::prelude::*;\nuse std::collections::HashMap;\n\n\/\/\/ Fast mathematical operations\n#&#91;pyfunction]\nfn fast_fibonacci(n: u64) -&gt; PyResult&lt;u64&gt; {\n    fn fib(n: u64) -&gt; u64 {\n        match n {\n            0 =&gt; 0,\n            1 =&gt; 1,\n            _ =&gt; {\n                let mut a = 0u64;\n                let mut b = 1u64;\n                for _ in 2..=n {\n                    let temp = a.saturating_add(b);\n                    a = b;\n                    b = temp;\n                }\n                b\n            }\n        }\n    }\n    Ok(fib(n))\n}\n\n\/\/\/ Parallel data processing\n#&#91;pyfunction]\nfn parallel_sum(data: Vec&lt;f64&gt;) -&gt; PyResult&lt;f64&gt; {\n    let sum: f64 = data.par_iter().sum();\n    Ok(sum)\n}\n\n\/\/\/ Fast string processing\n#&#91;pyfunction]\nfn fast_word_count(text: String) -&gt; PyResult&lt;HashMap&lt;String, usize&gt;&gt; {\n    let mut word_count: HashMap&lt;String, usize&gt; = HashMap::new();\n\n    text.split_whitespace()\n        .map(|word| word.to_lowercase().trim_matches(|c: char| !c.is_alphanumeric()).to_string())\n        .filter(|word| !word.is_empty())\n        .for_each(|word| {\n            *word_count.entry(word).or_insert(0) += 1;\n        });\n\n    Ok(word_count)\n}\n\n\/\/\/ Data analysis functions\n#&#91;pyfunction]\nfn fast_moving_average(data: Vec&lt;f64&gt;, window: usize) -&gt; PyResult&lt;Vec&lt;f64&gt;&gt; {\n    if window == 0 || data.is_empty() {\n        return Ok(vec!&#91;]);\n    }\n\n    let result: Vec&lt;f64&gt; = data\n        .windows(window)\n        .map(|window| window.iter().sum::&lt;f64&gt;() \/ window.len() as f64)\n        .collect();\n\n    Ok(result)\n}\n\n\/\/\/ Complex number operations\n#&#91;pyclass]\n#&#91;derive(Clone)]\nstruct ComplexNumber {\n    #&#91;pyo3(get, set)]\n    real: f64,\n    #&#91;pyo3(get, set)]\n    imag: f64,\n}\n\n#&#91;pymethods]\nimpl ComplexNumber {\n    #&#91;new]\n    fn new(real: f64, imag: f64) -&gt; Self {\n        ComplexNumber { real, imag }\n    }\n\n    fn magnitude(&amp;self) -&gt; f64 {\n        (self.real * self.real + self.imag * self.imag).sqrt()\n    }\n\n    fn add(&amp;self, other: &amp;ComplexNumber) -&gt; ComplexNumber {\n        ComplexNumber {\n            real: self.real + other.real,\n            imag: self.imag + other.imag,\n        }\n    }\n\n    fn __repr__(&amp;self) -&gt; String {\n        format!(\"{}+{}i\", self.real, self.imag)\n    }\n}\n\n\/\/\/ Python module\n#&#91;pymodule]\nfn my_rust_extension(_py: Python, m: &amp;PyModule) -&gt; PyResult&lt;()&gt; {\n    m.add_function(wrap_pyfunction!(fast_fibonacci, m)?)?;\n    m.add_function(wrap_pyfunction!(parallel_sum, m)?)?;\n    m.add_function(wrap_pyfunction!(fast_word_count, m)?)?;\n    m.add_function(wrap_pyfunction!(fast_moving_average, m)?)?;\n    m.add_class::&lt;ComplexNumber&gt;()?;\n    Ok(())\n}\n\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Building the Rust Extension<\/h3>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code># Develop build (faster compilation)\nmaturin develop\n\n# Release build (optimized)\nmaturin develop --release\n\n# Build wheel for distribution\nmaturin build --release\n\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"04\">Creating Streamlit Web Applications<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Main Streamlit Application (streamlit_app.py)<\/h3>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>import streamlit as st\nimport pandas as pd\nimport numpy as np\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom typing import Dict, List\nimport time\n\n# Import our Rust extension\ntry:\n    import my_rust_extension\n    RUST_AVAILABLE = True\nexcept ImportError:\n    RUST_AVAILABLE = False\n    st.warning(\"\u26a0\ufe0f Rust extension not available. Install with: maturin develop\")\n\n# Configure page\nst.set_page_config(\n    page_title=\"Python + Rust + Streamlit App\",\n    page_icon=\"\ud83d\ude80\",\n    layout=\"wide\",\n    initial_sidebar_state=\"expanded\"\n)\n\n# Custom CSS for mobile responsiveness\nst.markdown(\"\"\"\n&lt;style&gt;\n    .main .block-container {\n        padding-top: 2rem;\n        padding-bottom: 2rem;\n    }\n\n    @media (max-width: 768px) {\n        .main .block-container {\n            padding-left: 1rem;\n            padding-right: 1rem;\n        }\n\n        .stButton &gt; button {\n            width: 100%;\n        }\n    }\n\n    .metric-card {\n        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);\n        padding: 1rem;\n        border-radius: 0.5rem;\n        color: white;\n        margin: 0.5rem 0;\n    }\n\n    .performance-badge {\n        background-color: #10b981;\n        color: white;\n        padding: 0.2rem 0.5rem;\n        border-radius: 0.25rem;\n        font-size: 0.8rem;\n        font-weight: bold;\n    }\n&lt;\/style&gt;\n\"\"\", unsafe_allow_html=True)\n\ndef main():\n    st.title(\"\ud83d\ude80 Python + Rust + Streamlit Integration\")\n    st.markdown(\"*High-performance web applications with Rust-powered backend*\")\n\n    # Sidebar navigation\n    st.sidebar.title(\"Navigation\")\n    page = st.sidebar.selectbox(\n        \"Choose a demo:\",\n        &#91;\"Performance Comparison\", \"Data Processing\", \"Text Analysis\", \"Mathematical Operations\", \"Complex Numbers\"]\n    )\n\n    if page == \"Performance Comparison\":\n        performance_demo()\n    elif page == \"Data Processing\":\n        data_processing_demo()\n    elif page == \"Text Analysis\":\n        text_analysis_demo()\n    elif page == \"Mathematical Operations\":\n        math_demo()\n    elif page == \"Complex Numbers\":\n        complex_numbers_demo()\n\ndef performance_demo():\n    st.header(\"\u26a1 Performance Comparison: Python vs Rust\")\n\n    col1, col2 = st.columns(2)\n\n    with col1:\n        st.subheader(\"Fibonacci Calculation\")\n        n = st.slider(\"Calculate Fibonacci of:\", 1, 50, 35)\n\n        if st.button(\"Run Benchmark\", key=\"fib_benchmark\"):\n            # Python implementation\n            def python_fibonacci(n):\n                if n &lt;= 1:\n                    return n\n                a, b = 0, 1\n                for _ in range(2, n + 1):\n                    a, b = b, a + b\n                return b\n\n            # Benchmark Python\n            start_time = time.time()\n            python_result = python_fibonacci(n)\n            python_time = time.time() - start_time\n\n            # Benchmark Rust (if available)\n            if RUST_AVAILABLE:\n                start_time = time.time()\n                rust_result = my_rust_extension.fast_fibonacci(n)\n                rust_time = time.time() - start_time\n                speedup = python_time \/ rust_time if rust_time &gt; 0 else float('inf')\n            else:\n                rust_result = \"N\/A\"\n                rust_time = 0\n                speedup = 0\n\n            # Display results\n            col1_1, col1_2 = st.columns(2)\n            with col1_1:\n                st.metric(\"Python Result\", f\"{python_result:,}\")\n                st.metric(\"Python Time\", f\"{python_time:.6f}s\")\n\n            with col1_2:\n                if RUST_AVAILABLE:\n                    st.metric(\"Rust Result\", f\"{rust_result:,}\")\n                    st.metric(\"Rust Time\", f\"{rust_time:.6f}s\")\n                    st.markdown(f'&lt;div class=\"performance-badge\"&gt;\ud83d\ude80 {speedup:.1f}x faster&lt;\/div&gt;',\n                              unsafe_allow_html=True)\n\n    with col2:\n        st.subheader(\"Parallel Array Sum\")\n        array_size = st.selectbox(\"Array Size:\", &#91;10_000, 100_000, 1_000_000, 10_000_000])\n\n        if st.button(\"Run Parallel Benchmark\", key=\"parallel_benchmark\"):\n            # Generate test data\n            data = np.random.randn(array_size).tolist()\n\n            # Python sum\n            start_time = time.time()\n            python_sum = sum(data)\n            python_time = time.time() - start_time\n\n            # Rust parallel sum (if available)\n            if RUST_AVAILABLE:\n                start_time = time.time()\n                rust_sum = my_rust_extension.parallel_sum(data)\n                rust_time = time.time() - start_time\n                speedup = python_time \/ rust_time if rust_time &gt; 0 else float('inf')\n            else:\n                rust_sum = \"N\/A\"\n                rust_time = 0\n                speedup = 0\n\n            # Display results\n            st.metric(\"Array Size\", f\"{array_size:,}\")\n            col2_1, col2_2 = st.columns(2)\n            with col2_1:\n                st.metric(\"Python Sum\", f\"{python_sum:.2f}\")\n                st.metric(\"Python Time\", f\"{python_time:.6f}s\")\n\n            with col2_2:\n                if RUST_AVAILABLE:\n                    st.metric(\"Rust Sum\", f\"{rust_sum:.2f}\")\n                    st.metric(\"Rust Time\", f\"{rust_time:.6f}s\")\n                    st.markdown(f'&lt;div class=\"performance-badge\"&gt;\ud83d\ude80 {speedup:.1f}x faster&lt;\/div&gt;',\n                              unsafe_allow_html=True)\n\ndef data_processing_demo():\n    st.header(\"\ud83d\udcca Data Processing with Rust\")\n\n    # File upload\n    uploaded_file = st.file_uploader(\"Upload CSV file\", type=&#91;'csv'])\n\n    if uploaded_file is not None:\n        df = pd.read_csv(uploaded_file)\n        st.write(\"Data Preview:\", df.head())\n\n        # Select numeric column for moving average\n        numeric_cols = df.select_dtypes(include=&#91;np.number]).columns.tolist()\n        if numeric_cols:\n            selected_col = st.selectbox(\"Select column for moving average:\", numeric_cols)\n            window_size = st.slider(\"Window size:\", 2, 50, 5)\n\n            if st.button(\"Calculate Moving Average\"):\n                data = df&#91;selected_col].dropna().tolist()\n\n                if RUST_AVAILABLE:\n                    # Use Rust for fast moving average\n                    moving_avg = my_rust_extension.fast_moving_average(data, window_size)\n                    st.success(f\"\u2705 Calculated {len(moving_avg)} moving average points using Rust!\")\n                else:\n                    # Fallback to pandas\n                    moving_avg = df&#91;selected_col].rolling(window=window_size).mean().dropna().tolist()\n                    st.info(\"\ud83d\udcca Calculated moving average using pandas (Rust not available)\")\n\n                # Plot results\n                fig = go.Figure()\n                fig.add_trace(go.Scatter(y=data, name=\"Original Data\", opacity=0.7))\n                fig.add_trace(go.Scatter(y=moving_avg, name=f\"Moving Average (window={window_size})\",\n                                       line=dict(width=3)))\n                fig.update_layout(title=\"Moving Average Analysis\", xaxis_title=\"Index\", yaxis_title=\"Value\")\n                st.plotly_chart(fig, use_container_width=True)\n\n    else:\n        # Demo with generated data\n        st.info(\"Upload a CSV file or use the demo data below\")\n\n        if st.button(\"Generate Demo Data\"):\n            # Create sample data\n            np.random.seed(42)\n            dates = pd.date_range('2023-01-01', periods=365)\n            values = 100 + np.cumsum(np.random.randn(365) * 0.5)\n            df = pd.DataFrame({'date': dates, 'value': values})\n\n            st.write(\"Demo Data:\", df.head())\n\n            # Calculate moving average\n            window_size = st.slider(\"Window size:\", 2, 50, 7, key=\"demo_window\")\n\n            if RUST_AVAILABLE:\n                moving_avg = my_rust_extension.fast_moving_average(values.tolist(), window_size)\n                st.success(\"\u2705 Using Rust for high-performance calculation!\")\n            else:\n                moving_avg = df&#91;'value'].rolling(window=window_size).mean().dropna().tolist()\n                st.info(\"\ud83d\udcca Using pandas (Rust extension not available)\")\n\n            # Create chart\n            fig = go.Figure()\n            fig.add_trace(go.Scatter(x=df&#91;'date'], y=df&#91;'value'], name=\"Original Data\", opacity=0.6))\n\n            if moving_avg:\n                avg_dates = dates&#91;window_size-1:len(moving_avg)+window_size-1]\n                fig.add_trace(go.Scatter(x=avg_dates, y=moving_avg,\n                                       name=f\"Moving Average ({window_size}d)\",\n                                       line=dict(width=3, color='red')))\n\n            fig.update_layout(title=\"Stock Price Moving Average\",\n                            xaxis_title=\"Date\", yaxis_title=\"Price ($)\")\n            st.plotly_chart(fig, use_container_width=True)\n\ndef text_analysis_demo():\n    st.header(\"\ud83d\udcdd Text Analysis with Rust\")\n\n    # Text input\n    text_input = st.text_area(\n        \"Enter text for analysis:\",\n        value=\"The quick brown fox jumps over the lazy dog. The dog was sleeping peacefully.\",\n        height=150\n    )\n\n    if st.button(\"Analyze Text\"):\n        if text_input:\n            if RUST_AVAILABLE:\n                # Use Rust for fast word counting\n                start_time = time.time()\n                word_count = my_rust_extension.fast_word_count(text_input)\n                rust_time = time.time() - start_time\n                st.success(f\"\u2705 Analysis completed using Rust in {rust_time:.6f}s\")\n            else:\n                # Fallback to Python\n                start_time = time.time()\n                words = text_input.lower().split()\n                word_count = {}\n                for word in words:\n                    clean_word = ''.join(c for c in word if c.isalnum())\n                    if clean_word:\n                        word_count&#91;clean_word] = word_count.get(clean_word, 0) + 1\n                python_time = time.time() - start_time\n                st.info(f\"\ud83d\udcca Analysis completed using Python in {python_time:.6f}s\")\n\n            # Display results\n            col1, col2 = st.columns(2)\n\n            with col1:\n                st.subheader(\"Word Count Statistics\")\n                total_words = sum(word_count.values())\n                unique_words = len(word_count)\n                st.metric(\"Total Words\", total_words)\n                st.metric(\"Unique Words\", unique_words)\n                st.metric(\"Vocabulary Richness\", f\"{unique_words\/total_words:.2%}\")\n\n            with col2:\n                st.subheader(\"Most Common Words\")\n                sorted_words = sorted(word_count.items(), key=lambda x: x&#91;1], reverse=True)\n                for word, count in sorted_words&#91;:10]:\n                    st.write(f\"**{word}**: {count}\")\n\n            # Word frequency chart\n            if len(word_count) &gt; 1:\n                top_words = dict(sorted_words&#91;:15])\n                fig = px.bar(\n                    x=list(top_words.keys()),\n                    y=list(top_words.values()),\n                    title=\"Word Frequency Distribution\"\n                )\n                fig.update_layout(xaxis_title=\"Words\", yaxis_title=\"Frequency\")\n                st.plotly_chart(fig, use_container_width=True)\n\ndef math_demo():\n    st.header(\"\ud83d\udd22 Mathematical Operations\")\n\n    col1, col2 = st.columns(2)\n\n    with col1:\n        st.subheader(\"Fibonacci Sequence\")\n        fib_n = st.number_input(\"Calculate Fibonacci up to n:\", min_value=1, max_value=100, value=20)\n\n        if st.button(\"Generate Sequence\"):\n            if RUST_AVAILABLE:\n                fib_sequence = &#91;my_rust_extension.fast_fibonacci(i) for i in range(fib_n)]\n                st.success(\"\u2705 Generated using Rust!\")\n            else:\n                def fib(n):\n                    if n &lt;= 1:\n                        return n\n                    a, b = 0, 1\n                    for _ in range(2, n + 1):\n                        a, b = b, a + b\n                    return b\n                fib_sequence = &#91;fib(i) for i in range(fib_n)]\n                st.info(\"\ud83d\udcca Generated using Python\")\n\n            # Display sequence\n            st.write(\"Sequence:\", fib_sequence&#91;:20])  # Show first 20\n\n            # Plot growth\n            fig = px.line(x=range(len(fib_sequence)), y=fib_sequence,\n                         title=\"Fibonacci Sequence Growth\")\n            fig.update_layout(xaxis_title=\"n\", yaxis_title=\"F(n)\")\n            st.plotly_chart(fig, use_container_width=True)\n\n    with col2:\n        st.subheader(\"Array Statistics\")\n        array_size = st.selectbox(\"Array size:\", &#91;1000, 10000, 100000])\n\n        if st.button(\"Generate &amp; Analyze\"):\n            # Generate random array\n            data = np.random.randn(array_size).tolist()\n\n            if RUST_AVAILABLE:\n                total_sum = my_rust_extension.parallel_sum(data)\n                st.success(\"\u2705 Calculated using Rust parallel processing!\")\n            else:\n                total_sum = sum(data)\n                st.info(\"\ud83d\udcca Calculated using Python\")\n\n            # Statistics\n            mean_val = total_sum \/ len(data)\n            std_val = np.std(data)\n\n            st.metric(\"Array Size\", f\"{array_size:,}\")\n            st.metric(\"Sum\", f\"{total_sum:.4f}\")\n            st.metric(\"Mean\", f\"{mean_val:.4f}\")\n            st.metric(\"Std Dev\", f\"{std_val:.4f}\")\n\n            # Histogram\n            fig = px.histogram(data, bins=50, title=\"Data Distribution\")\n            st.plotly_chart(fig, use_container_width=True)\n\ndef complex_numbers_demo():\n    st.header(\"\ud83d\udd22 Complex Number Operations\")\n\n    if not RUST_AVAILABLE:\n        st.warning(\"\u26a0\ufe0f This demo requires the Rust extension. Please run: maturin develop\")\n        return\n\n    col1, col2 = st.columns(2)\n\n    with col1:\n        st.subheader(\"Create Complex Numbers\")\n        real1 = st.number_input(\"Real part (first):\", value=3.0)\n        imag1 = st.number_input(\"Imaginary part (first):\", value=4.0)\n\n        real2 = st.number_input(\"Real part (second):\", value=1.0)\n        imag2 = st.number_input(\"Imaginary part (second):\", value=2.0)\n\n    with col2:\n        st.subheader(\"Results\")\n        if st.button(\"Calculate\"):\n            # Create complex numbers using Rust\n            c1 = my_rust_extension.ComplexNumber(real1, imag1)\n            c2 = my_rust_extension.ComplexNumber(real2, imag2)\n\n            # Operations\n            sum_result = c1.add(c2)\n\n            st.write(f\"**Number 1**: {c1}\")\n            st.write(f\"**Number 2**: {c2}\")\n            st.write(f\"**Sum**: {sum_result}\")\n            st.write(f\"**Magnitude 1**: {c1.magnitude():.4f}\")\n            st.write(f\"**Magnitude 2**: {c2.magnitude():.4f}\")\n\n            # Visualization\n            fig = go.Figure()\n            fig.add_trace(go.Scatter(x=&#91;0, real1], y=&#91;0, imag1], mode='lines+markers',\n                                   name=f'Number 1: {c1}', line=dict(width=3)))\n            fig.add_trace(go.Scatter(x=&#91;0, real2], y=&#91;0, imag2], mode='lines+markers',\n                                   name=f'Number 2: {c2}', line=dict(width=3)))\n            fig.add_trace(go.Scatter(x=&#91;0, sum_result.real], y=&#91;0, sum_result.imag],\n                                   mode='lines+markers', name=f'Sum: {sum_result}',\n                                   line=dict(width=3, dash='dash')))\n\n            fig.update_layout(title=\"Complex Numbers Visualization\",\n                            xaxis_title=\"Real\", yaxis_title=\"Imaginary\",\n                            showlegend=True)\n            fig.add_hline(y=0, line_dash=\"dot\", line_color=\"gray\")\n            fig.add_vline(x=0, line_dash=\"dot\", line_color=\"gray\")\n\n            st.plotly_chart(fig, use_container_width=True)\n\nif __name__ == \"__main__\":\n    main()\n\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"05\">Mobile App Solutions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Option 1: Responsive Streamlit Web App<\/h3>\n\n\n\n<p>Create a mobile-optimized CSS file (<code>mobile_styles.css<\/code>):<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>\/* Mobile-first responsive design *\/\n@media (max-width: 768px) {\n    .main .block-container {\n        padding-left: 1rem !important;\n        padding-right: 1rem !important;\n        max-width: 100% !important;\n    }\n\n    .stSelectbox &gt; div &gt; div {\n        font-size: 14px;\n    }\n\n    .stButton &gt; button {\n        width: 100%;\n        margin-bottom: 1rem;\n    }\n\n    .stColumns {\n        flex-direction: column !important;\n    }\n\n    .stMetric {\n        text-align: center;\n        padding: 1rem;\n        border: 1px solid #e0e0e0;\n        border-radius: 8px;\n        margin-bottom: 1rem;\n    }\n}\n\n\/* Touch-friendly interface *\/\nbutton, select, input {\n    min-height: 44px !important;\n    font-size: 16px !important;\n}\n\n\/* Progressive Web App styles *\/\n.pwa-header {\n    position: sticky;\n    top: 0;\n    background: white;\n    z-index: 1000;\n    padding: 1rem;\n    border-bottom: 1px solid #e0e0e0;\n}\n\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Option 2: Capacitor Mobile App Wrapper<\/h3>\n\n\n\n<p>Install Capacitor for mobile app packaging:<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>npm install -g @capacitor\/cli\nnpm install @capacitor\/core @capacitor\/ios @capacitor\/android\n\n<\/code><\/pre>\n\n\n\n<p>Create <code>capacitor.config.ts<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>import { CapacitorConfig } from '@capacitor\/cli';\n\nconst config: CapacitorConfig = {\n  appId: 'com.yourcompany.rustpythonapp',\n  appName: 'Rust Python App',\n  webDir: 'dist',\n  server: {\n    url: '&lt;https:\/\/your-streamlit-app.herokuapp.com&gt;',\n    cleartext: true\n  },\n  plugins: {\n    SplashScreen: {\n      launchShowDuration: 2000,\n      backgroundColor: \"#667eea\",\n      showSpinner: true,\n      spinnerColor: \"#ffffff\"\n    },\n    StatusBar: {\n      style: \"dark\",\n      backgroundColor: \"#667eea\"\n    }\n  }\n};\n\nexport default config;\n\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Option 3: FastAPI + Mobile Frontend<\/h3>\n\n\n\n<p>Create an API backend (<code>api_backend.py<\/code>):<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>from fastapi import FastAPI, HTTPException\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom pydantic import BaseModel\nfrom typing import List, Dict\nimport my_rust_extension\n\napp = FastAPI(title=\"Rust Python API\", version=\"1.0.0\")\n\n# Enable CORS for mobile apps\napp.add_middleware(\n    CORSMiddleware,\n    allow_origins=&#91;\"*\"],\n    allow_credentials=True,\n    allow_methods=&#91;\"*\"],\n    allow_headers=&#91;\"*\"],\n)\n\nclass FibonacciRequest(BaseModel):\n    n: int\n\nclass TextAnalysisRequest(BaseModel):\n    text: str\n\nclass ArrayRequest(BaseModel):\n    data: List&#91;float]\n    window: int = 5\n\n@app.get(\"\/\")\nasync def root():\n    return {\"message\": \"Rust Python API is running!\"}\n\n@app.post(\"\/fibonacci\")\nasync def calculate_fibonacci(request: FibonacciRequest):\n    try:\n        result = my_rust_extension.fast_fibonacci(request.n)\n        return {\"n\": request.n, \"result\": result}\n    except Exception as e:\n        raise HTTPException(status_code=400, detail=str(e))\n\n@app.post(\"\/text-analysis\")\nasync def analyze_text(request: TextAnalysisRequest):\n    try:\n        word_count = my_rust_extension.fast_word_count(request.text)\n        total_words = sum(word_count.values())\n        unique_words = len(word_count)\n\n        return {\n            \"word_count\": word_count,\n            \"total_words\": total_words,\n            \"unique_words\": unique_words,\n            \"vocabulary_richness\": unique_words \/ total_words if total_words &gt; 0 else 0\n        }\n    except Exception as e:\n        raise HTTPException(status_code=400, detail=str(e))\n\n@app.post(\"\/moving-average\")\nasync def calculate_moving_average(request: ArrayRequest):\n    try:\n        result = my_rust_extension.fast_moving_average(request.data, request.window)\n        return {\"moving_average\": result, \"window\": request.window}\n    except Exception as e:\n        raise HTTPException(status_code=400, detail=str(e))\n\nif __name__ == \"__main__\":\n    import uvicorn\n    uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"06\">Complete Working Examples<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Example 1: Data Processing Pipeline<\/h3>\n\n\n\n<p>Create <code>data_pipeline.py<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>import streamlit as st\nimport pandas as pd\nimport numpy as np\nimport plotly.express as px\nimport my_rust_extension\nimport time\n\ndef main():\n    st.title(\"\ud83c\udfed High-Performance Data Pipeline\")\n\n    # Generate or upload data\n    st.sidebar.header(\"Data Source\")\n    data_source = st.sidebar.radio(\"Choose data source:\", &#91;\"Generate Sample\", \"Upload CSV\"])\n\n    if data_source == \"Generate Sample\":\n        rows = st.sidebar.slider(\"Number of rows:\", 1000, 1000000, 50000)\n\n        if st.sidebar.button(\"Generate Data\"):\n            with st.spinner(\"Generating data...\"):\n                np.random.seed(42)\n                data = {\n                    'timestamp': pd.date_range('2023-01-01', periods=rows, freq='1min'),\n                    'sensor1': np.random.randn(rows) * 10 + 50,\n                    'sensor2': np.random.randn(rows) * 5 + 25,\n                    'sensor3': np.random.randn(rows) * 15 + 100\n                }\n                df = pd.DataFrame(data)\n                st.session_state.df = df\n                st.success(f\"\u2705 Generated {rows:,} rows of sensor data!\")\n\n    if 'df' in st.session_state:\n        df = st.session_state.df\n\n        # Data overview\n        st.subheader(\"\ud83d\udcca Data Overview\")\n        col1, col2, col3, col4 = st.columns(4)\n        col1.metric(\"Rows\", f\"{len(df):,}\")\n        col2.metric(\"Columns\", len(df.columns))\n        col3.metric(\"Memory Usage\", f\"{df.memory_usage(deep=True).sum() \/ 1024**2:.1f} MB\")\n        col4.metric(\"Date Range\", f\"{(df&#91;'timestamp'].max() - df&#91;'timestamp'].min()).days} days\")\n\n        # Processing options\n        st.subheader(\"\u2699\ufe0f Processing Options\")\n        col1, col2 = st.columns(2)\n\n        with col1:\n            sensor_col = st.selectbox(\"Select sensor:\", &#91;'sensor1', 'sensor2', 'sensor3'])\n            window_size = st.slider(\"Moving average window:\", 2, 100, 10)\n\n        with col2:\n            operation = st.selectbox(\"Operation:\", &#91;\"Moving Average\", \"Sum\", \"Word Count (if text)\"])\n            use_rust = st.checkbox(\"Use Rust acceleration\", value=True)\n\n        if st.button(\"\ud83d\ude80 Process Data\"):\n            data_values = df&#91;sensor_col].tolist()\n\n            # Benchmark processing\n            if use_rust and operation == \"Moving Average\":\n                start_time = time.time()\n                result = my_rust_extension.fast_moving_average(data_values, window_size)\n                processing_time = time.time() - start_time\n                method = \"Rust (Parallel)\"\n            elif operation == \"Moving Average\":\n                start_time = time.time()\n                result = df&#91;sensor_col].rolling(window=window_size).mean().dropna().tolist()\n                processing_time = time.time() - start_time\n                method = \"Pandas\"\n            elif use_rust and operation == \"Sum\":\n                start_time = time.time()\n                result = &#91;my_rust_extension.parallel_sum(data_values)]\n                processing_time = time.time() - start_time\n                method = \"Rust (Parallel)\"\n            else:\n                start_time = time.time()\n                result = &#91;sum(data_values)]\n                processing_time = time.time() - start_time\n                method = \"Python\"\n\n            # Display results\n            st.success(f\"\u2705 Processed {len(data_values):,} points using {method} in {processing_time:.4f}s\")\n\n            # Visualization\n            if operation == \"Moving Average\":\n                fig = px.line(title=f\"{sensor_col} - Original vs Moving Average\")\n                fig.add_scatter(y=data_values, name=\"Original\", opacity=0.6)\n                fig.add_scatter(y=result, name=f\"Moving Avg ({window_size})\", line=dict(width=3))\n                st.plotly_chart(fig, use_container_width=True)\n            else:\n                st.metric(f\"{operation} Result\", f\"{result&#91;0]:,.2f}\")\n\nif __name__ == \"__main__\":\n    main()\n\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Example 2: Real-time Performance Monitor<\/h3>\n\n\n\n<p>Create <code>performance_monitor.py<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>import streamlit as st\nimport time\nimport psutil\nimport plotly.graph_objects as go\nfrom collections import deque\nimport threading\nimport my_rust_extension\n\nclass PerformanceMonitor:\n    def __init__(self, max_points=100):\n        self.max_points = max_points\n        self.timestamps = deque(maxlen=max_points)\n        self.cpu_usage = deque(maxlen=max_points)\n        self.memory_usage = deque(maxlen=max_points)\n        self.rust_times = deque(maxlen=max_points)\n        self.python_times = deque(maxlen=max_points)\n\n    def update_system_metrics(self):\n        self.timestamps.append(time.time())\n        self.cpu_usage.append(psutil.cpu_percent())\n        self.memory_usage.append(psutil.virtual_memory().percent)\n\n    def benchmark_operation(self, operation_size=10000):\n        # Generate test data\n        test_data = list(range(operation_size))\n\n        # Benchmark Python sum\n        start_time = time.time()\n        python_result = sum(test_data)\n        python_time = time.time() - start_time\n        self.python_times.append(python_time * 1000)  # Convert to ms\n\n        # Benchmark Rust sum\n        start_time = time.time()\n        rust_result = my_rust_extension.parallel_sum(&#91;float(x) for x in test_data])\n        rust_time = time.time() - start_time\n        self.rust_times.append(rust_time * 1000)  # Convert to ms\n\n        return python_time, rust_time, python_result, rust_result\n\ndef main():\n    st.title(\"\ud83d\udcc8 Real-time Performance Monitor\")\n\n    # Initialize monitor\n    if 'monitor' not in st.session_state:\n        st.session_state.monitor = PerformanceMonitor()\n\n    monitor = st.session_state.monitor\n\n    # Controls\n    col1, col2, col3 = st.columns(3)\n    with col1:\n        monitoring = st.checkbox(\"Enable Monitoring\", value=False)\n    with col2:\n        operation_size = st.selectbox(\"Operation Size:\", &#91;1000, 10000, 100000])\n    with col3:\n        auto_refresh = st.checkbox(\"Auto Refresh\", value=True)\n\n    # Create placeholders for real-time updates\n    metrics_placeholder = st.empty()\n    charts_placeholder = st.empty()\n\n    # Real-time monitoring loop\n    if monitoring or st.button(\"Take Snapshot\"):\n        monitor.update_system_metrics()\n        python_time, rust_time, python_result, rust_result = monitor.benchmark_operation(operation_size)\n\n        # Display current metrics\n        with metrics_placeholder.container():\n            col1, col2, col3, col4 = st.columns(4)\n            col1.metric(\"CPU Usage\", f\"{monitor.cpu_usage&#91;-1]:.1f}%\")\n            col2.metric(\"Memory Usage\", f\"{monitor.memory_usage&#91;-1]:.1f}%\")\n            col3.metric(\"Python Time\", f\"{python_time*1000:.2f}ms\")\n            col4.metric(\"Rust Time\", f\"{rust_time*1000:.2f}ms\",\n                       delta=f\"{((python_time\/rust_time - 1)*100):+.1f}%\")\n\n        # Create real-time charts\n        with charts_placeholder.container():\n            if len(monitor.timestamps) &gt; 1:\n                # System metrics chart\n                fig_system = go.Figure()\n                fig_system.add_trace(go.Scatter(\n                    x=list(monitor.timestamps),\n                    y=list(monitor.cpu_usage),\n                    name=\"CPU %\",\n                    mode='lines+markers'\n                ))\n                fig_system.add_trace(go.Scatter(\n                    x=list(monitor.timestamps),\n                    y=list(monitor.memory_usage),\n                    name=\"Memory %\",\n                    mode='lines+markers'\n                ))\n                fig_system.update_layout(title=\"System Metrics\", yaxis_title=\"Percentage\")\n                st.plotly_chart(fig_system, use_container_width=True)\n\n                # Performance comparison chart\n                fig_perf = go.Figure()\n                fig_perf.add_trace(go.Scatter(\n                    x=list(range(len(monitor.python_times))),\n                    y=list(monitor.python_times),\n                    name=\"Python\",\n                    mode='lines+markers',\n                    line=dict(color='blue')\n                ))\n                fig_perf.add_trace(go.Scatter(\n                    x=list(range(len(monitor.rust_times))),\n                    y=list(monitor.rust_times),\n                    name=\"Rust\",\n                    mode='lines+markers',\n                    line=dict(color='red')\n                ))\n                fig_perf.update_layout(title=\"Execution Time Comparison\",\n                                     yaxis_title=\"Time (ms)\", xaxis_title=\"Test Run\")\n                st.plotly_chart(fig_perf, use_container_width=True)\n\n        if monitoring and auto_refresh:\n            time.sleep(1)\n            st.experimental_rerun()\n\nif __name__ == \"__main__\":\n    main()\n\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"07\">Deployment &amp; Production<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Docker Configuration<\/h3>\n\n\n\n<p>Create <code>Dockerfile<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>FROM python:3.11-slim\n\n# Install system dependencies\nRUN apt-get update &amp;&amp; apt-get install -y \\\\\n    build-essential \\\\\n    curl \\\\\n    software-properties-common \\\\\n    git \\\\\n    pkg-config \\\\\n    libssl-dev \\\\\n    &amp;&amp; rm -rf \/var\/lib\/apt\/lists\/*\n\n# Install Rust\nRUN curl --proto '=https' --tlsv1.2 -sSf &lt;https:\/\/sh.rustup.rs&gt; | sh -s -- -y\nENV PATH=\"\/root\/.cargo\/bin:${PATH}\"\n\nWORKDIR \/app\n\n# Copy Rust and Python files\nCOPY Cargo.toml pyproject.toml .\/\nCOPY src\/ .\/src\/\nCOPY requirements.txt .\/\n\n# Install Python dependencies\nRUN pip install --upgrade pip\nRUN pip install -r requirements.txt\n\n# Build Rust extension\nRUN maturin develop --release\n\n# Copy Streamlit app\nCOPY streamlit_app.py .\/\nCOPY *.py .\/\n\nEXPOSE 8501\n\nHEALTHCHECK CMD curl --fail &lt;http:\/\/localhost:8501\/_stcore\/health&gt;\n\nENTRYPOINT &#91;\"streamlit\", \"run\", \"streamlit_app.py\", \"--server.port=8501\", \"--server.address=0.0.0.0\"]\n\n<\/code><\/pre>\n\n\n\n<p>Create <code>docker-compose.yml<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>version: '3.8'\n\nservices:\n  app:\n    build: .\n    ports:\n      - \"8501:8501\"\n    environment:\n      - PYTHONUNBUFFERED=1\n    volumes:\n      - .\/data:\/app\/data\n    restart: unless-stopped\n\n  nginx:\n    image: nginx:alpine\n    ports:\n      - \"80:80\"\n      - \"443:443\"\n    volumes:\n      - .\/nginx.conf:\/etc\/nginx\/nginx.conf\n      - .\/ssl:\/etc\/ssl\/certs\n    depends_on:\n      - app\n    restart: unless-stopped\n\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Heroku Deployment<\/h3>\n\n\n\n<p>Create <code>Procfile<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>web: streamlit run streamlit_app.py --server.port=$PORT --server.address=0.0.0.0\n\n<\/code><\/pre>\n\n\n\n<p>Create <code>runtime.txt<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>python-3.11.0\n\n<\/code><\/pre>\n\n\n\n<p>Create <code>setup.sh<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>#!\/bin\/bash\n\n# Install Rust\ncurl --proto '=https' --tlsv1.2 -sSf &lt;https:\/\/sh.rustup.rs&gt; | sh -s -- -y\nsource ~\/.cargo\/env\n\n# Build Rust extension\nmaturin develop --release\n\n# Run the app\nexec \"$@\"\n\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Cloud Function Deployment<\/h3>\n\n\n\n<p>For serverless deployment, create <code>cloud_function.py<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>import functions_framework\nfrom flask import jsonify, request\nimport my_rust_extension\n\n@functions_framework.http\ndef rust_python_api(request):\n    \"\"\"HTTP Cloud Function for Rust-Python operations.\"\"\"\n\n    if request.method == 'OPTIONS':\n        headers = {\n            'Access-Control-Allow-Origin': '*',\n            'Access-Control-Allow-Methods': 'POST',\n            'Access-Control-Allow-Headers': 'Content-Type',\n            'Access-Control-Max-Age': '3600'\n        }\n        return ('', 204, headers)\n\n    headers = {'Access-Control-Allow-Origin': '*'}\n\n    try:\n        request_json = request.get_json(silent=True)\n\n        if request_json and 'operation' in request_json:\n            operation = request_json&#91;'operation']\n\n            if operation == 'fibonacci':\n                n = request_json.get('n', 10)\n                result = my_rust_extension.fast_fibonacci(n)\n                return (jsonify({'result': result}), 200, headers)\n\n            elif operation == 'text_analysis':\n                text = request_json.get('text', '')\n                word_count = my_rust_extension.fast_word_count(text)\n                return (jsonify({'word_count': word_count}), 200, headers)\n\n            elif operation == 'parallel_sum':\n                data = request_json.get('data', &#91;])\n                result = my_rust_extension.parallel_sum(data)\n                return (jsonify({'sum': result}), 200, headers)\n\n        return (jsonify({'error': 'Invalid request'}), 400, headers)\n\n    except Exception as e:\n        return (jsonify({'error': str(e)}), 500, headers)\n\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"08\">Troubleshooting<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Common Issues and Solutions<\/h3>\n\n\n\n<p><strong>1. Rust Extension Build Errors<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code># Problem: \"error: Microsoft Visual C++ 14.0 is required\"\n# Solution (Windows):\nwinget install Microsoft.VisualStudio.2022.BuildTools\n\n# Problem: \"cannot find -lpython3.11\"\n# Solution (Linux):\nsudo apt-get install python3.11-dev\n\n# Problem: \"maturin not found\"\n# Solution:\npip install --upgrade maturin\n\n<\/code><\/pre>\n\n\n\n<p><strong>2. Import Errors<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code># Problem: ImportError: cannot import name 'my_rust_extension'\n# Solution: Rebuild the extension\n# Run in terminal:\nmaturin develop --release\n\n# Check if module is properly installed:\nimport sys\nprint(sys.path)\n\n<\/code><\/pre>\n\n\n\n<p><strong>3. Performance Issues<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code># Problem: Rust extension slower than expected\n# Solution: Ensure release build\nmaturin develop --release  # Not just 'maturin develop'\n\n# Problem: Large data serialization overhead\n# Solution: Use numpy arrays or implement custom serialization\nimport numpy as np\n\ndef optimize_data_transfer(data):\n    \"\"\"Convert data to numpy array for better performance\"\"\"\n    return np.array(data, dtype=np.float64)\n\n<\/code><\/pre>\n\n\n\n<p><strong>4. Mobile App Issues<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code># Problem: Streamlit app not mobile responsive\n# Solution: Add mobile-first CSS and test on various screen sizes\n\n# Problem: Capacitor build fails\n# Solution: Ensure correct web directory and server configuration\nnpx cap sync\nnpx cap run ios  # or android\n\n<\/code><\/pre>\n\n\n\n<p><strong>5. Memory Issues<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code># Problem: Out of memory with large datasets\n# Solution: Process data in chunks\n\ndef process_large_dataset(data, chunk_size=10000):\n    \"\"\"Process large dataset in chunks to avoid memory issues\"\"\"\n    results = &#91;]\n    for i in range(0, len(data), chunk_size):\n        chunk = data&#91;i:i + chunk_size]\n        if RUST_AVAILABLE:\n            result = my_rust_extension.parallel_sum(chunk)\n        else:\n            result = sum(chunk)\n        results.append(result)\n    return sum(results)\n\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Performance Optimization Tips<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Use Release Builds<\/strong>: Always use <code>maturin develop --release<\/code> for production<\/li>\n\n\n\n<li><strong>Minimize Python-Rust Boundaries<\/strong>: Process data in bulk rather than individual items<\/li>\n\n\n\n<li><strong>Leverage Parallelism<\/strong>: Use Rust&#8217;s <code>rayon<\/code> for CPU-intensive tasks<\/li>\n\n\n\n<li><strong>Cache Results<\/strong>: Use Streamlit&#8217;s <code>@st.cache_data<\/code> decorator for expensive computations<\/li>\n\n\n\n<li><strong>Profile Your Code<\/strong>: Use <code>cProfile<\/code> for Python and <code>cargo flamegraph<\/code> for Rust<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Testing<\/h3>\n\n\n\n<p>Create <code>test_integration.py<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>import pytest\nimport my_rust_extension\nimport numpy as np\n\ndef test_fibonacci():\n    \"\"\"Test Fibonacci calculation\"\"\"\n    assert my_rust_extension.fast_fibonacci(0) == 0\n    assert my_rust_extension.fast_fibonacci(1) == 1\n    assert my_rust_extension.fast_fibonacci(10) == 55\n\ndef test_parallel_sum():\n    \"\"\"Test parallel sum functionality\"\"\"\n    data = &#91;1.0, 2.0, 3.0, 4.0, 5.0]\n    result = my_rust_extension.parallel_sum(data)\n    assert result == 15.0\n\ndef test_word_count():\n    \"\"\"Test word counting\"\"\"\n    text = \"hello world hello\"\n    result = my_rust_extension.fast_word_count(text)\n    assert result&#91;\"hello\"] == 2\n    assert result&#91;\"world\"] == 1\n\ndef test_moving_average():\n    \"\"\"Test moving average calculation\"\"\"\n    data = &#91;1.0, 2.0, 3.0, 4.0, 5.0]\n    result = my_rust_extension.fast_moving_average(data, 3)\n    expected = &#91;2.0, 3.0, 4.0]  # 3-point moving average\n    np.testing.assert_array_almost_equal(result, expected)\n\nif __name__ == \"__main__\":\n    pytest.main(&#91;__file__])\n\n<\/code><\/pre>\n\n\n\n<p>Run tests with:<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>pip install pytest<br>python -m pytest test_integration.py -v<\/code><\/pre>\n\n\n\n<p>This comprehensive guide provides everything needed to create high-performance web and mobile applications using Python, Rust, and Streamlit. The combination offers the best of all worlds: Python&#8217;s ecosystem, Rust&#8217;s performance, and Streamlit&#8217;s rapid development capabilities.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Summary:<\/h2>\n\n\n\n<p>Python + Rust + Streamlit integration combines Python&#8217;s rich ecosystem with Rust&#8217;s high-performance computing and Streamlit&#8217;s rapid web development capabilities. This powerful combination delivers 10-100x performance improvements while maintaining Python&#8217;s ease of use for data science and machine learning applications. Organizations can build responsive, interactive dashboards and real-time applications in weeks rather than months, reducing development time by 50-70% and infrastructure costs by 30-60%. The technology stack is ideal for financial services, healthcare, manufacturing, and research sectors requiring fast data processing, real-time analytics, and user-friendly interfaces with production-ready scalability.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83c\udfaf Key Points<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">1. <strong>\ud83d\ude80 Exceptional Performance Gains<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>10-100x faster<\/strong> computational operations compared to pure Python<\/li>\n\n\n\n<li><strong>Sub-millisecond response times<\/strong> for real-time applications<\/li>\n\n\n\n<li><strong>Parallel processing capabilities<\/strong> utilizing all CPU cores efficiently<\/li>\n\n\n\n<li>Memory-safe operations preventing crashes and security vulnerabilities<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">2. <strong>\u26a1 Rapid Development &amp; Deployment<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>50-70% faster development<\/strong> compared to traditional web frameworks<\/li>\n\n\n\n<li><strong>Single codebase<\/strong> for frontend and backend logic<\/li>\n\n\n\n<li><strong>Automatic UI generation<\/strong> with Streamlit eliminates HTML\/CSS\/JavaScript complexity<\/li>\n\n\n\n<li><strong>Minutes to deploy<\/strong> from local development to cloud production<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">3. <strong>\ud83d\udcb0 Significant Cost Reduction<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>30-60% lower infrastructure costs<\/strong> through efficient resource utilization<\/li>\n\n\n\n<li><strong>Reduced server requirements<\/strong> handling more users per instance<\/li>\n\n\n\n<li><strong>Minimal additional training<\/strong> leveraging existing Python expertise<\/li>\n\n\n\n<li><strong>Lower maintenance overhead<\/strong> with fewer bugs and performance issues<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">4. <strong>\ud83c\udfe2 Enterprise-Ready Applications<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Production scalability<\/strong> from prototype to millions of users<\/li>\n\n\n\n<li><strong>Cloud-native deployment<\/strong> on AWS, Google Cloud, Azure, and Heroku<\/li>\n\n\n\n<li><strong>Security compliance<\/strong> with GDPR, HIPAA, and SOX requirements<\/li>\n\n\n\n<li><strong>Real-time monitoring<\/strong> and performance optimization capabilities<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">5. <strong>\ud83c\udfaf Ideal Use Cases &amp; Industries<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Financial Services<\/strong>: High-frequency trading, risk analysis, fraud detection<\/li>\n\n\n\n<li><strong>Healthcare<\/strong>: Genomic analysis, medical imaging, clinical trials<\/li>\n\n\n\n<li><strong>Manufacturing<\/strong>: IoT sensor processing, predictive maintenance<\/li>\n\n\n\n<li><strong>Research<\/strong>: Scientific computing, data visualization, collaborative tools<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">6. <strong>\ud83d\udee0\ufe0f Technical Implementation Advantages<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>PyO3 &amp; Maturin<\/strong> provide seamless Python-Rust integration<\/li>\n\n\n\n<li><strong>Type safety<\/strong> from Rust prevents runtime errors and improves reliability<\/li>\n\n\n\n<li><strong>WebAssembly support<\/strong> for browser-based high-performance computing<\/li>\n\n\n\n<li><strong>Comprehensive ecosystem<\/strong> with testing, profiling, and deployment tools<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">\ud83d\udcc8 <strong>Bottom Line Impact<\/strong><\/h3>\n\n\n\n<p>Transform your data applications with this proven technology stack that delivers enterprise performance at startup speed, reducing both development time and operational costs while providing superior user experiences.<\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This highlights the revolutionary impact of combining Python + Rust + Streamlit technologies, emphasizing the dramatic performance gains (10-100x), development efficiency (50-70% faster), cost savings (30-60% reduction), and the ultimate benefit of building enterprise-grade applications in weeks rather than months with minimal complexity.<\/p>\n","protected":false},"author":1,"featured_media":7942,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[15,18,13,1],"tags":[],"class_list":["post-7940","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ai","category-education","category-quantum-and-u","category-uncategorized"],"aioseo_notices":[],"featured_image_src":"https:\/\/meta-quantum.today\/wp-content\/uploads\/2025\/08\/Python-Rust-Streamlit-Complete-Integration-Guide.jpg","featured_image_src_square":"https:\/\/meta-quantum.today\/wp-content\/uploads\/2025\/08\/Python-Rust-Streamlit-Complete-Integration-Guide.jpg","author_info":{"display_name":"coffee","author_link":"https:\/\/meta-quantum.today\/?author=1"},"rbea_author_info":{"display_name":"coffee","author_link":"https:\/\/meta-quantum.today\/?author=1"},"rbea_excerpt_info":"This highlights the revolutionary impact of combining Python + Rust + Streamlit technologies, emphasizing the dramatic performance gains (10-100x), development efficiency (50-70% faster), cost savings (30-60% reduction), and the ultimate benefit of building enterprise-grade applications in weeks rather than months with minimal complexity.","category_list":"<a href=\"https:\/\/meta-quantum.today\/?cat=15\" rel=\"category\">AI<\/a>, <a href=\"https:\/\/meta-quantum.today\/?cat=18\" rel=\"category\">Education<\/a>, <a href=\"https:\/\/meta-quantum.today\/?cat=13\" rel=\"category\">Quantum and U<\/a>, <a href=\"https:\/\/meta-quantum.today\/?cat=1\" rel=\"category\">Uncategorized<\/a>","comments_num":"0 comments","_links":{"self":[{"href":"https:\/\/meta-quantum.today\/index.php?rest_route=\/wp\/v2\/posts\/7940","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meta-quantum.today\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meta-quantum.today\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meta-quantum.today\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/meta-quantum.today\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=7940"}],"version-history":[{"count":5,"href":"https:\/\/meta-quantum.today\/index.php?rest_route=\/wp\/v2\/posts\/7940\/revisions"}],"predecessor-version":[{"id":7946,"href":"https:\/\/meta-quantum.today\/index.php?rest_route=\/wp\/v2\/posts\/7940\/revisions\/7946"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/meta-quantum.today\/index.php?rest_route=\/wp\/v2\/media\/7942"}],"wp:attachment":[{"href":"https:\/\/meta-quantum.today\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=7940"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meta-quantum.today\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=7940"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meta-quantum.today\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=7940"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}