File size: 6,554 Bytes
4cbfa17 3d5a2a0 4cbfa17 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
---
license: mit
title: python_to_streamlit_convertor
sdk: streamlit
emoji: π
colorFrom: green
colorTo: gray
sdk_version: 1.51.0
---
# Python β Streamlit Converter Pro
A powerful, production-ready tool that converts Python scripts and Jupyter Notebooks into fully functional Streamlit applications. Handles large files, preserves comments and markdown, and provides multiple conversion strategies.
## β¨ Features
### Core Capabilities
- **Multi-Format Support**: Convert `.py` files and `.ipynb` notebooks
- **Large File Handling**: Efficiently processes files up to 5MB+ with optimized algorithms
- **Comment Preservation**: All comments, docstrings, and inline documentation are preserved
- **Markdown Support**: Notebook markdown cells are converted to commented Python code
- **Batch Processing**: Upload ZIP archives to convert multiple files at once
### Conversion Strategies
1. **Hybrid Mode (Recommended)**: Combines AST parsing with regex patterns
- Best balance of accuracy and performance
- Handles complex code structures
- Preserves formatting and comments
2. **AST Mode (Precise)**: Pure abstract syntax tree transformation
- Deep understanding of code structure
- Best for complex transformations
- Preserves all code semantics
3. **Regex Mode (Fast)**: Pattern-based matching
- Fastest for very large files
- Good for simple conversions
- Efficient memory usage
4. **Auto Mode**: Automatically selects the best strategy based on file size
### What Gets Converted?
| Original Code | Streamlit Equivalent |
|--------------|---------------------|
| `print(x)` | `st.write(x)` |
| `display(df)` | `st.dataframe(df)` |
| `df.head()` / `df.tail()` | `st.dataframe(df.head())` |
| `plt.show()` | `st.pyplot(plt.gcf())` |
| `fig.show()` (Plotly) | `st.plotly_chart(fig)` |
| Markdown cells | Commented markdown |
| All comments | Preserved |
## π Installation
1. Clone or download this repository
2. Install dependencies:
```bash
pip install -r Requirements.txt
```
## π Usage
### Running the Application
```bash
streamlit run app.py
```
The application will open in your default web browser.
### Basic Workflow
1. **Upload Files**: Use the sidebar to upload Python files or Jupyter notebooks
- Individual files: Upload one or more files directly
- ZIP archive: Upload a ZIP containing multiple files
2. **Configure Settings** (Optional):
- Choose conversion strategy (Hybrid recommended)
- Set large file threshold
- Enable/disable main guard
- Toggle comment preservation
3. **Review & Download**:
- View original and converted code side-by-side
- Check conversion report for details
- Download the converted Streamlit app
### Advanced Settings
- **Conversion Strategy**: Choose how the code is analyzed and converted
- **Large File Threshold**: Files above this size (in KB) use optimized processing
- **Main Guard**: Adds `if __name__ == '__main__':` wrapper for safer execution
- **Preserve Comments**: Keep all comments and docstrings in the output
## π― Use Cases
- **Data Science Projects**: Convert Jupyter notebooks with visualizations to interactive Streamlit dashboards
- **Script Migration**: Transform existing Python scripts into web applications
- **Batch Conversion**: Process entire project folders at once
- **Prototyping**: Quickly create Streamlit apps from existing code
## π§ Technical Details
### Architecture
- **AST-Based Transformation**: Uses Python's `ast` module for structural analysis
- **Regex Fallback**: Pattern matching for edge cases and large files
- **Hybrid Approach**: Combines both methods for optimal results
- **Error Recovery**: Graceful fallbacks when parsing fails
### Performance
- Handles files up to 5MB+ efficiently
- Chunked processing for large files
- Caching for repeated conversions
- Memory-efficient algorithms
### Limitations
- Does not execute code (safe conversion only)
- Complex interactive widgets (e.g., `ipywidgets`) require manual conversion
- Some edge cases in very complex code may need manual adjustment
- Manual review recommended before production deployment
## π Example
### Input (Jupyter Notebook Cell):
```python
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('data.csv')
print(f"Dataset has {len(df)} rows")
display(df.head())
plt.figure(figsize=(10, 6))
plt.plot(df['x'], df['y'])
plt.show()
```
### Output (Streamlit App):
```python
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
st.set_page_config(
page_title='Converted App',
layout='wide'
)
st.title(' Converted Streamlit App')
df = pd.read_csv('data.csv')
st.write(f"Dataset has {len(df)} rows")
st.dataframe(df.head())
plt.figure(figsize=(10, 6))
plt.plot(df['x'], df['y'])
st.pyplot(plt.gcf())
```
## π οΈ Development
### Project Structure
```
python_to_full_streamlit/
βββ app.py # Main Streamlit application
βββ Requirements.txt # Python dependencies
βββ README.md # This file
```
### Key Components
1. **HybridConverter**: Main conversion engine with multiple strategies
2. **CommentPreservingTransformer**: AST transformer that preserves code structure
3. **extract_code_from_notebook**: Enhanced notebook processing with markdown support
4. **File Processing**: Cached, efficient file handling with error recovery
## π€ Contributing
This is a production-ready converter. Improvements welcome for:
- Additional conversion patterns
- Performance optimizations
- Edge case handling
- UI/UX enhancements
## π License
This project is provided as-is for converting Python code to Streamlit applications.
## π‘ Tips
- Use **Hybrid mode** for best results on most files
- Enable **comment preservation** to maintain documentation
- For very large files (>1MB), consider using **Regex mode**
- Always review converted code before deployment
- Test the generated Streamlit app with sample data
## π Troubleshooting
**Issue**: Conversion fails on a file
- **Solution**: Try a different conversion mode (AST vs Regex)
- Check if the file has syntax errors
- Verify the file is valid Python/Jupyter format
**Issue**: Comments are missing
- **Solution**: Enable "Preserve Comments" in advanced settings
- Use AST or Hybrid mode instead of Regex
**Issue**: Large file processing is slow
- **Solution**: Increase the large file threshold
- Use Regex mode for very large files
- Process files individually instead of in ZIP
---
**Made with β€οΈ for the Streamlit community** |